Tomcat 默認 URIEncoding=ISO-8859-1,導致 GET 參數中文亂碼;響應默認編碼不一致導致輸出亂碼。雙管齊下徹底解決。
修改 $CATALINA_HOME/conf/server.xml,找到 <Connector port="8080" ...> 添加屬性:
<Connector port="8080"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true"
URIEncoding="UTF-8" />
建議統一用 UTF-8 (而非 GBK),全鏈路一致:數據庫、連接池、JVM、前端頁面 <meta charset="UTF-8">、JS 文件編碼、HTTP Header Content-Type: text/html; charset=UTF-8。
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 必須在獲取 Writer/OutputStream 前設置
resp.setContentType("text/html; charset=UTF-8");
// 等價於 resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("中文測試正常");
}
}
@WebFilter("/*")
public class EncodingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
req.setCharacterEncoding("UTF-8"); // POST 請求體解碼
resp.setCharacterEncoding("UTF-8"); // 響應編碼
resp.setContentType("text/html;charset=UTF-8");
chain.doFilter(req, resp);
}
}
Spring Boot 直接配置:
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true
POST 表單提交亂碼需在讀取參數前調用 request.setCharacterEncoding("UTF-8"),或配置上述過濾器。URIEncoding **不影響 POST**。
server.xml 修改。Content-Type: text/html; charset=UTF-8。utf8mb4,連接串 characterEncoding=UTF-8。統一 UTF-8 全鏈路,中文亂碼徹底告別。