JavaWeb—filter全局乱码解决
- 在获取参数之前设置请求编码
- 在响应浏览器之前设置响应编码
案例代码
GetFormServlet
package com.lbl.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/get_form")
public class GetFormServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//1:获取表单数据
String username = request.getParameter("username");
System.out.println("username:"+username);
//2:响应
// response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("收到数据啦!");
}
}
form.jsp
<%--
Created by IntelliJ IDEA.
User: Carlos
Date: 2020/9/16
Time: 11:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/get_form" method="post">
用户名:<input type="text" name="username"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
运行效果:
打开GetFormServlet中的response.setContentType("text/html;charset=UTF-8");
这一行的注释
运行效果:
此处是关键,只要符合条件的请求会被过滤器拦截,多个Servlet的请求,被拦截下来之后先设置好编码,再交给Servlet
CharSetFilter
package com.lbl.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter("/*")
public class CharSetFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//1:解决请求参数乱码
HttpServletRequest request = (HttpServletRequest)req;
String method = request.getMethod();
if(method.equals("POST")) {
req.setCharacterEncoding("UTF-8");
}
resp.setContentType("text/html;charset=UTF-8");
chain.doFilter(req, resp);
}
public void init(FilterConfig config) throws ServletException {
}
}
现在注释response.setContentType("text/html;charset=UTF-8");
filter-全局乱码分析
- doFilter方法内部执行
- 先执行doChain之前的代码,再执行doChain方法
- 再执行Servlet的doGet/doPost
- 最后执行doChain之后的代码