要在WebSecurityConfig中的configure方法中配置登录
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/home").successHandler(new LoginSuccessHandle())
.permitAll()
重点在.successHandler
建立一个LoginSuccessHandle的类
class LoginSuccessHandle implements AuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException,ServletException {
Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
String path = request.getContextPath() ;
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
if (roles.contains("ROLE_ADMIN")){
response.sendRedirect(basePath+"adminHome");
return;
}
response.sendRedirect(basePath+"home");
}
LoginSuccessHandle类中根据用户是ROLE_ADMIN还是其他角色使用response.sendRedirect跳转到了不同的页面。