现在的位置: 首页 > 综合 > 正文

springmvc中文乱码的问题

2017年12月27日 ⁄ 综合 ⁄ 共 2518字 ⁄ 字号 评论关闭

链接:http://developer.51cto.com/art/200708/53612.htm

链接:http://blog.csdn.net/chenghui0317/article/details/10299103

 

---中文乱码问题:
1。设置Tomcat config编码 (ok)
2。设置Filter过滤器,配置utf-8编码 (无效???)
3。在AnnotationMethodHandlerAdapter的bean中配置StringHttpMessageConverter (移除掉<mvc:annotation-driven/>才ok)
4。取得response对象,设置编码encode、contentType后返回(ok)
5。<mvc:annotation-driven>内配置StringHttpMessageConverter(ok)
6。前台编码utf-8后再发送数据,后台拿到数据后先解码utf-8

1.配置Tomcat config:
<Connector connectionTimeout="20000" port="8888" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>  

2.web.xml
(no???)

	<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>/*</url-pattern>
	</filter-mapping> 

3.springmvc转换器

注意:这样配置的时候要移除掉默认的<mvc:annotation-driven>,不然会不起作用(why??),另外配置上<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />等等。

	<!--启动Spring MVC的注解功能,设置编码方式,防止乱码 -->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean class="org.springframework.http.converter.StringHttpMessageConverter">
					<property name="supportedMediaTypes">
						<list>
							<value>text/plain;charset=UTF-8</value>
						</list>
					</property>
				</bean>
			</list>
		</property>
	</bean> 

 

4.response

			try {
				response.setCharacterEncoding("utf-8");
				response.setContentType("text/html;charset=UTF-8");
				OutputStream out = response.getOutputStream();
				PrintWriter pw = new PrintWriter(new OutputStreamWriter(out,"utf-8"));
				pw.println(result);
				pw.flush();
				pw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

 

5、<mvc:annotation-driven>

<pre class="html" name="code">	<!-- 简化springmvc的相关配置 -->
	<mvc:annotation-driven>
		<!-- 解决utf-8页面乱码问题 -->
		<mvc:message-converters register-defaults="true">
			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
				<!-- <property name="supportedMediaTypes" value="text/pain;charset=UTF-8" /> -->
				<property name="supportedMediaTypes">
						<list>
							<value>text/plain;charset=UTF-8</value>
							<value>text/html;charset=UTF-8</value>
							<value>application/json;charset=UTF-8</value>
						</list>
				</property>
			</bean>
		</mvc:message-converters>
	</mvc:annotation-driven>


 

 

6。前台编码utf-8后再发送数据,后台拿到数据后先解码utf-8

链接:http://blog.sina.com.cn/s/blog_9385f6d90101dzf2.html
链接:http://gaojiewyh.iteye.com/blog/1297746

抱歉!评论已关闭.