1,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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

2.Controller

 @RequestMapping("/test")
@ResponseBody
public String test(HttpServletResponse re){
JSONObject json=new JSONObject();
json.put("msg", "测试");    re.setHeader("Charset", "UTF-8");    re.setContentType("application/x-www-form-urlencoded; charset=utf-8");
return json.toString();
}

3.ajax

$.ajax({
type : "GET",
url : "../cart/test",
data:{},
datatype : "json",
scriptCharset: 'UTF-8',
success : function(result) {
var data = JSON.parse(result);
},
error : function(result) {
var data = JSON.parse(result);
}

仍旧乱码,另外jsp页面、tomcat、项目、General下的Workspace全部设为UTF-8仍旧乱码

最终发现 <mvc:annotation-driven/>

这个意思是说注解驱动,@作用:springMVC为@Controllers分发请求所必须的。
并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。

@作用:(Springmvc3)

<!-- 注解请求映射  -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="logNDCInteceptor"/> <!-- 日志拦截器,这是你自定义的拦截器 -->
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="byteArray_hmc" />
<ref bean="string_hmc" />
<ref bean="resource_hmc" />
<ref bean="source_hmc" />
<ref bean="xmlAwareForm_hmc" />
<ref bean="jaxb2RootElement_hmc" />
<ref bean="jackson_hmc" />
</list>
</property>
</bean>
<bean id="byteArray_hmc" class="org.springframework.http.converter.ByteArrayHttpMessageConverter" /><!-- 处理.. -->
<bean id="string_hmc" class="org.springframework.http.converter.StringHttpMessageConverter" /><!-- 处理.. -->
<bean id="resource_hmc" class="org.springframework.http.converter.ResourceHttpMessageConverter" /><!-- 处理.. -->
<bean id="source_hmc" class="org.springframework.http.converter.xml.SourceHttpMessageConverter" /><!-- 处理.. -->
<bean id="xmlAwareForm_hmc" class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter" /><!-- 处理.. -->
<bean id="jaxb2RootElement_hmc" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" /><!-- 处理.. -->
<bean id="jackson_hmc" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /><!-- 处理json-->

其中StringHttpMessageConverter的作用是

看源码:

/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.http.converter; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List; import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils; /**
* Implementation of {@link HttpMessageConverter} that can read and write strings.
*
* <p>By default, this converter supports all media types ({@code */*}),
* and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden
* by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class StringHttpMessageConverter extends AbstractHttpMessageConverter<String> { public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1"); private final Charset defaultCharset; private final List<Charset> availableCharsets; private boolean writeAcceptCharset = true; /**
* A default constructor that uses {@code "ISO-8859-1"} as the default charset.
* @see #StringHttpMessageConverter(Charset)
*/
public StringHttpMessageConverter() {
this(DEFAULT_CHARSET);
} /**
* A constructor accepting a default charset to use if the requested content
* type does not specify one.
*/
public StringHttpMessageConverter(Charset defaultCharset) {
super(new MediaType("text", "plain", defaultCharset), MediaType.ALL);
this.defaultCharset = defaultCharset;
this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
} /**
* Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
* <p>Default is {@code true}.
*/
public void setWriteAcceptCharset(boolean writeAcceptCharset) {
this.writeAcceptCharset = writeAcceptCharset;
} @Override
public boolean supports(Class<?> clazz) {
return String.class == clazz;
} @Override
protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException {
Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
return StreamUtils.copyToString(inputMessage.getBody(), charset);
} @Override
protected Long getContentLength(String str, MediaType contentType) {
Charset charset = getContentTypeCharset(contentType);
try {
return (long) str.getBytes(charset.name()).length;
}
catch (UnsupportedEncodingException ex) {
// should not occur
throw new IllegalStateException(ex);
}
} @Override
protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
if (this.writeAcceptCharset) {
outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
}
Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
StreamUtils.copy(str, charset, outputMessage.getBody());
} /**
* Return the list of supported {@link Charset}s.
* <p>By default, returns {@link Charset#availableCharsets()}.
* Can be overridden in subclasses.
* @return the list of accepted charsets
*/
protected List<Charset> getAcceptedCharsets() {
return this.availableCharsets;
} private Charset getContentTypeCharset(MediaType contentType) {
if (contentType != null && contentType.getCharSet() != null) {
return contentType.getCharSet();
}
else {
return this.defaultCharset;
}
} }

方法writeInternal将字符串指定编码输出为响应信息,而这个编码默认的是

public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

所以需要显示的指定编码private final Charset defaultCharset;

因此在<mvc:annotation-driven/>中指定如下:

<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

此时乱码问题解决

另外,也可在@RequestMapping中加入produces="text/html;charset=UTF-8",如

  @RequestMapping(value="/test",,produces="text/html;charset=UTF-8")
@ResponseBody
public String test(HttpServletResponse re){
JSONObject json=new JSONObject();
json.put("msg", "测试");    return json.toString();
}
												

ajax请求返回乱码的更多相关文章

  1. ajax请求返回数据,模板中的数据处理

    /*ajax请求返回数据,模板中的数据处理*/ function QueryGameAsset(){ var new_start_time=$('#new_start_time').val();//开 ...

  2. 在使用Ajax请求返回json数据的时候IE浏览器弹出下载保存对话框的解决方法

    在使用Ajax请求返回json数据的时候IE浏览器弹出下载保存对话框的解决方法 最近在做一个小东西,使用kindeditor上传图片的时候,自己写了一个上传的方法,按照协议规则通过ajax返回json ...

  3. AJAX请求,返回json进行页面绑值

    AJAX请求,返回json进行页面绑值 后台 controller @RequestMapping(value = "backjson.do",method=RequestMeth ...

  4. jquery发送ajax请求返回数据格式

    jquery向服务器发送一个ajax请求后,可以返回多种类型的数据格式,包括:html,xml,json,text等. 1.html格式的数据 "<div class='comment ...

  5. dotnet webservice处理数据量过大,ajax请求返回500错误解决方案

    ajax请求webservice返回json数据,数据规模过大时ajax请求会得到500的响应,webservice+ajax处理大规模的数据需要在web.config中进行如下配置: <sys ...

  6. IE bug:ajax请求返回304解决方案

    bug说明: 同一账户下的默认收货地址只有一个,默认收货地址可以修改,修改完成后,使用ajax重新加载收货地址部分. 默认收货地址状态标记:status = 1: 在IE浏览器做了修改后,重新加载的数 ...

  7. 关于IE浏览器 ajax 请求返回数据不对的问题

    在使用ajax向后台发送请求的时候,在使用ie 进行调试的时候发现根据条件进行查询时,返回的数据与没有根据条件进行查询时数据相同,也就是条件没有发生作用. 经过同事的帮助发现ajax初始化设置时没有c ...

  8. jsp Ajax请求(返回html标签)

    <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http:// ...

  9. 如何使用 window.open() 处理ajax请求返回的url: 在本页面打开并防止浏览器拦截

    ajax请求中用window.open()打开请求返回url(例如实现下载功能时),可能会因为跨域问题导致浏览器拦截 解决办法是:在请求前,打开一个窗口,请求成功后将返回的url直接赋值给该窗口的hr ...

随机推荐

  1. linux 实时同步inotify

    #实时同步inotify 1.inotify简介inotify是一种强大的,细腻度的,异步的文件系统事件监控机制,linux内核从2.6.13起,加入了inotify支持,通过INOTIFY可以监控文 ...

  2. VSCode好用的Python插件及配置

    MS Python插件. 这是微软官方的Python插件,已经自带很多功能.下面是插件功能描述,其中部分内容我做了翻译. a)        Linting (Prospector, Pylint,  ...

  3. 基于PDO的简易ORM

    #基于PRO的一个简单地ORM GitHub 项目地址 #在用原生写脚本的时候怀念起框架中封装好的ORM,所以仿照laravel写了这个简洁版的ORM,可以链式操作. #实现功能 ###条件函数 ta ...

  4. request拿各种东西

    例如 : http://localhost:8080/projectName/aaa/bbb?name=zhangsan获取项目名(目录) /projectNameString uri = reque ...

  5. 【Zookeeper】Zookeeper安装配置

    本文演示使用三台Linux服务器安装Zookeeper,使用的是zookeeper-3.4.5版本,将zookeeper-3.4.5.tar.gz上传到linux服务器, 使用如下命令解压到/usr/ ...

  6. 微信公众号问题:{"errcode":40125,"errmsg":"invalid appsecret, view more at http:\/\/t.cn\/LOEdzVq, hints: [ req_id: kL8J90219sg58 ]"}

    在调试微信公众号授权登录时遇到了这个错误,着实是心烦了半天,公众号相关开发以前是经常做的,很久没有接触了,而且遇到了这么个以前没遇到的问题. {"errcode":40125,&q ...

  7. python学习路线

    目录: 硬件: 第一篇:操作系统简介 第二篇:操作系统 linux基础: 第一篇:初始Linux 第二篇:基本使用 第三篇:Linux进阶 python基础: 第一篇:python基础大纲 第二篇:变 ...

  8. java.io.FileNotFoundException class path resource [xxx.xml] cannot be opened

    没有找到xxx.xml,首先确定你项目里有这个文件吗,如果没有请添加,或者你已经存在配置文件,只是名字不是xxx.xml,请改正名字.此外还要注意最好把xxx.xml加入到classpath里,就是放 ...

  9. Python之排序算法:快速排序与冒泡排序

    Python之排序算法:快速排序与冒泡排序 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/7828610.html 入坑(简称IT)这一行也有些年头了,但自老师 ...

  10. RED_HAWK:基于PHP实现的信息收集与SQL注入漏洞扫描工具

    无事早上就去逛freebuf看到一款不错的工具,打算介绍给大家 RED_HAWK:基于PHP实现的信息收集与SQL注入漏洞扫描工具 RED HAWK 最新版本:v1.0.0[2017年6月11日] 下 ...