方式一:使用【注解】方式实现过滤 @WebFilter("/*")
@WebFilter("/*")
public class FilterCode implements Filter {
public FilterCode() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 处理编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 过滤器继续执行
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
方式二:使用xml配置文件来实现过滤
此时不需要写@WebFilter("/*")
public class FilterCode implements Filter {
public FilterCode() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 处理编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 过滤器继续执行
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
<!-- 过滤器过滤字符编码问题 -->
<filter>
<filter-name>filter</filter-name>
<filter-class>com.filter.FilterCode</filter-class> <!-- 过滤器位置 -->
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern> <!-- 过滤器的内容 -->
</filter-mapping>