Forewarned: The issue here is to solve the garbage problem for Chinese web project how to solve all the resources under the current project Servlet Filter through a filter.
- The first post request to appear in Chinese garbled;
- Second respose output character stream emerging Chinese garbage problem;
First, configure the path to intercept the Filter
In order to make all over the Servlet resources under the current project can solve the garbage problem, we configured a comment Filter is @WebFilter ( "/ "), "/ " on behalf of all current project resources will be filtered Servlet Filter this filter.
Second, to solve a problem, post request parameters garbage problem
1. Before Filter no filter configuration
2. configure our Filter Filters
3. It can be seen after the configuration we solved the problem of Chinese garbled post requests
Third, solve the garbage problem response output stream
1. First, in the absence of configuration, we output the character flow to the html page
2. We then filter Filter Configuration acquired first character stream resp.setCharacterEncoding utf-8's ( "utf-8"); We then tell the browser of MIME data output stream is our html, the encoding format of the output stream is utf 8 (since we acquired stream is utf-8 format) resp.setContentType ( "text / html; utf-8") ;.
3. Finally, you can see the Chinese on the page is not garbled
Fourth, accompanied Filter source code, if an ordinary web projects, then you can directly apply this filter to solve the garbage problem in Chinese current project.
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")![在这里插入图片描述](https://img-blog.csdnimg.cn/20200205223546333.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMjMwMDA3,size_16,color_FFFFFF,t_70)
public class Filter implements javax.servlet.Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//1.解决response输出流的乱码问题
req.setCharacterEncoding("utf-8");
//2.解决post请求中的中文信息乱码问题
//2.1 设置获取流的编码格式
resp.setCharacterEncoding("utf-8");
//2.2 告知浏览器我们输出的文件类型以及编码格式
resp.setContentType("text/html;utf-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}