spring退出登录代码
时间: 2023-05-14 22:04:32 浏览: 76
以下是一个简单的 Spring 退出登录的代码示例:
```
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
```
这个代码片段会从 Spring Security 上下文中获取当前用户的认证信息,然后使用 SecurityContextLogoutHandler 类来执行退出登录操作。最后,它会重定向到登录页面,并在 URL 中添加一个参数来指示用户已经成功退出登录。
相关问题
spring编写一个退出登录代码
以下是一个简单的 Spring 退出登录代码示例:
```
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
new SecurityContextLogoutHandler().logout(request, response, auth);
}
return "redirect:/login?logout";
}
```
这个代码段会将当前用户从 Spring Security 上下文中注销,并重定向到登录页面。
spring退出登录如何写
Spring退出登录可以通过以下步骤实现:
1. 在Spring Security配置文件中,配置logout()方法,例如:
@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")
.logoutSuccessUrl("/login")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID");
}
}
2. 在页面中添加退出登录的链接或按钮,例如:
<a href="/logout">退出登录</a>
3. 当用户点击退出登录链接或按钮时,Spring Security会自动调用logout()方法,清除用户的认证信息,使其退出登录。
注意:以上代码仅供参考,具体实现方式可能因项目而异。