Servlet学习笔记—request获得参数中文乱码问题解决
2017-11-04 10:00
597 查看
一、使用post请求方式的时候
html页面如下<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>中文乱码示例</h1> <form action="/www/demo" method="post"> 姓名:<input name="name" type="text"><br> <input type="submit" value="提交"> </form> </body> </html>
当处理post请求如下的时候,会出现中文乱码的问题
String name = req.getParameter("name"); System.out.println(name);
出现中文乱码问题的原因是由于html页面的编码方式是UTF-8,而在处理post参数的时候,默认是使用ISO-8859-1这种拉丁文编码方式,因此会出现中文乱码的问题
解决方式一(比较麻烦,不推荐):
String name = req.getParameter("name"); System.out.println(name);
name=new String(name.getBytes("ISO-8859-1"),"UTF-8");//重新用utf-8来编码
System.out.println(name);
解决方式二(推荐使用):
在处理post参数请求的时候,指定用UTF-8这种编码方式,就不会出现乱码的情况(注意:使用这种方式的时候一定要在所有的获取post参数的方式之前)//在获取参数之前,先指定UTF-8的编码方式,这样以后获取post参数的时候,都会统一使用UTF-8的编码方式
req.setCharacterEncoding("UTF-8");
String name = req.getParameter("name"); System.out.println(name);
二、使用get请求方式的时候
在使用tomcat8.x及以上版本的时候没有中文乱码的问题
html页面如下<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>中文乱码示例</h1> <a href="/wwwz/demo?describe=中文乱码">点击发送get请求</a> </body> </html>
解决方式一(比较麻烦,不推荐):
String describe = req.getParameter("describe"); describe=new String(describe.getBytes("ISO-8859-1"),"UTF-8"); System.out.println(describe);
解决方式二(推荐使用):
修改tomcat服务器的server.xml文件,在Connector节点加入URIEncoding=”UTF-8”如下:
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8" redirectPort="8443"/>
相关文章推荐
- 20160324servlet学习笔记HttpServletRequest对象中文乱码解决方法
- struts2学习笔记----------struts2.1.6接收中文请求参数乱码问题
- jsp中request接收中文参数乱码问题解决办法
- JSP+Servlet学习经验1:解决form表单提交后相应页面中文乱码的问题
- JSP学习笔记(三):解决JSP中文乱码问题
- SprintBoot学习笔记(5):解决中文乱码问题
- HttpServletRequest解决中文乱码的问题
- Java学习笔记37:Spring 使用 @ResponseBody 返回中文乱码问题解决
- node.js 学习笔记(一) 解决node里中文乱码问题
- flex URLRequest传中文参数到后台乱码问题解决方法
- spring boot 学习笔记(5) 解决HttpServletRequest inputStream只能读取一次的问题
- json传递中文乱码解决方法以及解决request.getParameter()获取参数为乱码的问题
- Struts2 学习笔记 —— 10 —— Action接收参数时的中文乱码问题
- JSP内置对象(包括request和response)以及解决url传中文参数出现乱码问题
- 解决 jsp传中文参数到servlet出现乱码问题
- 【MySQL学习笔记】4:解决JDBC连接MySQL的query结果中文乱码问题
- Java 解决 servlet 接收参数中文乱码问题
- robot framework学习笔记之八—解决列表或者字典中文乱码问题
- 解决var url="xxx&参数名="+“中文参数”; 传到后台根据String x = request.getParameter("中文参数名");乱码问题
- [学习笔记]Servlet 中文乱码问题及解决方案剖析