Using Interceptor to validate user access privilege

后端 未结 2 806
温柔的废话
温柔的废话 2020-12-07 05:12

I am trying to use an Interceptor to restrict users from performing certain actions.

ContainsKeyInterceptor:



        
2条回答
  •  -上瘾入骨i
    2020-12-07 05:25

    Struts Session is just a Map wrapping the underlying HttpSession.

    While implementing the SessionAware interface is the correct way to get it in an Action, if you want to get it from within an Interceptor, you need to do the following:

    To get the Struts Session Map:

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        final ActionContext context = ai.getInvocationContext();
    
        // Struts Session
        Map session = context.getSession();
    

    To get the real HttpSession object:

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        final ActionContext context = ai.getInvocationContext();
    
        HttpServletRequest request = (HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST);
    
        // Http Session
        HttpSession session = request.getSession();
    

    That said, the reason you are not getting session (nor any other parameter, object and so on) in your Actions, is because you are falling in a common mistake: applying only one Interceptor (your) instead of applying an entire Interceptor Stack (that should contain your):

    You can define it twice in every action:

    
         
        
    

    or, much better, define it once in a custom stack, and use always the stack:

    
                        
           
           
        
    
    
    
        
    

    and eventually define it with default-interceptor-ref to avoid writing it for every action config of that package:

    
    
    
    

提交回复
热议问题