如何从spring启动应用程序中的onApplicationEvent()重定向到其他站点

时间:2017-10-11 08:22:15

标签: spring-boot

我有一个班级:

@Component
public class AuthenticationSuccessListener implements ApplicationListener<InteractiveAuthenticationSuccessEvent> 

和无效的方法:

@Override
public void onApplicationEvent(InteractiveAuthenticationSuccessEvent arg0)

我想重定向到其他网站

if(daysBetweenLocalDates(LocalDate.now(), operator.getDateOfChangePassword()) >= 30)
{
    System.out.println("###DEB forcing operator to change pass because date of change pass is: " + operator.getDateOfChangePassword());
    ModelAndView mav = new ModelAndView();
    mav.setViewName("redirect:/changePassword");
}

但我需要return mav;,因为onApplicationEvent无效而存在问题。如何从该方法将用户重定向到另一个网站?

1 个答案:

答案 0 :(得分:0)

正如@Brian Clozel建议Handler工作得很好! 所以我做了一个处理程序:

package local.vlex.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

    @Component
    public class VlexAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
                throws IOException, ServletException {
            response.sendRedirect("/changePassword");
        }
    }

并在WebSecurityConfig中使用它:

@Autowired
VlexAuthenticationSuccessHandler successHandler;

然后:

.formLogin().loginPage("/login").permitAll().successHandler(successHandler)

谢谢@Brian Clozel!