我正在使用 javax.servlet.http.HttpServletRequest 来实现Web应用程序。
我可以使用 getParameter 方法获取请求的参数。但是我不知道如何在请求中设置参数。
您不能,不使用标准API。HttpServletRequest代表服务器收到的请求,因此添加新参数不是有效的选择(就API而言)。
HttpServletRequest
原则上,您可以实现一个子类,HttpServletRequestWrapper该子类包装原始请求,并拦截getParameter()方法,并在转发时传递包装的请求。
HttpServletRequestWrapper
getParameter()
如果您走这条路线,则应使用Filter将替换HttpServletRequest为HttpServletRequestWrapper:
Filter
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); }