解决JSP中文乱码问题

一.页面加载时

保证contentType="text/html",charset="UTF-8",pageEncoding="UTF-8"

且客户端浏览器的字符编码也要与JSP页面保持一致

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

二.获取中文参数值时

因为默认参数在传输过程中使用的编码为 ISO-8859-1 。

1.当请求为POST时

在获取请求信息前,调用 request.setCharacterEncoding("UTF-8") 即可

<%
    request.setCharacterEncoding("UTF-8");
%>
<%=request.getParameter("username")%>

2.当请求为GET时

1)手动转换编码

<%
    String val = request.getParameter("username");
    String username = new String(val.getBytes("iso-8859-1"), "UTF-8");
    out.println(username);
%>

2)在Tomcat根目录/conf/server.xml中的Connector节点加上属性useBodyEncodingForURI="true",便可以像POST方法一样使用request.setCharacterEncoding("UTF-8")来吊证编码

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" 
               useBodyEncodingForURI="true"/>
原文地址:https://www.cnblogs.com/CComma/p/7143841.html