ajax请求返回乱码

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.setCharacterEncoding("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>

此时乱码问题解决

时间: 2024-11-10 14:18:03

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

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

/*ajax请求返回数据,模板中的数据处理*/ function QueryGameAsset(){ var new_start_time=$('#new_start_time').val();//开始时间 var new_end_time=$('#new_end_time').val();//结束时间 if(!new_start_time||!new_end_time){ alert("时间不能为空"); return false; } $.ajax({ url:'/Statisti

ajax请求返回Json字符串运用highcharts数据图表展现数据

[1].[图片] Json字符串和highcharts数据图表展现.jpg 跳至 [1] [2] [2].[代码] Json字符串和highcharts数据图表展现 跳至[1] [2] 001 /* 002 * Filename: OQtyOrPriceReport.js 003 * Description:客户订单数量和价格报表分析 004 * Created: 2013.11.14 005 * Author : liangjw 006 * Company:Copyright (C) 2013

SpringMVC使用Ajax请求返回中文乱码

前言: 最近在写一个JavaWeb后台时采用了spring+MyBatis+MySQL的方式.记录下遇到的关键问题 接口返回数据相关 使用@ResponseBody后返回NUll 说明:刚把后台运行起来,兴高采烈的测试接口数据,结果无论如何都是返回null, 最终通过各种百度,发现原来是没有引入关键的Jar包. 解决办法: 需要引入jackson的jar包(jackson core和jackson mapper),引入后 图: 使用@RequestMapping返回中文乱码 原因分析:(网上基本

ajax请求返回map,并遍历

最近老用到ajax请求数据,但是每次都遇到一点梗,浪费了些许时间,所以记录下来. $.ajax({ type: "POST", url: "<%=path%>/account/queryRolesAndGroups.action", data: "enterpriseId="+eid, success: function(msg){ var obj=eval("(" + msg + ")");

Ajax请求返回Json数据

介绍一下用Ajax向服务器请求数据的方法,以及对于返回的Json数据的使用. 1 $.ajax({ 2 type:"post", 3 async:false, 4 url: ******** 5 data:{"province":$("#provice").val(), 6 "city":$("#city").val(), 7 "area":$("#area").va

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

1 jquery向服务器发送一个ajax请求后,可以返回多种类型的数据格式,包括:html,xml,json,text等. 2 3 1.html格式的数据 4 5 "<div class='comment'><h6> "+username+" :</h6><p class='para'> "+content+" </p></div>" 6 7 服务器端返回数据格式是html片

AJAX请求返回HTTP 400 错误 - 请求无效 (Bad request)

在ajax请求后台数据时有时会报HTTP400错误-请求无效(Badrequest);出现这个请求无效报错说明请求没有进入到后台服务里: 原因: 1)前端提交数据的字段名称或者是字段类型和后台的实体类不一致,导致无法封装: 2)前端提交的到后台的数据应该是json字符串类型,而前端没有将对象转化为字符串类型: 3)少传参数,后台要求必传的参数 解决方案: 1)对照字段名称,类型保证一致性 2)使用stringify将前端传递的对象转化为字符串data:JSON.stringify(param);

Chrome 调试AJAX请求返回的JS脚本

有时候会使用AJAX请求加载局部的Html页面,这个时候如果想调试局部页面中的js就比较麻烦,现在暂时发现了两种方法.第一种是在js代码中想要断点的地方加debugger,这样代码执行到此处会进入断点.此时你会发现进入断点的js文件名称是VM+数字,关于Chrome的VMJS脚本可以查看这个文档.Chrome VM B乎的解释 除了增加debugger这种略显麻烦的方式外,还有另外一种调试的方式.那就是在脚本首部增加这行代码. //# sourceURL=名字随意起.js 经测试,在Chrome

jsp Ajax请求(返回xml数据类型)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP page</title> <s