过滤器细节:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>demo01</filter-name>
<filter-class>com.ailyt.filter.FilterStudy02</filter-class>
</filter>
<filter-mapping>
<filter-name>demo01</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
package com.ailyt.filter;
import javax.servlet.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {
/*初始化*/
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncoding初始化");
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
//filterChain链
/**
* 过滤中的所有代码在过滤特定的请求的时候都会被执行
* 必须要让过滤器继续通行
* filterChain.doFilter(servletRequest, servletResponse);
*/
System.out.println("CharacterEncodingFilter执行前");
filterChain.doFilter(servletRequest, servletResponse);//让我们的请求继续走,如果不写程序到这里就会被拦截
System.out.println("CharacterEncodingFilter执行后");
}
/*销毁*/
public void destroy() {
System.out.println("CharacterEncoding销毁");
}
}