本文介绍过滤器来设置字符编码的问题,通过编写一个servlet和配置web.xml来即可实现 这样不必在每个jsp页面社自豪字符编码了,值需要在web.xml配置需要的编码即可。
web.xml配置内容如下:
<!-- 字符过滤器 --> <filter> <filter-name>encodeFilter</filter-name> <filter-class> test.servlet.CharacterEncodingFilter </filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter>
<filter-mapping> <filter-name>encodeFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>encodeFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>
<filter-mapping> <filter-name>encodeFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Filter内容如下:
package test.servlet;
import javax.servlet.*;import java.io.IOException;
public class CharacterEncodingFilter implements Filter {
protected String encoding = "UTF-8";
protected FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; this.encoding = filterConfig.getInitParameter("encoding"); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Conditionally select and set the character encoding to be used if (request.getCharacterEncoding() == null) { String encoding = selectEncoding(request); if (encoding != null) { request.setCharacterEncoding(encoding); } } // Pass control on to the next filter chain.doFilter(request, response); }
protected String selectEncoding(ServletRequest request) { return (this.encoding); }
public void destroy() { this.encoding = null; this.filterConfig = null; }
}
转: 字符页面设置方式:
1. pageEncoding:<%@ page pageEncoding="UTF-8"%>
jsp页面编码: jsp文件本身的编码
2. contentType: <%@ page contentType="text/html; charset=UTF-8"%>
web页面显示编码:jsp的输出流在浏览器中显示的编码
3. html页面charset:<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
web页面输入编码: 输入框输入的字体编码
4. setCharacterEncoding:request.setCharacterEncoding(),response.setCharacterEncoding()
web服务器输入的请求流: web Server相应浏览器的请求数据
5 .setContentType:response.setContentType()
web服务器输出的响应流: web Server相应浏览器的输出数据
本文来自博客,转载请标明出处:http://blog.csdn.net/XinVSYuan/archive/2009/02/05/3864853.aspx