Spring Security教程(9)---- 自定义AccessDeniedHandler

时间:2025-04-02 13:13:51
  • public class DefaultAccessDeniedHandler implements AccessDeniedHandler {  
  •   
  •     /* (non-Javadoc) 
  •      * @see #handle(, , ) 
  •      */  
  •     private String errorPage;  
  •   
  •     //~ Methods ========================================================================================================  
  •   
  •     public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)  
  •             throws IOException, ServletException {  
  •         boolean isAjax = (request);  
  •         if(isAjax){  
  •             Message msg = (accessDeniedException);  
  •             (response, msg);  
  •         }else if (!()) {  
  •             if (errorPage != null) {  
  •                 // Put exception into request scope (perhaps of use to a view)  
  •                 (WebAttributes.ACCESS_DENIED_403, accessDeniedException);  
  •   
  •                 // Set the 403 status code.  
  •                 (HttpServletResponse.SC_FORBIDDEN);  
  •   
  •                 // forward to error page.  
  •                 RequestDispatcher dispatcher = (errorPage);  
  •                 (request, response);  
  •             } else {  
  •                 (HttpServletResponse.SC_FORBIDDEN, ());  
  •             }  
  •         }  
  •     }  
  •   
  •     /** 
  •      * The error page to use. Must begin with a "/" and is interpreted relative to the current context root. 
  •      * 
  •      * @param errorPage the dispatcher path to display 
  •      * 
  •      * @throws IllegalArgumentException if the argument doesn't comply with the above limitations 
  •      */  
  •     public void setErrorPage(String errorPage) {  
  •         if ((errorPage != null) && !("/")) {  
  •             throw new IllegalArgumentException("errorPage must begin with '/'");  
  •         }  
  •   
  •         this.errorPage = errorPage;  
  •     }  
  •   
  • }