照着书上的例子写了个过滤器
package org.lxh.filterdemo;
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 EncodingFilter implements Filter {
private String charSet;
public void init(FilterConfig config) throws ServletException {
this.charSet = config.getInitParameter("charset");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(this.charSet);
}
public void destroy() {
}
}
写完后配置web.xml
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.lxh.filterdemo.EncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<filter-mapping> <filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
话说这个程序没有什么肉眼看的出的效果,但是我发现此时运行原先的一些jsp程序,发现浏览器都是一片空白。搞了半天,最后发现把过滤器加一行就可以了:
package org.lxh.filterdemo;
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 EncodingFilter implements Filter {
private String charSet;
public void init(FilterConfig config) throws ServletException {
this.charSet = config.getInitParameter("charset");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(this.charSet);
chain.doFilter(request, response);
}
public void destroy() {
}
}
- 原因,过滤器要将过滤的结果传给链上的后一个过滤器,或者传给最终的jsp程序,所以必须加chain.doFilter(request, response);否则就请求就在这里终止了。