一、SpringMVC中的中文乱码问题
a:处理全局请求的中文乱码(配置Web.xml的字符编码过滤器)
<filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
b : 异步Ajax乱码处理(配置Springmvc-Servlet.xml)
<!-- 批量创建处理器映射 --> <mvc:annotation-driven> <!-- 配置异步请求中文乱码全局处理 --> <mvc:message-converters> <!-- 将请求的信息转换为String,默认ISO-8859-1,改为utf8 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <!--阿里fastjson的中文支持 --> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json</value> </list> </property> <property name="features"> <list> <!--fastjson日期格式的转换,配合实体类@jsonField注解 --> <value>WriteDateUseDateFormat</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
二、Servlet中文乱码
不乱码的条件:
1.JSP页面本身的编码 pageEncoding UTF-8
(把jsp页面翻译成java在编译为class文件的编码格式)
2.浏览器渲染页面采用的编码 contentType UTF-8
3.服务器保存数据采用的编码(request) UTF-8
-------------------------------------------
上述条件1和2中,如果只指定了一种编码方式的话,另一种也默认指定该编码方式.
-------------------------------
get()和post()都可以防止乱码
name = new String(name.getBtyes("ISO-8859-1"),"UTF-8");%>
----------------------------------------------------
post提交方式防止乱码:
request.setCharactorEncoding("utf-8");
response.setCharacterEncoding("UTF-8");
注:只设置内部保存数据的格式,不包括URL的格式
----------------------------------------------
get提交方式防止乱码:
1.修改URL编码:修改Tomcat-conf-server.xml文件
<connector port="6060" URIEncoding="UTF-8"/>
------------------------------------------------------
在过滤器页面设置统一编码格式
........
---------------------------------------------------------
contentType:定义响应的资源类型,也可以包含JSP页面和响
应内容的字符集,定义浏览器渲染页面的格式
pageEncoding:指定JSP文件的字符集及默认的contentType
字符集。它定义了JSP-》.java->.class过程
的编码格式。
-----------------------------------------------------------------
关于在Servlet中,跳转渲染页面的中文乱码问题:
跳转语句:
out.print("<script type='text/javascript'>alert('你输入的账号密码有误!');location.href='index.jsp';</script>");
原因:Servlet中不能为渲染页面设置pageEncoding=“utf-8”,所以只能设置
response.setContentType("text/html;charset=utf-8");