有关重写SimpleUrlAuthenticationFailureHandler的说明

时间:2014-10-22 08:13:06

标签: java spring jsp java-ee spring-security

我在业余时间一直在研究java和Spring一段时间,所以我既不掌握java也不掌握Spring。

对于我为研究java和Spring而创建的Web项目,我必须扩展SimpleUrlAuthenticationFailureHandlerm

在我自己的SimpleUrlAuthenticationFailureHandler方法中扩展onAuthenticationFailure并覆盖onAuthenticationFailure()...后,我不得不调用super.onAuthenticationFailure(...)方法,这是不清楚的原因。

可能我没有得到java的主要规则之一。

这是我正在谈论的课程

public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { 

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {    

       if(exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
              setDefaultFailureUrl("/url1");
        }

       else if (exception.getClass().isAssignableFrom(DisabledException.class)) {        
            setDefaultFailureUrl("/url2");
       }

       else if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {      
            setDefaultFailureUrl("/url3");  
      }

      super.onAuthenticationFailure(request, response, exception);  //why this???
    }    
}

1 个答案:

答案 0 :(得分:3)

在这里,您尝试覆盖SimpleUrlAuthenticationFailureHandler的方法。

此方法在SimpleUrlAuthenticationFailureHandler中定义:

public void onAuthenticationFailure(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException {
        if (this.defaultFailureUrl == null) {
            this.logger.debug("No failure URL set, sending 401 Unauthorized error");
            response.sendError(401,"Authentication Failed: " + exception.getMessage());
        } else {
            saveException(request, exception);

            if (this.forwardToDestination) {
                this.logger.debug("Forwarding to " + this.defaultFailureUrl);
                request.getRequestDispatcher(this.defaultFailureUrl).forward(request, response);
            } else {
                this.logger.debug("Redirecting to " + this.defaultFailureUrl);
                this.redirectStrategy.sendRedirect(request, response,
                        this.defaultFailureUrl);
            }
        }
    }

在CustomAuthenticationFailureHandler中,您将覆盖SimpleUrlAuthenticationFailureHandler的方法:

基本上,您只需设置默认网址。而且你需要编写重定向策略。但它是在超类SimpleUrlAuthenticationFailureHandler中定义的。所以你需要调用super.onAuthenticationFailure(请求,响应,异常);