SSM框架中SPRINGMVC解决中文乱码

一,在web.xml配置 post请求方式

<filter><description>字符编码过滤器</description>

<filter-name>encodingFilter</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>

<init-param>

<param-name>forceEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

2、对于get请求,在tomcat的server.xml配置文件中配置:

<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />

添加URIEncoding="utf-8"
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>

如果不改变tomcat里的配置,比如用maven,则需要用produces

produces可能不算一个注解,因为什么呢,它是注解@requestMapping注解里面的属性项,

它的作用是指定返回值类型,不但可以设置返回值类型还可以设定返回值的字符编码;

还有一个属性与其对应,就是consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

他们的使用方法如下:

一、produces的例子

produces第一种使用,返回json数据,下边的代码可以省略produces属性,因为我们已经使用了注解@responseBody就是返回值是json数据:

 

@Controller

@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")

@ResponseBody

public Pet getPet(@PathVariable String petId, Model model) {

 implementation omitted

}


produces第二种使用,返回json数据的字符编码为utf-8.:

 

@Controller

@RequestMapping(value = "/pets/{petId}", produces="MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8")

@ResponseBody

public Pet getPet(@PathVariable String petId, Model model) {

 implementation omitted

}


二、consumes的例子(方法仅处理request Content-Type为“application/json”类型的请求。)

@Controller  

@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")  

public void addPet(@RequestBody Pet pet, Model model) {      

    // implementation omitted  

}  

猜你喜欢

转载自blog.csdn.net/zalan01408980/article/details/82704917