springsecurity登录成功跳转
时间: 2023-06-28 11:13:16 浏览: 50
在Spring Security中,可以通过配置实现登录成功后的跳转,具体步骤如下:
1. 配置登录页面
在Spring Security的配置文件中,配置登录页面,例如:
```java
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll();
}
```
这里的`loginPage("/login")`表示登录页面的URL是`/login`,`.defaultSuccessUrl("/home")`表示登录成功后跳转到`/home`页面。
2. 配置登录成功处理器
在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")
.successHandler(loginSuccessHandler()) // 配置登录成功处理器
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
public AuthenticationSuccessHandler loginSuccessHandler(){
return new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
httpServletResponse.sendRedirect("/home"); // 登录成功后跳转到/home页面
}
};
}
}
```
这里的`successHandler(loginSuccessHandler())`表示在登录成功后调用一个名为`loginSuccessHandler`的Bean,该Bean是一个实现了`AuthenticationSuccessHandler`接口的类,在其`onAuthenticationSuccess`方法中实现登录成功后的跳转。
以上就是在Spring Security中实现登录成功后跳转的步骤。