如何在 HttpServletRequest 中设置参数?

2022-09-01 05:44:38

我正在使用javax.servlet.http.HttpServletRequest来实现Web应用程序。

我没有问题使用getParameter方法获取请求的参数。但是,我不知道如何在我的请求中设置参数。


答案 1

您不能,不使用标准 API。 表示服务器收到的请求,因此添加新参数不是一个有效的选项(就API而言)。HttpServletRequest

原则上,您可以实现一个子类,该子类包装原始请求并拦截方法,并在转发时传递包装的请求。HttpServletRequestWrappergetParameter()

如果您走这条路,您应该使用 a 将您替换为 :FilterHttpServletRequestHttpServletRequestWrapper

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);
}

答案 2

如果你真的想这样做,创建一个HttpServletRequestWrapper。

public class AddableHttpRequest extends HttpServletRequestWrapper {

   private HashMap params = new HashMap();

   public AddableingHttpRequest(HttpServletRequest request) {
           super(request);
   }

   public String getParameter(String name) {
           // if we added one, return that one
           if ( params.get( name ) != null ) {
                 return params.get( name );
           }
           // otherwise return what's in the original request
           HttpServletRequest req = (HttpServletRequest) super.getRequest();
           return validate( name, req.getParameter( name ) );
   }

   public void addParameter( String name, String value ) {
           params.put( name, value );
   }

}

推荐