第一步:新建一个编码过滤器,实现javax.servlet.Filter
package com.itcast.web.filter;
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;
import javax.servlet.http.HttpServletRequest;
public class SetEncodeFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
<span style="color:#ff0000;">//过滤编码
req.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);</span>
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
第二步:在web.xml中配置该过滤器
请注意:为了编码过滤器对整个应用起作用,请将该过滤器放在所有过滤器之前。
<filter>
<filter-name>setEncodeFilter</filter-name>
<filter-class>com.itcast.web.filter.SetEncodeFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>setEncodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
此时,该编码过滤器会过滤应用中所有的访问路径,统一编码。