<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
2、JDBC获取连接时:
<span style="font-size:14px;">DriverManager.getConnection("jdbc:mysql://localhost:3306/developerdb?useUnicode=true&characterEncoding=utf8", "developer", "developer");</span>
浏览器请求传到Tomcat容器的时候还会经历一次编码转换,而Tomcat7.0对请求的默认编码字符集是ISO8859-1(还没找到Tomcat的官方文档来支持这一观点),所以解决方法就是在java代码里对请求再次进行编码转换。其中有两种处理方式:
(1)对参数值的字符串进行编码转换。
new String(request.getParameter("name").getByte("ISO-8859-1"),"UTF-8");
(2)对进入容器的所有请求进行编码转换。这个方式需要配置一个过滤器,然后在web.xml中调用
<span style="font-size:14px;">public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); chain.doFilter(request, response); }</span>或在servlet的doPost方法的最开始加上两句
request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8");
(3)如果使用spring,可以直接调用spring的包
<!-- CharacterEncodingFilter provided by SpringFramework --> <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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>