preHandle problem of adding and overriding parameters, overriding HttpServletRequestWrapper and Filter

Posted by saltious on Tue, 31 Mar 2020 23:23:36 +0200

Because HttpServletRequest in preHandle only has setAttribute, no setParameter and no add method

So there is no way to add parameters directly. I checked a lot of data from the Internet, basically speaking, I need to rewrite HttpServletRequestWrapper

Just do what you say. Check the blog on the Internet to see how others can realize it. Maybe because you don't have a solid foundation, you can't understand a lot of it. You've fumbled

It's been a day. Now record it for future reference.

 

First, create a ChangeRequestWrapper class to inherit HttpServletRequestWrapper. The code is as follows

package com.ccs.ssmis.common.interceptors;

import com.ccs.ssmis.common.redis.RedisUtils;
import com.ccs.ssmis.common.utils.Constants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class ChangeRequestWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> parameterMap; // Of all parameters Map aggregate

    public ChangeRequestWrapper(HttpServletRequest request) {
        super(request);
        parameterMap = request.getParameterMap();
    }


    /**
     * Get all parameter names
     *
     * @return Return all parameter names
     */
    @Override
    public Enumeration<String> getParameterNames() {
        Vector<String> vector = new Vector<String>(parameterMap.keySet());
        return vector.elements();
    }

    /**
     * Gets the value of the specified parameter name. If there is a duplicate parameter name, the first value is returned to receive the general variable, such as text type
     *
     * @param name Specify parameter name
     * @return Specify the value of the parameter name
     */
    @Override
    public String getParameter(String name) {
        String[] results = parameterMap.get(name);
        return results[0];
    }


    /**
     * Gets an array of all values of the specified parameter name, such as all data of the checkbox
     * Receive array variables, such as type checkobx
     */
    @Override
    public String[] getParameterValues(String name) {
        return parameterMap.get(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return parameterMap;
    }
   
    public void setParameterMap(Map<String, String[]> parameterMap) {
        this.parameterMap = parameterMap;
    }

}

Then rewrite the Filter. The code is as follows

package com.ccs.ssmis.common.interceptors;

import com.ccs.ssmis.common.redis.RedisUtils;
import com.ccs.ssmis.common.utils.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LangFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        ChangeRequestWrapper changeRequestWrapper = new ChangeRequestWrapper((HttpServletRequest) servletRequest);

        Map<String, String[]> parameterMap = new HashMap<>(changeRequestWrapper.getParameterMap());

        String[] strings = parameterMap.get("token");
        //Logic code to judge whether there is any incoming token,Without,Directly through
        if (strings == null || strings.length == 0) {
            changeRequestWrapper.setParameterMap(parameterMap);
        }else{
            logger.info("=============Interceptor analysis token==================");
            parameterMap.put("token", strings);
            //analysis token
            Map<String, Object> map = RedisUtils.getMap(strings[0] + Constants.token_Suffix);
            parameterMap.put("isok", "false".split(","));
            if (map!=null) {
                parameterMap.put("userId", map.get("userId").toString().split(","));
                parameterMap.put("isok", "true".split(","));
            }
            changeRequestWrapper.setParameterMap(parameterMap);
        }
        //Make carbon copies HttpServletRequestWrapper
        filterChain.doFilter(changeRequestWrapper, servletResponse);
    }

    @Override
    public void destroy() {

    }


}

Then add interceptor configuration in web.xml and copy it directly.

  <filter>
    <filter-name>languageFilter</filter-name>
    <filter-class>com.ccs.ssmis.common.interceptors.LangFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>

  <filter-mapping>
    <filter-name>languageFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

Note: the configured interceptor will execute before the preHandle method. So the logic code can be written directly in the override class of Filter

I hope you can learn and make progress together. Thank you.

This blog is adapted from other people's blogs. Please indicate the place of reprint. Thank you.

Reference address: https://www.cnblogs.com/cache/p/8052108.html

Link address: http://www.cnblogs.com/richard-ju/p/L2018003.html

Topics: Java Redis xml encoding