request.getParameter()在get和post方法中文乱码问题

时间:2023-03-10 01:58:01
request.getParameter()在get和post方法中文乱码问题

乱码原因:Http请求传输时将url以ISO-8859-1编码,服务器收到字节流后默认会以ISO-8859-1编码来解码成字符流(造成中文乱码)

post请求:

假设提交请求的jsp页面是UTF-8编码

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

解决方法1:在服务端获取参数前,先设置解码方式。

//设置解码方式,对于简体中文,使用UTF-8解码
request.setCharacterEncoding("UTF-8");
request.getParameter("参数名");

解决方法2:Tomcat默认编码ISO8859-1,设置成其他的编码

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8444"
useBodyEncodingForURI="true"
URIEncoding="UTF-8"/>

解决方法3:通过字符串和字节流转换时使用正确的编码获取中文参数

String str = new String(request.getParameter("参数名").getBytes("iso-8859-1"), "utf-8"); 

Get请求 ,只有第三种方法有效。