



Сначала вы должны получить запрос и прочитать все его параметры. Затем создайте еще один запрос с исходными параметрами + новыми и отправьте его снова.
HttpServletRequest неизменен, и изменить его невозможно.
Я обычно оборачиваю исходный HttpServletRequest в новый CustomHttpServletRequest, который действует как прокси для исходного запроса, а затем передаю этот новый CustomHttpServletRequest в цепочку фильтров.
В этом CustomHttpServletRequest вы можете переопределить методы getParameterNames, getParameter, getParameterMap для возврата любых параметров, которые вам нужны.
Это пример фильтра:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletRequest customRequest = new CustomHttpServletRequest(httpRequest);
customRequest.addParameter(xxx, "xxx");
chain.doFilter(customRequest, response);
}
Подкласс HttpServletRequestWrapper и переопределите методы getParameter. Описание этого класса гласит:
Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet.
В фильтре заключите запрос в экземпляр вашего подкласса.
открытый класс CustomHttpServletRequestWrapper расширяет HttpServletRequestWrapper {private Map <String, String> customParameters; общедоступный CustomHttpServletRequestWrapper (запрос HttpServletRequest) {супер (запрос); } public void addCustomParameter (имя строки, значение строки) {customParameters.put (имя, значение); } @Override public String getParameter (String name) {String originalParameter = super.getParameter (имя); если (originalParameter! = null) {вернуть originalParameter; } else {return customParameters.get (имя); }}}
В противном случае вы можете использовать строго типизированный метод setAttribute (). Следовательно, можно использовать метод getAttribute () ...
Я добавляю это как механизм, управляемый файлом свойств, который изменяет обычный запрос. И пользовательский интерфейс, и сам сервлет не могут быть изменены для соответствия этим требованиям - он прозрачен.
Почему бы вам просто не сохранить переменные как атрибуты области действия запроса вместо того, чтобы пытаться добавить их к параметрам запроса?
Я добавляю это как механизм, управляемый файлом свойств, который изменяет обычный запрос. И пользовательский интерфейс, и сам сервлет не могут быть изменены для соответствия этим требованиям - он прозрачен.
Вы можете обернуть HttpServletRequest в новый объект HttpServletRequestWrapper и перезаписать некоторые методы.
Следующий код взят из http://www.ocpsoft.org/opensource/how-to-safely-add-modify-servlet-request-parameter-values/.
Чтобы добавить параметр в фильтр:
public class MyFilter implements Filter {
...
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httprequest = (HttpServletRequest) request;
Map<String, String[]> extraParams = new HashMap<String, String[]>();
extraParams.put("myparamname", String[] { "myparamvalue" });
request = new WrappedRequestWithParameter(httprequest, extraParams);
}
chain.doFilter(request, response);
}
...
class WrappedRequestWithParameter extends HttpServletRequestWrapper {
private final Map<String, String[]> modifiableParameters;
private Map<String, String[]> allParameters = null;
public WrappedRequestWithParameter(final HttpServletRequest request, final Map<String, String[]> additionalParams) {
super(request);
modifiableParameters = new TreeMap<String, String[]>();
modifiableParameters.putAll(additionalParams);
}
@Override
public String getParameter(final String name) {
String[] strings = getParameterMap().get(name);
if (strings != null) {
return strings[0];
}
return super.getParameter(name);
}
@Override
public Map<String, String[]> getParameterMap() {
if (allParameters == null) {
allParameters = new TreeMap<String, String[]>();
allParameters.putAll(super.getParameterMap());
allParameters.putAll(modifiableParameters);
}
// Return an unmodifiable collection because we need to uphold the interface contract.
return Collections.unmodifiableMap(allParameters);
}
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(getParameterMap().keySet());
}
@Override
public String[] getParameterValues(final String name) {
return getParameterMap().get(name);
}
}
}
Вы можете привести пример?