其实写个过滤器是很方便的,可以起到“一招封喉”的作用,写了过滤器就不用在jsp的代码中,再考虑各种编码的问题了!请求和回应都会经过这个过滤器,转换成统一的编码格式。下面是过滤器的代码:
package com.suo;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CharacterEncodingFilter implements Filter
{
protected String encoding=null;
protected FilterConfig filterConfig=null;
protected boolean ignore=true;
public CharacterEncodingFilter(){}
public void destroy()
{
this.encoding=null;
this.filterConfig=null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
if(ignore || request.getCharacterEncoding()==null)
{
if(encoding!=null)
request.setCharacterEncoding(encoding);
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
this.filterConfig=filterConfig;//从web.xml中取得参数。
this.encoding=filterConfig.getInitParameter("encoding");
String value=filterConfig.getInitParameter("ignore");
if(value==null)
{
ignore=true;
}
else if(value.equalsIgnoreCase("true"))
{
ignore=true;
}
else if(value.equalsIgnoreCase("yes"))
{
ignore=true;
}
else
{
ignore=false;
}
}
}
然后在web.xml 中进行一下配置,关键是传递过去参数,即编码格式:
<filter>
<filter-name>CharacterEncoding</filter-name>
<filter-class>com.suo.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在服务器启动时,就会读取这个web.xml文件,注册这个过滤器,等于是注册这个过滤器类到服务器中。