Servlet中的中文乱码问题

xiaoxiao2021-02-27  288

启动Servlet时因为前后端牵涉的东西比较多,请求交互双方外加servlet容器,在输入中文的时候出现乱码我们应该怎么处理? 乱码处理关注点总结:【牧牛遛马】

以下以utf-8编码设置实现:

1、交互双方的编码需要保持一致:

在servlet的service方法中设置,当然如果使用继承至HttpServlet时,在doPost,doGet方法中进行设置:

response.setCharacterEncoding("utf8"); request.setCharacterEncoding("utf8"); reponse.setHeader("Content-Type","text/html;charset=utf8");

2、客户页面的编码设置与后台编码一致:

<meta http-equiv="Content-Type" content="text/html;charset=utf8">

3、把Tomcat的编码也设置为一致编码

修改Tomcat中Conf目录下的server.xml文件

<connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8" />

4、检查修改Servlet程序的编码格式

在Eclipse下面找到 Windows—preference—-general—workspace下面修改。

5、转码

修改客户端传过来的编码格式:

String str = new String(request.getParameter("name").getBytes("ISO-8859-I"),"utf-8");

转载请注明原文地址: https://www.6miu.com/read-7160.html

最新回复(0)