在书写程序时,经常遇到要解决中文乱码问题的情况,如果能快速和简单的操作就能解决问题,就再好不过了,过滤器和监听器的使用会有很好的效果。这里简单的写了一点。
先在WEB-INF中的web.xml中配置过滤器的相关信息(以配置解决中文乱码问题的过滤器为例)
encoding
com.zdsoft.filtertest.EncondingFilter
coding
utf-8
encoding
/*
在EncondingFilter过滤器中进行过滤操作
public String encoding;
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException
{
//为了便于后面的jsp和servlet进行数据处理,要将ServletRequest型和ServletResponse型数据进行转型为HttpServletRequest型和HttpServletResponse型数据
HttpServletRequest req = (HttpServletRequest)arg0;
HttpServletResponse res=(HttpServletResponse)arg1;
//进行数据转码操作(对表单中method为post最有效)
req.setCharacterEncoding(encoding);
res.setCharacterEncoding(encoding);
res.setContentType("text/html charset="+encoding);
//调用下一个过滤器(如果有的话)
arg2.doFilter(req, res);
}
@Override
public void init(FilterConfig arg0) throws ServletException
{
//通过过滤器的配置环境获得init中参数名对应的的参数值
String code=arg0.getInitParameter("coding");
//如果参数值不为空或空格字符串的话,将值赋值给encoding;
if(StringUtils.isNotBlank(code)){
encoding=code;
}
}