/*
对所有乱码进行拦截及纠正,包括get提交方式,解决get提交方式乱码,方式是重写了request的getParameter方法,
让其在返回值的时候检查提交方式,如果为“get”就进行解码
*/
public class FilterTest1 implements Filter{
private String code = null;
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//设置码表
request.setCharacterEncoding(code);
response.setCharacterEncoding(code);
response.setContentType("text/html;charset="+code);
//将现在的reuqest对象换成我自己的request对象
MyHttpServletRequest myRequest = new MyHttpServletRequest((HttpServletRequest)request);
//跳转到请求的资源,并传入自己定义的myRequest对象
chain.doFilter(myRequest, response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
//获取配置的编码格式
String code = config.getInitParameter("code");
//获取xml文件<init-param>标签中code的value//如果没有配置,就使用UTF-8默认编码
this.code = code == null || "".equals(code.trim()) ? "utf-8" : code;
}
}
//重新定义一个自己的request对象,继承HttpServletRequestWrapper 这个HttpServletRequest的适配器
class MyHttpServletRequest extends HttpServletRequestWrapper{
public MyHttpServletRequest(HttpServletRequest request){
super(request);
}
//重写getParameter方法
@Override
public String getParameter(String name) {
String value = super.getParameter(name);
if(value == null)
return null;
//判断只要不是“get”方式提交就直接返回,equalsIgnoreCase方法是不考虑大小写的匹配
if(!"get".equalsIgnoreCase(super.getMethod()))
return value;
//如果请求方式为"get",那么就进行加码,解码码表为父类的码表
try {
value = new String(value.getBytes("ISO-8859-1"),super.getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
}
在web.xml配置文件中 注册此过滤器
<!-- 注册过滤器(ServletTest1.jsp的过滤器) -->
<filter>
<filter-name>FilterTest1</filter-name>
<filter-class>cn.messy_code.FilterTest1</filter-class>
<!-- 设置init方法接收的参数(配置的是编码表) -->
<init-param>
<param-name>code</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- 当访问此web应用中所有的资源时,都用过滤器拦截 -->
<filter-mapping>
<filter-name>FilterTest1</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>