1.前言

以前开发一直使用 springMVC模式开发 ,前端页面常使用 JSP  ,现在html5淘汰了 ,要么使用html ,要么使用vue ,

现在使用spring boot ,有必要总结一下 spring boot 对html 的操作 。

2.环境

spring boot   2.1.6.RELEASE

3.操作

(1)下载依赖

  <!--spring security 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!--访问静态资源-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

完整pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>security-5500</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>security-5500</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<!--spring security 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <!--访问静态资源-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

(2)目录结构

 (3)resources 里的static包是存放静态资源的 ,static下面新建一个img包 ,里面放一个图片文件

启动后,直接输入网址 http://localhost:5500/img/xx.png    即可访问  ,不会被security拦截

【只要pom加了security依赖包 ,将默认启动security,默认账户名 为 user

密码是打印台打印的 随机数

(4)使用了thymeleaf 模板 ,那么html文件必须放在 路径为 resources/templates 的文件夹里面

否则spring boot 扫描不到文件 ,当然,也是可以修改的需要在application配置文件里修改

完整的pom.xml

spring.application.name=security-5500
# 应用服务web访问端口
server.port=5500
#配置security登录账户密和密码 ,不配置则默认账户是user,密码是随机生成的字符串,打印在启动栏中
#spring.security.user.name=11
#spring.security.user.password=22
#
##
##
##
## Enable template caching.
#spring.thymeleaf.cache=true
## Check that the templates location exists.
#spring.thymeleaf.check-template-location=true
## Content-Type value.
##spring.thymeleaf.content-type=text/html
## Enable MVC Thymeleaf view resolution.
#spring.thymeleaf.enabled=true
## Template encoding.
#spring.thymeleaf.encoding=utf-8
## Comma-separated list of view names that should be excluded from resolution.
#spring.thymeleaf.excluded-view-names=
## Template mode to be applied to templates. See also StandardTemplateModeHandlers.
#spring.thymeleaf.mode=HTML5
## Prefix that gets prepended to view names when building a URL.
##设置html文件位置
#spring.thymeleaf.prefix=classpath:/templates/
## Suffix that gets appended to view names when building a URL.
#spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

(5)新建html文件

新建一个名为 index.html的文件 ,使用了 thymeleaf 模板的语法  th:href="@{/home}" 进行跳转  ,这个 /home路径是虚拟路径 ,需要设置的,待会展示

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
你好 ,世界 ,2333
<p>点击 <a th:href="@{/home}">我</a> 去home.html页面</p> </body>
</html>

新建一个名为 home.html的文件

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8">
<title>security首页</title>
</head>
<body>
<h1>Welcome!你好,世界</h1> <p>Click <a th:href="@{/hai}">here</a> to see a greeting.</p>
</body>
</html>

新建一个名为 hai.html的文件

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8">
<title>hai文件</title>
</head>
<body>
你好呀世界,成功登录进来了
</body>
</html>

新建一个名为 kk.html的文件,用于测试html文件获取静态文件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>kk</title>
</head>
<body>
<img src="img/xx.png" alt="">
</body>
</html>

还需要新建一个login.html文件 ,待会用来作为security的自定义登录页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security自定义</title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
<br>
lalallalalal啊是德国海
</body>
</html>

(6)设置虚拟路径用于访问html文件 【springMVC的视图设置一样,但是,不需要配置,直接引入 thymeleaf 即可使用】

在controller层

package com.example.security5500.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView; @Controller
public class MVCController { @RequestMapping("/home")
public String home() {
return "home";
} @RequestMapping("/login")
public String login(){
return "login";
} @RequestMapping("/hai")
public String hai() {
return "hai";
} @RequestMapping("/")
public String index() {
return "index";
} @RequestMapping("kk")
public String kk() {
return "kk";
} //心得,index.html默认是首页,当没有指定路径 / 是哪个文件时 index.html将默认是根路径/ }

(7)测试

启动类没有改变 ,默认即可

启动程序,访问  http://localhost:5500/    将会弹出security页面

输入默认账户和密码 即可跳转index.html页面

点击 “我” ,可跳转到home.html页面

【注意 ,必须配置好了 html文件的虚拟路径

thymeleaf 模板语法

才可以使用,否则提示404

好了,到了这里已经完整的解释了 spring boot 怎么使用html作为前端页面开发

(8)修改security的拦截规则

新建 文件  WebSecurityConfig

源码

package com.example.security5500.securityConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { //定义了哪些URL路径应该被保护,哪些不应该。具体来说,“/”和“/ home”路径被配置为不需要任何身份验证。所有其他路径必须经过身份验证。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//设置不拦截页面,可直接通过,路径访问 "/", "/index", "/home" 则不拦截
.authorizeRequests()
.antMatchers("/", "/index", "/home").permitAll()
.anyRequest().authenticated()
.and()
//设置自定义登录页面
.formLogin()
.loginPage("/login")
.permitAll()
.and()
//设置自定义登出页面
.logout()
// .logoutUrl("/mylogout")
.permitAll();
} }

再次启动工程

访问  http://localhost:5500/  可直接进入页面了 ,不需要security 验证

访问  http://localhost:5500/hai 会被security拦截  ,将进入配置的自定义登录页面

登录后才可以跳转 hai.html

(9)登出

登出 security 网址访问 http://localhost:5500/login?logout  ,点击蓝色大按钮即可

4.如何修改security的账户与密码?

(1)方法一 :

application配置文件添加属性

#配置security登录账户密和密码  ,不配置则默认账户是user,密码是随机生成的字符串,打印在启动栏中
spring.security.user.name=11
spring.security.user.password=22

完整源码

spring.application.name=security-5500
# 应用服务web访问端口
server.port=5500
#配置security登录账户密和密码 ,不配置则默认账户是user,密码是随机生成的字符串,打印在启动栏中
spring.security.user.name=11
spring.security.user.password=22
#
##
##
##
## Enable template caching.
#spring.thymeleaf.cache=true
## Check that the templates location exists.
#spring.thymeleaf.check-template-location=true
## Content-Type value.
##spring.thymeleaf.content-type=text/html
## Enable MVC Thymeleaf view resolution.
#spring.thymeleaf.enabled=true
## Template encoding.
#spring.thymeleaf.encoding=utf-8
## Comma-separated list of view names that should be excluded from resolution.
#spring.thymeleaf.excluded-view-names=
## Template mode to be applied to templates. See also StandardTemplateModeHandlers.
#spring.thymeleaf.mode=HTML5
## Prefix that gets prepended to view names when building a URL.
##设置html文件位置
#spring.thymeleaf.prefix=classpath:/templates/
## Suffix that gets appended to view names when building a URL.
#spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

(2)方法二:

进入刚才配置security规则的文件 WebSecurityConfig  ,直接将用户设置在内存中

 //将单个用户设置在内存中  ,在这里设置了用户信息,那么application的登录信息则不需要写
@Bean
@Override
protected UserDetailsService userDetailsService() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
UserDetails user = User
.withUsername("user")
.password(encoder.encode("11"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}

完整源码

package com.example.security5500.securityConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { //定义了哪些URL路径应该被保护,哪些不应该。具体来说,“/”和“/ home”路径被配置为不需要任何身份验证。所有其他路径必须经过身份验证。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//设置不拦截页面,可直接通过,路径访问 "/", "/index", "/home" 则不拦截
.authorizeRequests()
.antMatchers("/", "/index", "/home").permitAll()
.anyRequest().authenticated()
.and()
//设置自定义登录页面
.formLogin()
.loginPage("/login")
.permitAll()
.and()
//设置自定义登出页面
.logout()
// .logoutUrl("/mylogout")
.permitAll();
} //将单个用户设置在内存中 ,在这里设置了用户信息,那么application的登录信息则不需要写
@Bean
@Override
protected UserDetailsService userDetailsService() {
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
UserDetails user = User
.withUsername("user")
.password(encoder.encode("11"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
} }

(3)方法三:

仍然是修改 配置security规则的文件 WebSecurityConfig

 //可以使用以下配置在内存中进行注册公开内存的身份验证{@link UserDetailsService}:
// 在内存中添加 user 和 admin 用户
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication().withUser("user").password("11").roles("USER").and()
.withUser("admin").password("11").roles("USER", "ADMIN");
}
// 将 UserDetailsService 显示为 Bean
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
}

完整源码

package com.example.security5500.securityConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager; @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { //定义了哪些URL路径应该被保护,哪些不应该。具体来说,“/”和“/ home”路径被配置为不需要任何身份验证。所有其他路径必须经过身份验证。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
//设置不拦截页面,可直接通过,路径访问 "/", "/index", "/home" 则不拦截
.antMatchers("/", "/index", "/home").permitAll()
.anyRequest().authenticated()
.and()
//设置自定义登录页面
.formLogin()
.loginPage("/login")
.permitAll()
.and()
//设置自定义登出页面
.logout()
// .logoutUrl("/mylogout")
.permitAll(); } //可以使用以下配置在内存中进行注册公开内存的身份验证{@link UserDetailsService}:
// 在内存中添加 user 和 admin 用户
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication().withUser("user").password("11").roles("USER").and()
.withUser("admin").password("11").roles("USER", "ADMIN");
}
// 将 UserDetailsService 显示为 Bean
@Bean
@Override
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Bean
public static NoOpPasswordEncoder passwordEncoder() {
return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
} }

注意:

@Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

这一个方法是用来设置加密方式的额 ,NoOpPasswordEncoder是不加密的意思,虽然不加密,但是少了会报错,

处理该加密方式外还有  BCryptPasswordEncoder 、SCryptPasswordEncoder 等 ,详细可查看我的其他随笔

【注意: 三个方法任选一个都可以修改登录账号密码,但是,方法2和3不能同时使用 ,如果WebSecurityConfig 和application 文件 都写上 ,会导致application配置文件设置的账号密码失效,仅WebSecurityConfig内的方法设置的有效】

spring boot + thymeleaf +security自定义规则 的简单使用的更多相关文章

  1. Spring Boot Thymeleaf 使用详解

    在上篇文章Spring Boot (二):Web 综合开发中简单介绍了一下 Thymeleaf,这篇文章将更加全面详细的介绍 Thymeleaf 的使用.Thymeleaf 是新一代的模板引擎,在 S ...

  2. spring boot + thymeleaf 3 国际化

    在给spring boot 1.5.6 + thymeleaf 3进行国际化时,踩了一个坑(其实不止一个). 现象: 看到了吧, 就是取值的key, 后面被加了_en_US 或 _zh_CN, 以及前 ...

  3. spring boot + Thymeleaf开发web项目

    "Spring boot非常适合Web应用程序开发.您可以轻松创建自包含的HTTP应用.web服务器采用嵌入式Tomcat,或者Jetty等.大多数情况下Web应用程序将使用 spring- ...

  4. Spring Boot Thymeleaf 实现国际化

    开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了.SpringBoot支持如下页面模板语言 Thymeleaf FreeMarker Vel ...

  5. Spring Boot 快速入门 史上最简单

    1.Spring Boot 概述 Spring Boot 是所有基于 Spring 开发的项目的起点.Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的 ...

  6. spring boot + thymeleaf 乱码问题

    spring boot + thymeleaf 乱码问题 hellotrms 发布于 2017/01/17 15:27 阅读 1K+ 收藏 0 答案 1 开发四年只会写业务代码,分布式高并发都不会还做 ...

  7. spring boot / cloud (四) 自定义线程池以及异步处理@Async

    spring boot / cloud (四) 自定义线程池以及异步处理@Async 前言 什么是线程池? 线程池是一种多线程处理形式,处理过程中将任务添加到队列,然后在创建线程后自动启动这些任务.线 ...

  8. Spring boot+Thymeleaf+easyui集成:js创建组件页面报错

    开发工具:Ideal 使用场景:Demo 前提:       环境:Spring boot +Thymeleaf+easyui 引入thymeleaf模板引擎 <html lang=" ...

  9. spring boot: thymeleaf模板引擎使用

    spring boot: thymeleaf模板引擎使用 在pom.xml加入thymeleaf模板依赖 <!-- 添加thymeleaf的依赖 --> <dependency> ...

随机推荐

  1. 企业级BI是自研还是采购?

    企业级BI是自研还是采购? 上一篇<企业级BI为什么这么难做?>,谈到了企业级BI项目所具有的特殊背景,以及在"破局"方面的一点思考,其中谈论的焦点主要是在IT开发项目 ...

  2. Mybatis-plus报Invalid bound statement (not found)错误

    错误信息 org.springframework.security.authentication.InternalAuthenticationServiceException: Invalid bou ...

  3. 关于使用Topshelf创建服务

    目录 0. 背景说明 1. 使用Topshelf组件创建Windows服务 1.1 依赖Quartz.net实现定时任务 1.2 依赖于Topshelf创建服务类 1.3 log4net的配置文件lo ...

  4. Mysql资料 锁机制

    目录 一.简介 二.类型 三.操作 四.死锁 第一种情况 第二种情况 第三种情况 一.简介 数据库和操作系统一样,是一个多用户使用的共享资源.当多个用户并发地存取数据 时,在数据库中就会产生多个事务同 ...

  5. LuoguP6904 [ICPC2015 WF]Amalgamated Artichokes 题解

    Content 已知常数 \(p,a,b,c,d\),我们知道,第 \(k\) 天的股价公式为 \(price_k=p\times(\sin(a\times k+b)+\cos(c\times k+d ...

  6. Jquery监控audio单选框选中事件(实际通过click)

    $('input:radio[name="pathType"]').click(function(){ var checkValue = $('input:radio[name=& ...

  7. python 学生信息管理系统

    python与数据库的例子 初始化数据库 链接数据库创建库和表并插入数据 init.py import pymysql sql_base='create database school;' sql_t ...

  8. SpringBoot整合MQTT (使用官方demo)

    依赖 <dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse. ...

  9. UiPath RPA培训2021.4版本解读 (2021年5月)-RPA学习天地

    2021年5月26日Ui Path发布了新产品2021.4版本,我们来看看有什么新功能: 说明一下uipath的版本发布节奏: uipath的版本一般是每年发布2个版本,其中5月份发布的一般是FTS版 ...

  10. UDP&串口调试助手用法(1)

    一览 UDP 串口 常用 功能概述 概览 支持UDP通信协议: 广播.单播.组播 支持串口通信 配置了常用的配置,常用的进制转化: 2进制,8进制,10进制,和16进制之间的转换 配置了 计算器,加减 ...