Search code examples
javaparametersstruts2interceptoractioncontext

Get a specific parameter sent from view in interceptor


Currently using this code to fetch value of the parameter "csrfPreventionSalt" of Interceptor in Struts2.

Can anyone please tell a direct way to fetch its value...

public String intercept(ActionInvocation invocation) throws Exception {
    final ActionContext context=invocation.getInvocationContext();
    HttpServletRequest httpReq = ServletActionContext.getRequest();
    String salt ="";

    Map<String, Object> params = (Map<String, Object>)ActionContext.getContext().getParameters();
    Iterator<Entry<String, Object>> it = (Iterator<Entry<String, Object>>)params.entrySet().iterator();
    while(it.hasNext()) {
        Entry<String, Object> entry = it.next();
        if(entry.getKey().equals("csrfPreventionSalt"))
        {
        Object obj = entry.getValue();
        if (obj instanceof String[]){
            String[] strArray = (String[]) obj;
            if (strArray!=null) {
                 salt = strArray[0];
            }
        }
    }
}

Solution

  • Assume a parameter was sent to the action, not to the interceptor. When an action is invoked the action context is created and parameters from the request are copied to the action context. You can get parameters via

    public String intercept(ActionInvocation invocation) throws Exception {
        final ActionContext context = invocation.getInvocationContext(); 
        Map<String, Object> parameters = context.getParameters();
        String[] values = (String[]) parameters.get("csrfPreventionSalt");
        String salt = values[0];
        ...