1. 程式人生 > 其它 >springMVC裡面後端json資料中文亂碼問題解決

springMVC裡面後端json資料中文亂碼問題解決

1.在
@RequestMapping(value = "j1",produces = "application/json;charset=utf-8")

註解中加入produces的編碼解釋

package wsh.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import wsh.pojo.User; @Controller public class userController { @RequestMapping(value = "j1",produces = "application/json;charset=utf-8") @ResponseBody public String json01() throws JsonProcessingException { ObjectMapper mapper
=new ObjectMapper(); User user=new User("版本",11,"貓貓"); String str=mapper.writeValueAsString(user); return str; } }

2.在springMVC配置檔案中做亂碼統一處理

mvc:annotation-driven

標籤內既是亂碼處理官方方式

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <context:component-scan base-package="wsh.controller"/> <mvc:default-servlet-handler/> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="defaultCharset" value="utf-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver"> <property name="prefix" value="/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>

處理效果