1.web项目出现乱码问题
做web项目的时候,多多少少会出现中文乱码问题。 对于jsp页面表单提交,controller接收乱码,保存到数据库中文乱码等问题,统一给出几种乱码的解决方式。
1.项目编码没有设置为utf8 有一些普遍的乱码问题,是因为我们在创建web项目或者是导入别人的web项目的时候,没有设置项目的编码。项目没设置utf-8编码会导致中文乱码。
 

2.确保数据库编码为utf8,以mysql为例,可到mysql目录下,my.ini文件中修改后,重启mysql服务

重启mysql服务方法:
 
 
3.数据库建库时,确认编码为utf-8,以使用Navicat为例
 
4.在jsp页面乱码问题
可以在 jsp的顶端加入;
<%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8”%>
Head中加入
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8”>
form表单的提交方式设为 “Post”
5.如果使用的是spring,可以在项目的web.xml中加入:
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
6.在java代码的controller层或者是form表单提交的action中,设置:
request.setCharacterEncoding("utf-8")
7.tomcat设置
打开tomcat安装路径下的conf-server.xml 文件:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" useBodyEncodingForURI="true"/>
以上7种基本上是用来解决jsp页面表单提交,controller接收乱码,数据库乱码等问题,一般4,5,6方法最常用也是关系最大的。 比如我有写form表单,提交数据到数据库的时候,打开数据库发现中文乱码,设置什么utf-8之类的都是设置了的。 于是采用第5种方式,加入字符过滤器。 如图:

web.xml中:
 效果:
 |