zoukankan      html  css  js  c++  java
  • ResponseBody的使用

    使用Spring的@ResponseBody有时还是挺方便的,在ajax调用返回纯字符串时有中文编码问题。
    @ResponseBody
    @RequestMapping(value="/decode", produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")
    public String decode(HttpServletResponse response, @RequestParam String token) {
        return "大家好";
        //return new String("大家好".getBytes("utf-8"),"iso-8859-1");
        //如果不指定utf-8编码,麻烦一点转成iso-8859-1的字符串也行
    }
    参考spring源码:StringHttpMessageConverter会从MediaType获取编码(分析charset参数),默认是ISO-8859-1不支持中文。
        private Charset getContentTypeCharset(MediaType contentType) {
            if (contentType != null && contentType.getCharSet() != null) {
                return contentType.getCharSet();
            }
            else {
                return DEFAULT_CHARSET;
            }
        }
        public Charset getCharSet() {
            String charSet = getParameter(PARAM_CHARSET);//charset
            return (charSet != null ? Charset.forName(charSet) : null);
        }
     
    还有一种使用场景就是实现服务端接口返回json文本数据,MappingJacksonHttpMessageConverter默认就是utf-8编码
    @RequestMapping(value="/api/item/getMallItem.json",produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object getMallItem(HttpServletRequest request,Model model){
        model.addAttribute("status", 0);
        return model;
    }
    MappingJacksonHttpMessageConverter,部分源码:
        protected JsonEncoding getJsonEncoding(MediaType contentType) {
            if (contentType != null && contentType.getCharSet() != null) {
                Charset charset = contentType.getCharSet();
                for (JsonEncoding encoding : JsonEncoding.values()) {
                    if (charset.name().equals(encoding.getJavaName())) {
                        return encoding;
                    }
                }
            }
            return JsonEncoding.UTF8;
        }




  • 相关阅读:
    让xamarin的Entry绑定时,支持Nullable类型
    xamarin.forms 绑定页面里指定元素的某个属性值
    俄文环境下,字符串转数字失败
    使用devstack安装openstack
    在linux中访问macos 下的分区。
    git 多用户多仓库配置
    Macos上 ProxyChains 的坑, 需要关闭 sip
    MacOS 的预览 Preview 打开pdf 容易卡死 解决方案
    一客户端使用多个密钥对登录多个主机的解决方案.
    MacOS 10.13.6 下装xcode 流程
  • 原文地址:https://www.cnblogs.com/xingqi/p/3412815.html
Copyright © 2011-2022 走看看