方法一
在web.xml文件中注册过滤器
<!-- 注册过滤器 设置编码 --><filter><filter-name>CharacterEncodingFilter</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>forceResponseEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
方法二
在注解中添加编码设置,主要是处理ajax请求乱码
produces = “text/html;charset=utf-8”
@RequestMapping(value="/getMajorList2",produces = "text/html;charset=utf-8")@ResponseBodypublic String getMajorList2(){List<Major> majorList=new ArrayList<Major>();majorList.add(new Major(1,"计算机"));majorList.add(new Major(2,"英语"));return JSON.toJSONString(majorList);}
方法三
修改tomcat的sever.xml文件
添加 URIEncoding=“utf-8”
主要解决post请求乱码
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="utf-8" />