090_乱码问题解决
目录
Tomcat设置编码
请求参数乱码解决,web.xml配置编码过滤器
<!--编码过滤器-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
统一处理乱码,springmvc-servlet.xml配置消息转换
<!--
支持MVC注解驱动
在spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效,必须向上下文中注册DefaultAnnotationHandlerMapping和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类和方法级别处理
而annotation-driven配置帮助我们自动完成上述两个实例的注入
-->
<mvc:annotation-driven>
<!--配置消息转换,解决乱码问题-->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg 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>
返回值乱码解决,@GetMapping配置produces,设置返回值类型和编码,注:如果配置了mvc消息转换,可以不用配置produces,优点是不需要每个方法都配置produces
package com.qing.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qing.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@GetMapping(value = "/j2",produces = "application/json;charset=utf-8")
@ResponseBody // 添加@ResponseBody,就不会走视图解析器
public String json02() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
User user = new User("张三丰","123456",999);
String jsonStr = mapper.writeValueAsString(user);
return jsonStr;
}
}


浙公网安备 33010602011771号