自定义登录页面
这里出现一个问题,记录一下:
1.如果我们loginPage方法里面写的是某个controller的uri,那么我们就应该在对应的uri那里返回一个页面
同时我们需要导入模板引擎的依赖,否则识别不了这个页面,会报404。同时这是login页面位于templates下的做法。
2.如果我们的login页面放在static下,那么我们只需要在loginPage方法里写上login.html的位置即可,如“/login.html”
首先我们准备好一个login.html
页面,一般来说我是喜欢将页面放在templates
下的,但是也有人放在static
下,同样的,就这两种情况,SpringSecurity
也给出了不同的实现方法。
<!-- 简陋的login页面 -->
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/user/login" method="post">
用户名<input type="text" name="username"/>
<br/>
密码<input type="text" name="password"/>
<br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
1、login
页面位于static
下
我们需要在自定义的配置类重写configure
方法,参数注意是HttpSecurity
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 自定义自己编写的登录页面
.loginPage("/login.html") // 登录页面设置
.loginProcessingUrl("/user/login") // 登录访问路径
.defaultSuccessUrl("/test/index").permitAll() // 登录成功后的跳转路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/login.html").permitAll() // 设置哪些路径可以直接访问,不需要认证
.anyRequest().authenticated()
.and().csrf().disable(); // 关闭csrf防护
}
此时我们无权限访问/test/index
这个路径,SpringSecurity
就会默认帮我们跳转到login.html
页面
输入密码验证
验证成功
2、login
页面位于templates
下
首先导入我们的模板引擎thymeleaf
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
依然是重写我们的configure
方法
此时注意loginPage
的参数应该为我们自定义的某个跳转页面的controller
内部的方法
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin() // 自定义自己编写的登录页面
.loginPage("/test/tologin") // 登录页面设置
.loginProcessingUrl("/user/login") // 登录访问路径
.defaultSuccessUrl("/test/index").permitAll() // 登录成功后的跳转路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/login.html").permitAll() // 设置哪些路径可以直接访问,不需要认证
.anyRequest().authenticated()
.and().csrf().disable(); // 关闭csrf防护
}
自定义controller
@Controller
@RequestMapping("/test")
public class LoginController {
@RequestMapping("/index")
@ResponseBody
public String index(){
return "hello index";
}
@RequestMapping("/hello")
@ResponseBody
public String hello(){
return "new hello";
}
@RequestMapping("tologin")
public String tologin(){
return "login";
}
}
注意,我们先将模板引擎给注释掉
此时return "login"
此时报了一个错
此时将模板引擎依赖取消注释
发现可以识别到login
页面了
这时我们继续访问/test/index
,发现也能自动跳转到login页面,同时url变成了/test/tologin
同样的这种方式也行。