springboot实现退出功能完整代码
时间: 2023-11-11 10:04:41 浏览: 45
以下是Spring Boot实现退出功能的完整代码:
1. 创建LogoutController类
```java
@Controller
public class LogoutController {
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
request.getSession().invalidate(); // 清空session
return "redirect:/login"; // 重定向到登录页面
}
}
```
2. 在登录页面添加退出按钮
```html
<form action="/logout" method="get">
<button type="submit">退出</button>
</form>
```
3. 配置Spring Security
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/home").permitAll()
.and()
.logout().logoutUrl("/logout").permitAll(); // 配置退出功能
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
```
在上面的代码中,我们配置了Spring Security的登录和退出功能。在configure(HttpSecurity http)方法中,我们使用了formLogin()方法配置了登录页面和默认成功页面,并使用了logout()方法配置了退出URL。
4. 运行应用程序
现在,您可以运行应用程序并访问登录页面。在登录后,您将看到一个退出按钮。单击按钮后,您将被重定向到登录页面,并且您的会话将被清除。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)