使用Filter来设置字符集编码

         在jsp中,会经常出现编码错误的问题的,尤其是对于servlet,我们知道是使用servlet来输入字符串的时候都是需要指定输出的编码的,一般必须是的输出的字符编码和我们的文件编码是一致的,否则的话就会出现编码错误的问题。但是每次都为servlet指定输出编码很是纠结的,每次都需要使用response.setContentType(“text/html; charset=utf-8″);

         现在比较好的就是使用Filter来拦截所有的路径,并为他们的输入指定输出的编码,这样不哟每次都这么纠结了。

         1.首先兴建一个Class是想Filter,代码如下:

package ynu.sanwen.testfilter;

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{
private String characterEncoding="gbk";
private boolean enabled;

public void destroy() {
characterEncoding=null;
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(enabled&&characterEncoding!=null){
System.out.println("指定的编码是:"+characterEncoding);
request.setCharacterEncoding(characterEncoding);
response.setContentType("text/html; charset="+characterEncoding);
}
chain.doFilter(request, response);
}

public void init(FilterConfig filterConfig) throws ServletException {
characterEncoding=filterConfig.getInitParameter("characterEncoding");//获得编码
enabled="true".equalsIgnoreCase(filterConfig.getInitParameter("enabled").trim());//启用

}

}

    2.在配置文件里面


characterEncodingFilter
ynu.sanwen.testfilter.CharacterEncodingFilter

characterEncoding utf-8

enabled true



characterEncodingFilter
/*

 

3.新建一个servlet测试

      

package ynu.sanwen.testfilter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestEncoding extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.print("我是三稳,喜欢。。。。。。。。。。");
}
}

效果:
设置false的时候:
设置true的时候:

项目代码:http://www.cangzhang.com/wp-content/uploads/2012/09/Filter_encoding.zip

共有 15 条评论

Top