解决Spring MVC @ResponseBody返回中文字符串乱码问题

引起乱码原因为spring mvc使用的默认处理字符串编码为ISO-8859-1,具体参考org.springframework.http.converter.StringHttpMessageConverter类中public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");

 

 

  • 第一种方法:

 

对于需要返回字符串的方法添加注解,如下:

	/***
	 * 返回类型是string需要用produces进行转码,并格式化
	 * json格式化 可以用Gson处理(obj <-> json)互相转换
	 * @return
	 * @date 2017年5月12日
	 * @author wanwenjun
	 */
	@RequestMapping(value="/stu",produces="application/json; charset=utf-8")
	@ResponseBody
	public String getStudent(){
		
		Student s = (Student) SpringContext.getBean("student");
		
		Gson gson = new Gson();
		
		//obj to String
		String stu = gson.toJson(s);
		
		//String to obj
		Student s2 = gson.fromJson(stu,Student.class);
		
		System.out.println(s2.toString());
		
		return stu;
	}

 使用modelandview,需Jackson支持,如下:

	/****
	 * 效果和Map一致,但需要jackson jar包支持
	 * @date 2017年5月12日
	 * @author wanwenjun
	 * @return ModelAndView
	 */
	@ResponseBody
	@RequestMapping(value="/student")
	public ModelAndView getStu(String a){
		Student s = (Student) SpringContext.getBean("student");
		
		Map<String, Student> map = new HashMap<>();
		map.put("stu", s);
		
		return new ModelAndView(new MappingJackson2JsonView(),map);
	}

 

 

上述方法只针对单个调用方法起作用。

两种方式有什么区别呢?

方式一:使用ModelAndView的contentType是"application/json"

方式二:返回String的            contentType是"text/html"

那么如何设置response的content type呢?

使用注解@RequestMapping 中的produces:

  • 第二种方法

在配置文件中加入:

<mvc:annotation-driven>
     <mvc:message-converters register-defaults="true">
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
    </bean>
   </mvc:message-converters>
     </mvc:annotation-driven>

 参考:http://stackoverflow.com/questions/3616359/who-sets-response-content-type-in-spring-mvc-responsebody

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值