问题描述
我正在使用 javax.servlet.http.HttpServletRequest 来实现一个Web应用程序。
I am using a javax.servlet.http.HttpServletRequest to implement a web application.
我没有问题来获取参数使用 getParameter 方法的请求。但是我不知道如何在我的请求中设置参数。
I have no problem to get the parameter of a request using the getParameter method. However I don't know how to set a parameter in my request.
推荐答案
你不能,不能使用标准API 。 HttpServletRequest
表示服务器收到的请求,因此添加新参数不是有效选项(就API而言)。
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).
你原则上可以实现一个包含原始请求的 HttpServletRequestWrapper
的子类,并拦截 getParameter()
方法,并在你转发时传递包装的请求。
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.
如果你走这条路线,你应该使用过滤器
用 HttpServletRequestWrapper
替换你的 HttpServletRequest
:
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);
}
这篇关于如何在HttpServletRequest中设置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!