今天碰到一个冷僻的需求,需要在Filter里增加request的parameter,类似于
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) {
...
req.setParameter(paramName, paramValue);
chain.doFilter(req, resp);
}
可是发现ServletRequest可以get/set Attribute但是对Paramter只能get,后来google了半天才
明白,按照j2ee的标准,Paramter是只读的,Attribute才可以读写,要想添加Parameter必须通
过ServletRequestWrapper。具体的做法是,继承ServletRequestWrapper实现自己的类,然后
重载getParameter方法,在其中加入新的Parameter,最后在doFilter中传递自己的RequestWrapper。
以下是相关的代码,是用的HttpServletRequestWrapper。代码是删减过的,只是表示个意思。
public class MyFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
...
FilteredRequest filteredReq = new FilteredRequest(slingReq);
filteredReq.setLabel(label);
filteredReq.setDestName(destName);
chain.doFilter(filteredReq, resp);
}
public void init(FilterConfig conf) throws ServletException {
}
class FilteredRequest extends HttpServletRequestWrapper {
private String label;
private String destName;
public FilteredRequest(HttpServletRequest request) {
super(request);
}
public void setLabel(String id) {
label = id;
}
public void setDestName(String id) {
destName = id;
}
public String getParameter(String paramName) {
if ("label".equals(paramName)) {
return label;
} else if ("destName".equals(paramName)) {
return destName;
} else {
return super.getParameter(paramName);
}
}
}
}