解決SpringMVC的@ResponseBody返回中文亂碼

SpringMVC的@ResponseBody返回中文亂碼的緣由是SpringMVC默認處理的字符集是ISO-8859-1,在Spring的org.springframework.http.converter.StringHttpMessageConverter類中能夠看到以下代碼:html

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

解決返回中文亂碼的問題有兩種,第一種是局部的,只針對於某個方法的返回進行處理,第二種是全局的,針對於整個項目,以下:java

第一種:在@RequestMapping中添加produces="text/html;charset=UTF-8,如:spring

@RequestMapping(value="/login.do",method=RequestMethod.POST,produces="text/html;charset=UTF-8")  @ResponseBody  public String login(@RequestParam(value="username") String userName,@RequestParam(value="password") String password){   return JSONMessageUtil.getSuccessJSON("登陸成功");  }

第二種:在配置文件中的mvc:annotation-driven中添加以下代碼:mvc

<mvc:annotation-driven >   <!-- 消息轉換器 -->   <mvc:message-converters register-defaults="true">    <bean class="org.springframework.http.converter.StringHttpMessageConverter">     <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>    </bean>   </mvc:message-converters>  </mvc:annotation-driven>  <mvc:resources location="/resources/" mapping="/resources/**" />

對於亂碼問題,這樣就能夠正常顯示中文了app

相關文章
相關標籤/搜索