引入模板依赖
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
定义登录页面 controller
@Controller
public class LoginController {
@RequestMapping("/login.html")
public String login() {
return "login";
}
}
在 templates 中定义登录界面
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h1>用户登录</h1>
<form method="post" th:action="@{/doLogin}">
用户名:<input name="uname" type="text"/><br>
密码:<input name="passwd" type="password"/><br>
<input type="submit" value="登录"/>
</form>
</body>
</html>
-
需要注意的是
-
登录表单 method 必须为
post
,action 的请求路径为/doLogin
-
用户名的 name 属性为
uname
-
密码的 name 属性为
passwd
-
-
配置 Spring Security 配置类
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.mvcMatchers("/login.html").permitAll()
.mvcMatchers("/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/doLogin")
.usernameParameter("uname")
.passwordParameter("passwd")
.successForwardUrl("/index") //forward 跳转 注意:不会跳转到之前请求路径
//.defaultSuccessUrl("/index") //redirect 重定向 注意:如果之前请求路径,会有优先跳转之前请求路径
.failureUrl("/login.html")
.and()
.csrf().disable();//这里先关闭 CSRF
}
}
successForwardUrl 、defaultSuccessUrl 这两个方法都可以实现成功之后跳转
-
successForwardUrl 默认使用
forward
跳转注意:不会跳转到之前请求路径
-
defaultSuccessUrl 默认使用
redirect
跳转注意:如果之前请求路径,会有优先跳转之前请求路径,可以传入第二个参数进行修改