request获取中文乱码的问题

乱码问题解决:
	* 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);
	}

}



 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值