1.Servlet的解决办法
1.请求乱码
(1) httpServletRequest.setCharacterEncoding()
1 2 3 4 5 6 7
| try { httpServletRequest.setCharacterEncoding("UTF-8"); String name = httpServletRequest.getParameter("name"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
|
(2)配置Tomcat
conf/server.xml添加URIEncoding="UTF-8"
1
| <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8" />
|
(3)String(byte[] bytes, String charsetName)
1 2 3 4 5 6 7
| String name = httpServletRequest.getParameter("name"); try { String nameParam = new String(name.getBytes(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }
|
2.响应乱码
1 2 3 4 5 6 7 8 9 10 11 12
| try { httpServletResponse.setCharacterEncoding("UTF-8"); PrintWriter printWriter = httpServletResponse.getWriter(); printWriter.write("hello world"); } catch (IOException e) { e.printStackTrace(); }
httpServletResponse.setContentType("text/html;charset=UTF-8");
|
3.过滤器
2.SpringMVC的解决方法(过滤器)
web.xml配置文件中添加配置,配置SpringMVC编码过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>01_springmvc_hello</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name>
<servlet-name>springmvc</servlet-name> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
|
3.数据库乱码
(1)创建数据库时指定编码
(2)修改jdbc连接url
1
| jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8
|
(3)修改mysql数据库的默认编码
mysql安装目录的my.ini
配置文件
注: utf8
不加-