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 SetCharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
// 设置申请对象的值为空,有利于内存资源的快速释放
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
// filter的主体操作
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 判断是否需要进行编码的设置
if (!ignore || request.getCharacterEncoding() == null) {
// 得到配置文件中的编码类型
String encoding = setEncoding(request);
if (encoding != null) {
request.setCharacterEncoding(encoding);
}
}
chain.doFilter(request, response);
}
protected String setEncoding(ServletRequest request) {
return this.encoding;
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null) {
this.ignore = false;
} else if (value.equalsIgnoreCase("false")) {
this.ignore = true;
} else if (value.equalsIgnoreCase("no")) {
this.ignore = true;
} else {
this.ignore = false;
}
}
}
web.xml
<filter>
<filter-name>SetCharacterEncodingFilter</filter-name>
<filter-class>myservlets.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gbk</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SetCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
还可以设置ignore参数,当其值为no或者false时,这个filter将不工作!
用Servlet过滤器去除JSP页面中的乱码
最新推荐文章于 2020-03-27 17:07:03 发布