How do I return a 403 Forbidden in Spring MVC?

后端 未结 5 1024
太阳男子
太阳男子 2020-12-29 03:14

I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.

5条回答
  •  忘掉有多难
    2020-12-29 03:49

    Quickie

    If you are using plain JSP views (as is most common), then simply add

    <% response.setStatus( 403 ); %>
    

    somewhere in your view file. At the top is a nice place.

    Detail

    In MVC, i would always set this in the view, and in most cases with Spring-MVC, use the SimpleMappingExceptionResolver to present the correct view in response to a thrown runtime Exception.

    For example: create and throw a PermissionDeniedException in your controller or service layer and have the exception resolver point to a view file permissionDenied.jsp. This view file sets the 403 status and shows the user an appropriate message.

    In your Spring bean XML file:

    
      
        
                    
            rescues/permissionDenied
          
          ... set other exception/view mappings as s here ...
        
      
      
    
    
    
      
      
      
    
    

    If you need to implement a user login mechanism, take a look at Spring Security (formerly Acegi Security).

提交回复
热议问题