乱码问题解决:* POST请求乱码 :request.setCharacterEncoding("utf-8"); * GET请求乱码解决方案一:修改tomcat/conf/server.xml <Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8"/>* 必须有修改tomcat服务器配置文件权限解决方案二:逆向编解码username = URLEncoder.encode(username, "ISO8859-1");username = URLDecoder.decode(username, "utf-8");解决方案三:简写的方式(推荐使用)username = new String(username.getBytes("ISO-8859-1"),"utf-8");* request获取中文数据乱码(总结:)* post提交* 设置request缓冲区的编码request.setCharacterEncoding("utf-8"); * get提交* String构造方法username = new String(username.getBytes("ISO-8859-1"),"utf-8");
处理中文乱码
post
setCharacterEncoding //放在getParameter前才有效
get
new String(str.getBytes(“ISO-8859-1”),”utf-8”)
设置tomcat Connector URIEncoding=“utf-8”
package cn.itcast.request;import java.io.IOException;import java.util.Arrays;import java.util.Map;import java.util.Set;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/*** 获取请求参数* @author Administrator**/public class RegServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {/*** request获取中文的乱码* post请求(经常使用)* setCharacterEncoding(String env) 设置request的缓冲区的编码* get请求* username = new String(username.getBytes("ISO-8859-1"),"UTF-8");*/// 设置request缓冲区的编码(一定要在request.getParameter("username");之前)// request.setCharacterEncoding("UTF-8");// 获取内容,做其他操作// 获取姓名String username = request.getParameter("username");// 解析get方式乱码的问题username = new String(username.getBytes("ISO-8859-1"),"UTF-8");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}