第一步:声明包装类:
//声明包装类
class MyRequestextends HttpServletRequestWrapper{
public MyRequest(HttpServletRequest request) {
super(request);
}
//增强getParamter
@Override
public String getParameter(String name) {
String val = super.getParameter(name);
if(super.getMethod().equals("GET")){
try {
val = new String(val.getBytes("ISO-8859-1"),super.getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return val;
}
}
第二步:在doFilter方法中,声明包装类的实例
package filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class CharFilter implements Filter {
// 声明编码的成员变量
private Stringencoding;
public void init(FilterConfig config) throws ServletException {
encoding = config.getInitParameter("bm");
}
public void doFilter(ServletRequest request, ServletResponseresponse,
FilterChain chain) throws IOException, ServletException{
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset=" +encoding);
// 判断是否需要包装
HttpServletRequest req = (HttpServletRequest) request;
if (req.getMethod().equals("GET")) {[W1]
request= new MyRequest(req);[W2]
}
// 声明包装类的实例
// 放行
chain.doFilter(request, response);
}
public void destroy() {
}
}