How to set a parameter in a HttpServletRequest?

后端 未结 7 696
感动是毒
感动是毒 2021-02-01 03:16

I am using a javax.servlet.http.HttpServletRequest to implement a web application.

I have no problem to get the parameter of a request using the getParamete

相关标签:
7条回答
  • 2021-02-01 03:49

    As mentioned in the previous posts, using an HttpServletReqiestWrapper is the way to go, however the missed part in those posts was that apart from overriding the method getParameter(), you should also override other parameter related methods to produce a consistent response. e.g. the value of a param added by the custom request wrapper should also be included in the parameters map returned by the method getParameterMap(). Here is an example:

       public class AddableHttpRequest extends HttpServletRequestWrapper {
    
        /** A map containing additional request params this wrapper adds to the wrapped request */
        private final Map<String, String> params = new HashMap<>();
    
        /**
         * Constructs a request object wrapping the given request.
         * @throws java.lang.IllegalArgumentException if the request is null
         */
        AddableHttpRequest(final HttpServletRequest request) {
            super(request)
        }
    
        @Override
        public String getParameter(final String name) {
            // if we added one with the given name, return that one
            if ( params.get( name ) != null ) {
                return params.get( name );
            } else {
                // otherwise return what's in the original request
                return super.getParameter(name);
            }
        }
    
    
        /**
         * *** OVERRIDE THE METHODS BELOW TO REFLECT PARAMETERS ADDED BY THIS WRAPPER ****
         */
    
        @Override
        public Map<String, String> getParameterMap() {
            // defaulf impl, should be overridden for an approprivate map of request params
            return super.getParameterMap();
        }
    
        @Override
        public Enumeration<String> getParameterNames() {
            // defaulf impl, should be overridden for an approprivate map of request params names
            return super.getParameterNames();
        }
    
        @Override
        public String[] getParameterValues(final String name) {
            // defaulf impl, should be overridden for an approprivate map of request params values
            return super.getParameterValues(name);
        }
    }
    
    0 讨论(0)
提交回复
热议问题