编写一个EncodingFilter
1.读取web.xml文件中配置的当前WEB应用的初始化参数encoding
2.指定请求的字符编码为1读取到的编码
3.调用chain.doFilter()方法"放行"请求
web.xml
<context-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</context-param>
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.demo.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/filter/b.jsp</url-pattern>
</filter-mapping>
EncodingFilter
package com.demo.filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class EncodingFilter extends HttpFilter {
private String encoding;
@Override
protected void init() {
encoding = getFilterConfig().getServletContext().getInitParameter("encoding");
System.out.println(encoding);
}
@Override
public void doFilter(HttpServletResponse response, HttpServletRequest request, FilterChain filterChain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
filterChain.doFilter(request,response);
}
}