1.jsp页面
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
2.jdbc获取连接时候
DriverManager.getConnection("jdbc:mysql://localhost:3306/developerdb?useUnicode=true&characterEncoding=utf8", "developer", "developer");
3.Tomcat
览器请求传到Tomcat容器的时候还会经历一次编码转换,而Tomcat7.0对请求的默认编码字符集是ISO8859-1,所以解决方法就是在java代码里对请求再次进行编码转换。其中有两种处理方式:
(1)对参数值的字符串进行编码转换。
new String(request.getParameter("name").getByte("ISO-8859-1"),"UTF-8");
(2)对进入容器的所有请求进行编码转换。这个方式需要配置一个过滤器,然后在web.xml中调用
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); chain.doFilter(request, response); }
或者在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>
4.在安装数据库时编码选择以及在新建数据库时的编码选择。