Java 如何在 HttpServletRequest 中设置参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/892537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:46:01  来源:igfitidea点击:

How to set a parameter in a HttpServletRequest?

javaweb-applications

提问by Alceu Costa

I am using a javax.servlet.http.HttpServletRequestto implement a web application.

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

I have no problem to get the parameter of a request using the getParametermethod. However I don't know how to set a parameter in my request.

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

采纳答案by skaffman

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

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

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

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

If you go this route, you should use a Filterto replace your HttpServletRequestwith a HttpServletRequestWrapper:

如果你走这条路,你应该用 aFilter替换你HttpServletRequestHttpServletRequestWrapper

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

回答by Maurizio Pozzobon

From your question, I think what you are trying to do is to store something (an object, a string...) to foward it then to another servlet, using RequestDispatcher(). To do this you don't need to set a paramater but an attribute using

从你的问题来看,我认为你想要做的是使用 RequestDispatcher() 存储一些东西(一个对象,一个字符串......)然后将它转发到另一个 servlet。为此,您不需要设置参数,而是使用属性

void setAttribute(String name, Object o);

and then

进而

Object getAttribute(String name);

回答by Jeff Williams

If you really want to do this, create an HttpServletRequestWrapper.

如果您真的想这样做,请创建一个 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 );
   }

}

回答by mifmax

Sorry, but why not use the following construction:

抱歉,为什么不使用以下结构:

request.getParameterMap().put(parameterName, new String[] {parameterValue});

回答by Ashish Marwal

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:

正如在之前的帖子中提到的,使用 HttpServletReqestWrapper 是可行的方法,但是这些帖子中遗漏的部分是除了覆盖方法 getParameter() 之外,您还应该覆盖其他与参数相关的方法以产生一致的响应。例如,自定义请求包装器添加的参数值也应包含在方法 getParameterMap() 返回的参数映射中。下面是一个例子:

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

回答by Eelco

The missing getParameterMap override ended up being a real problem for me. So this is what I ended up with:

丢失的 getParameterMap 覆盖最终对我来说是一个真正的问题。所以这就是我最终的结果:

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/***
 * Request wrapper enabling the update of a request-parameter.
 * 
 * @author E.K. de Lang
 *
 */
final class HttpServletRequestReplaceParameterWrapper
    extends HttpServletRequestWrapper
{

    private final Map<String, String[]> keyValues;

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, String key, String value)
    {
        super(request);

        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        // Can override the values in the request
        keyValues.put(key, new String[] { value });

    }

    @SuppressWarnings("unchecked")
    HttpServletRequestReplaceParameterWrapper(HttpServletRequest request, Map<String, String> additionalRequestParameters)
    {
        super(request);
        keyValues = new HashMap<String, String[]>();
        keyValues.putAll(request.getParameterMap());
        for (Map.Entry<String, String> entry : additionalRequestParameters.entrySet()) {
            keyValues.put(entry.getKey(), new String[] { entry.getValue() });
        }

    }

    @Override
    public String getParameter(String name)
    {
        if (keyValues.containsKey(name)) {
            String[] strings = keyValues.get(name);
            if (strings == null || strings.length == 0) {
                return null;
            }
            else {
                return strings[0];
            }
        }
        else {
            // Just in case the request has some tricks of it's own.
            return super.getParameter(name);
        }
    }

    @Override
    public String[] getParameterValues(String name)
    {
        String[] value = this.keyValues.get(name);
        if (value == null) {
            // Just in case the request has some tricks of it's own.
            return super.getParameterValues(name);
        }
        else {
            return value;
        }
    }

    @Override
    public Map<String, String[]> getParameterMap()
    {
        return this.keyValues;
    }

}