How to set a parameter in a HttpServletRequest?

后端 未结 7 888
感动是毒
感动是毒 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:43

    You can't, not using the standard API. HttpServletRequest represent a request received by the server, and so adding new parameters is not a valid option (as far as the API is concerned).

    You could in principle implement a subclass of HttpServletRequestWrapper which wraps the original request, and intercepts the getParameter() methods, and pass the wrapped request on when you forward.

    If you go this route, you should use a Filter to replace your HttpServletRequest with a HttpServletRequestWrapper:

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            // Check wether the current request needs to be able to support the body to be read multiple times
            if (MULTI_READ_HTTP_METHODS.contains(request.getMethod())) {
                // Override current HttpServletRequest with custom implementation
                filterChain.doFilter(new HttpServletRequestWrapper(request), servletResponse);
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
    

提交回复
热议问题