|
| 1 | +# 非SpringBoot项目中文乱码解决方案 |
| 2 | + |
| 3 | +前台页面向后台提交参数的时候,中文经常出现乱码问题,可以检查一下下边的配置。 |
| 4 | +1.检查项目的编码是否为UTF-8 |
| 5 | +2.设置tomcat服务的编码,在server.xml文件中修改为如下 |
| 6 | + <Connector URIEncoding="UTF-8" port="8888" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" /> |
| 7 | +3.在web.xml中添加编码过滤配置设置为UTF-8,这里使用springmvc的编码过滤 |
| 8 | + |
| 9 | +```xml |
| 10 | +<?xml version="1.0" encoding="UTF-8"?> |
| 11 | +<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" |
| 12 | + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
| 13 | + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" |
| 14 | + version="3.1"> |
| 15 | + <!--方式一,使用默认配置 |
| 16 | + 默认读取的springmvc配置文件为/WEB-INF/<servlet-name>-servlet.xml |
| 17 | + --> |
| 18 | + <!-- <servlet> |
| 19 | + <servlet-name>springmvc</servlet-name> |
| 20 | + <!– springMVC的入口,分发器,管家 ,分发器默认读取/WEB-INF/<servlet-name>-servlet.xml文件–> |
| 21 | + <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> |
| 22 | + <!– 1表示tomcat启动的时候,springmvc也初始化 –> |
| 23 | + <load-on-startup>1</load-on-startup> |
| 24 | + </servlet> |
| 25 | + <servlet-mapping> |
| 26 | + <servlet-name>springmvc</servlet-name> |
| 27 | + <url-pattern>/</url-pattern><!– /表示拦截所有请求,也可以 *.do *.html 等 –> |
| 28 | + </servlet-mapping>--> |
| 29 | + |
| 30 | + <!--方式二,手动指定springmvc配置文件的路径 |
| 31 | + 推荐使用这种方式 |
| 32 | + --> |
| 33 | + <servlet> |
| 34 | + <servlet-name>springmvc</servlet-name> |
| 35 | + <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> |
| 36 | + <!-- 读取指定目录下的配置文件,名字可以改变 |
| 37 | + *表示加载该目录以及子目录下的所有springmvc-servlet.xml |
| 38 | + 不加*只会加载指定路径下的指定文件 |
| 39 | + --> |
| 40 | + <init-param> |
| 41 | + <param-name>contextConfigLocation</param-name> |
| 42 | + <param-value> |
| 43 | + classpath*:configs/springmvc-annotaion-servlet.xml |
| 44 | + </param-value> |
| 45 | + </init-param> |
| 46 | + <load-on-startup>1</load-on-startup> |
| 47 | + </servlet> |
| 48 | + <servlet-mapping> |
| 49 | + <servlet-name>springmvc</servlet-name> |
| 50 | + <url-pattern>/</url-pattern><!-- /表示拦截所有请求,也可以 *.do *.html 等 --> |
| 51 | + </servlet-mapping> |
| 52 | + |
| 53 | + <!--编码过滤,使用spring的编码过滤类--> |
| 54 | + <filter> |
| 55 | + <filter-name>encodingFilter</filter-name> |
| 56 | + <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> |
| 57 | + <init-param> |
| 58 | + <param-name>encoding</param-name><!--设置为那种编码--> |
| 59 | + <param-value>UTF-8</param-value> |
| 60 | + </init-param> |
| 61 | + <init-param> |
| 62 | + <param-name>forceEncoding</param-name><!--是否强制过滤--> |
| 63 | + <param-value>true</param-value> |
| 64 | + </init-param> |
| 65 | + </filter> |
| 66 | + <filter-mapping> |
| 67 | + <filter-name>encodingFilter</filter-name> |
| 68 | + <url-pattern>/*</url-pattern><!--那种请求需要编码过滤,这里对所有的请求进行编码过滤--> |
| 69 | + </filter-mapping> |
| 70 | +</web-app> |
| 71 | +``` |
0 commit comments