springboot集成thymeleaf修改密码
时间: 2023-09-16 09:13:09 浏览: 48
首先,我们需要在 Spring Boot 项目中添加 Thymeleaf 和 Spring Security 的依赖。
```xml
<!-- Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
```
然后,我们需要创建一个修改密码的页面,比如说 `change-password.html`。
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>修改密码</title>
</head>
<body>
<h1>修改密码</h1>
<form method="post" th:action="@{/change-password}">
<div>
<label for="currentPassword">当前密码:</label>
<input type="password" id="currentPassword" name="currentPassword"/>
</div>
<div>
<label for="newPassword">新密码:</label>
<input type="password" id="newPassword" name="newPassword"/>
</div>
<div>
<label for="confirmPassword">确认密码:</label>
<input type="password" id="confirmPassword" name="confirmPassword"/>
</div>
<input type="submit" value="修改密码"/>
</form>
</body>
</html>
```
在这个页面中,我们定义了一个表单,包含当前密码、新密码和确认密码三个字段,以及一个提交按钮。
接着,我们需要创建一个 Controller,处理修改密码的请求。
```java
@Controller
public class PasswordController {
@GetMapping("/change-password")
public String changePasswordForm() {
return "change-password";
}
@PostMapping("/change-password")
public String changePassword(HttpServletRequest request, Model model) {
String currentPassword = request.getParameter("currentPassword");
String newPassword = request.getParameter("newPassword");
String confirmPassword = request.getParameter("confirmPassword");
// TODO: 校验密码是否正确,以及新密码和确认密码是否一致
// TODO: 更新密码
return "redirect:/logout";
}
}
```
在这个 Controller 中,我们定义了两个方法,一个用来展示修改密码的页面,一个用来处理修改密码的请求。在处理请求的方法中,我们首先获取当前密码、新密码和确认密码三个字段,然后校验当前密码是否正确,以及新密码和确认密码是否一致。如果校验通过,我们就可以更新密码了。最后,我们重定向到 `/logout`,让用户重新登录。
最后,我们需要在 Spring Security 中配置修改密码的页面和请求。
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/change-password").authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.permitAll();
}
}
```
在这个配置中,我们定义了 `/change-password` 请求需要认证,其他请求则不需要认证。同时,我们还定义了登录页面和登出请求的 URL。