Using Interceptor to validate user access privilege

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

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

ContainsKeyInterceptor:



        
相关标签:
2条回答
  • 2020-12-07 05:25

    Struts Session is just a Map<String,Object> 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<String, Object> 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:

    <action name="login" class="ph.edu.iacademy.action.LoginAction">
        <interceptor-ref name="defaultStack" /> <!-- this is missing -->
        <interceptor-ref name="containskeyinterceptor" />
    

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

    <interceptors>
        <interceptor-stack name="yourStack">                
           <interceptor-ref name="defaultStack"/>
           <interceptor-ref name="containskeyinterceptor"/>
        </interceptor-stack>
    </interceptors>
    
    <action name="login" class="ph.edu.iacademy.action.LoginAction">
        <interceptor-ref name="yourStack" />
    

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

    <default-interceptor-ref name="yourStack"/>
    
    <action name="login" class="ph.edu.iacademy.action.LoginAction">
    
    0 讨论(0)
  • 2020-12-07 05:46

    Based on this I don't think the interceptor itself can / needs to be session aware.

    You can access this property as such:

    final ActionContext context = actionInvocation.getInvocationContext();  
    this.session = context.getSession();  
    

    There may be a way to get this set automatically, I'm not too familiar with struts2, but it could be that the sessionaware only works for a specific subset of objects and this interceptor isn't one of them for some reason. (not being scanned, being excluded from scan, of the wrong type)

    0 讨论(0)
提交回复
热议问题