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. 【Vulfocus解题系列】手把手教你使用Vulfocus公开靶场对Apache Log4j2远程命令执行漏洞复现

    前言 关于这个漏洞,啥都不用说了,直接发车. 工具下载 JNDIExploit:https://github.com/0x727/JNDIExploit 复现过程 启动靶场环境 直接用vulfocus ...

  2. PostgreSql数据库安全加固

    1.确保通过"主机" TCP / IP套接字登录已正确配置 描述 大量的身份验证方法可用于使用 TCP / IP套接字,包括: ?信任 ? 拒绝 ?md5 ?scram-sha-2 ...

  3. Excel如何使用VLOOKUP函数多条件匹配查找数据

    一.对应源数据如sheet6所示,对应需查找的数据如sheet7所示 二.在sheet6中添加一列辅助列 三.在sheet7对应位置插入vlookup函数 四.最终结果如下图所示

  4. Spring框架源码干货分享之三级缓存和父子工厂

    记录并分享一下本人学习spring源码的过程,有什么问题或者补充会持续更新.欢迎大家指正! 环境: spring5.X + idea 建议:学习过程中要开着源码一步一步过 Spring中对象的创建宏观 ...

  5. String类源码分析

    1.String类注释说明 /** * The {@code String} class represents character strings. All * string literals in ...

  6. [BUUCTF]REVERSE——刮开有奖

    刮开有奖 附件 步骤: 例行检查,无壳,32位程序 32位ida载入,shift+f12检索程序里的字符串,看到了一个base64加密的特征字符串,猜想这题用到了base64加密 从main函数开始看 ...

  7. Mac brew安装MySQL8.0.18后忘记密码(重置密码篇)

    前要:MySQL8后密码要求很高,要有大小写字母和数字特殊字符,导致自己忘记以前配置的密码 一.跳过mysql的密码认证,修改配置文件my.cnf $ ls /usr/local/etc/my.cnf ...

  8. CSS 常用颜色代号

    常用颜色代号一览表:http://www.divcss5.com/html/h636.shtml   #000000   #2F0000   #600030   #460046   #28004D   ...

  9. lightgallery 使用

    用途 图片预览,支持多图片滑动预览 git 地址 https://github.com/sachinchoolur/lightgallery.js 代码 # idnex.html <script ...

  10. ACwing895. 最长上升子序列

    题目: 给定一个长度为N的数列,求数值严格单调递增的子序列的长度最长是多少. 输入格式: 第一行包含整数N. 第二行包含N个整数,表示完整序列. 输出格式: 输出一个整数,表示最大长度. 数据范围: ...