zoukankan      html  css  js  c++  java
  • springmvc返回json字符串中文乱码问题

    问题:

    后台代码如下:

        @RequestMapping("menuTreeAjax")
        @ResponseBody
        /**
         * 根据parentMenuId获取菜单的树结构
         * @param parentMenuId
         * @return
         */
        public String menuTreeAjax(Integer parentMenuId) {
            JSONArray array = menuService.getTreeMenuByParentMenuId(parentMenuId);
            return array.toString();
        }

    前台代码如下:

        $.ajax({
                url:'menuTreeAjax?parentMenuId=${menu.menuId}',
                async:false,
                dataType:"json",
                success:function(data){
                    menuTree=data;
                    alert(data[0].text);
                }
            });

    发现前台显示的json数据中的中文为???。乱码问题。

    原因:

    Spring中解析字符串的转换器默认编码居然是ISO-8859-1

    如下所示:

    解决方法:

    方法一,使用(produces = "application/json; charset=utf-8")

        @RequestMapping(value="menuTreeAjax", produces = "application/json; charset=utf-8")
        @ResponseBody
        /**
         * 根据parentMenuId获取菜单的树结构
         * @param parentMenuId
         * @return
         */
        public String menuTreeAjax(Integer parentMenuId) {
            JSONArray array = menuService.getTreeMenuByParentMenuId(parentMenuId);
            return array.toString();
        }

    方法二:在springmvc.xml配置:

      <!-- 处理请求返回json字符串的乱码问题 -->  
         <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>

     PS:如果返回的不是json,而只是一个字符串,则只需要这样就可以了。将produces改为text/html

        @ResponseBody
        @RequestMapping(value="webserviceDemo1", produces = "text/html; charset=utf-8")
        public String webserviceDemo1(){
            WeatherServiceService factory=new WeatherServiceService();
            WeatherService service=factory.getWeatherServicePort();
            String result=service.getWeatherByCityname("厦门");
            return result;
        }
  • 相关阅读:
    js拖拽效果 javascript实现将元素拖拽如某容器效果demo
    使用 transform3D 造成网页闪动的底层原因剖析
    设置文字垂直 竖向 显示
    文本光标,高亮选中一些出来
    HTMl5的sessionStorage和localStorage
    event 事件兼容性处理 keycode 大全
    收藏个支持进度条与文件拖拽上传的js File Uploader
    three.js 3D效果
    Winform下的地图开发控件(GMap.NET)使用心得
    ASP.NET Forms验证 实现子域名(SubDomain)共享登陆下的缺陷
  • 原文地址:https://www.cnblogs.com/roy-blog/p/7048401.html
Copyright © 2011-2022 走看看