15 SpringSecurity 集成thymeleaf
此项目是在springsecurity-12-database-authorization-method 的基础上进行
复制springsecurity-12-database-authorization-method 并重命名为springsecurity-13-thymeleaf
15.1 添加thymeleaf依赖
|
org.springframework.boot
spring-boot-starter-thymeleaf
15.2 修改application.yml
加入thymeleaf的配置
| spring:
thymeleaf:
cache: false # 不使用缓存check-template: true # 检查thymeleaf模板是否存在 |
---|
15.3 idea 添加thymeleaf模板
【File】—》【Settings…】
模板名称thymeleaf ,扩展名html,具体内容如下:
|
#[[ E N D END END]]#
简要说明:
#[[ T i t l e Title Title]]# #[[ E N D END END]]# 这两处的作用是,当你新建一个模板页面时,在 |
---|
15.4 新建LoginController
| @Controller
@RequestMapping(“/login”)
public class LoginController {
_/**
* 跳转到登陆页面
*/
_@RequestMapping(“/toLogin”)
public String toLogin(){
return “login”;
}
} |
---|
15.5 创建thymeleaf文件login.html
在templates下面创建login.html,使用模板创建
|
登录页面
用户名:
密码:
登录
15.7 修改安全配置文件WebSecurityConfig
修改后如下:
| @EnableGlobalMethodSecurity(prePostEnabled = true)
//@Configuration
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//设置登陆方式
http.formLogin()//使用用户名和密码的登陆方式
.usernameParameter(“uname”) //页面表单的用户名的name
.passwordParameter(“pwd”)//页面表单的密码的name
.loginPage(“/login/toLogin”) //自己定义登陆页面的地址
.loginProcessingUrl(“/login/doLogin”)//配置登陆的url
.successForwardUrl(“/index/toIndex”) //登陆成功跳转的页面
.failureForwardUrl(“/login/toLogin”)//登陆失败跳转的页面
.permitAll(); //放行和登陆有关的url,别忘了写这个
//配置退出方式
http.logout()
.logoutUrl(“/logout”)
.logoutSuccessUrl(“/login/toLogin”)
.permitAll();/放行和退出有关的url,别忘了写这个
//配置路径拦截 的url的匹配规则
http.authorizeRequests()
//任何路径要求必须认证之后才能访问
.anyRequest().authenticated();
// 禁用csrf跨站请求攻击 后面可以使用postman工具测试,注意要禁用csrf
http.csrf().disable();
}
} |
---|
15.8 创建IndexController
| @Controller
@RequestMapping(“/index”)
public class IndexController {
_/**
* 登录成功后进入主页
*/
_@RequestMapping(“/toIndex”)
public String toIndex(){
return “main”;
}
} |
---|
15.9 创建thymeleaf文件main.html
在templates下面创建main.html
|
系统首页
退出
15.10 修改Studentcontroller
修改后如下:
| @Controller
@Slf4j
@RequestMapping(“/student”)
public class StudentController {
@GetMapping(“/query”)