Jsp字符编码过滤器

通过此过滤器,可以实现统一将编码设置为UTF-8。

1.首先在web.xml中配置,添加如下代码:

<!-- 过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.itRed.util.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>

2.编写一个实现该过程的java类(包名:com.itRed.util,类名:CharacterEncodingFilter),代码如下:

package com.itRed.util;

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;

/**
* 字符编码过滤器
* @author itRed
*
*/
public class CharacterEncodingFilter implements Filter{
protected String encoding = null;
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 {
if (encoding != null) {
request.setCharacterEncoding(encoding);
response.setContentType("text/html; charset="+encoding);
}
chain.doFilter(request, response);
}

public void destroy() {
this.encoding = null;
this.filterConfig = null;
}

}

上一篇:干货 | Java中获取类名的3种方法!


下一篇:Servlet字符编码过滤器