1.JSP页面写中文
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
保证contentType, pageEncoding和浏览器编码都是UTF-8则不会出现乱码
2.表单提交中文
<% request.setCharacterEncoding("UTF-8"); %> <%= request.getParameter("message") %>
在用request获取参数前, 先设置编码.
3.通过get方法提交的中文
<% request.setCharacterEncoding("UTF-8"); String msg = new String(request.getParameter("message").getBytes("iso-8859-1"), "UTF-8"); %> <%= msg %>
get方式中文默认用Iso-8859-1编码.
第一种方法: 先解码中文, 然后用UTF-8编码.
第二种方法: 在tomcat的server.xml文件中配置useBodyEncodingForURI="true";
然后设置request.setCharacterEncoding("UTF-8")即可;
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" useBodyEncodingForURI="true" />