每一个JAVA WEB开发者都会碰到乱码问题。本文阐述了JAVA WEB开发中乱码的完全解决方法。 JAVA中,一个WEB应用从构成部分来看无非分3部分: JSP JAVA程序(业务逻辑) 数据库 要解决乱码问题,也从这3部分入手。 其实,我们的目标很明确,第一、保证显示中文时不为乱码;第二、保证保存到数据库里的数据不为乱码。 怎么样实现上面2个目标呢?让我们从数据的输入/输出的角度来分析。一个典型的用户请求的过程为: 1)浏览器接收用户输入 2)用户输入的数据-〉JAVA程序 3)JAVA程序对数据进行处理,保存到数据库(需要保存时) 4)从数据库取出数据,返回给浏览器 原则上,如果我们能保证在上述阶段中的数据编码都采用同一个编码方式的话,就应该不会产生乱码。怎么样把它们的编码方式统一起来呢?可以通过以下几个步骤实现: 1、用Filter把用户的输入数据统一编码后再传送给JAVA程序 1) Filter可以用Tomcat提供的SetCharacterEncodingFilter.class,也可以使用如下代码自己做一个SetCharacterEncodingFilter:
java代码
- public class SetCharacterEncodingFilter
- implements Filter
- {
- protected String encoding;
- protected FilterConfig filterConfig;
- protected boolean ignore;
- /**
- * Constructor
- *
- */
- public SetCharacterEncodingFilter()
- {
- encoding = null;
- filterConfig = null;
- ignore = true;
- }
- /**
- * @see javax.servlet.Filter#destroy()
- */
- public void destroy()
- {
- encoding = null;
- filterConfig = null;
- }
- /**
- * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
- */
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
- throws IOException, ServletException
- {
- if(ignore || request.getCharacterEncoding() == null)
- {
- String encoding = selectEncoding(request);
- if(encoding != null)
- request.setCharacterEncoding(encoding);
- }
- chain.doFilter(request, response);
- }
- /**
- * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
- */
- public void init(FilterConfig filterConfig)
- throws ServletException
- {
- this.filterConfig = filterConfig;
- encoding = filterConfig.getInitParameter("encoding");
- String value = filterConfig.getInitParameter("ignore");
- if(value == null)
- ignore = true;
- else
- if(value.equalsIgnoreCase("true"))
- ignore = true;
- else
- if(value.equalsIgnoreCase("yes"))
- ignore = true;
- else
- ignore = false;
- }
- /**
- * @param request
- * @return
- */
- protected String selectEncoding(ServletRequest request)
- {
- return encoding;
- }
- }
web.xml里设置:
Xml代码
- <filter>
- <filter-name>SetEncoding</filter-name>
- <filter-class>包名.SetCharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- ...
- <filter-mapping>
- <filter-name>SetEncoding</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
如果定义后编码还有问题,注意filter-mapping在web.xml中的定义顺序。
2、 数据库采用跟HTML一样的编码。
数据库编码设置为utf-8
3、JSP里明确指定编码方式,告诉编译器采用我们指定的编码对JSP加以编译。
JSP文件的开头加上:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
4、使用HTML<meta/>标签告诉浏览器使用指定的编码
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
5、 统一资源文件(比如消息等定义文件)的编码方式。并在打包之前用转换成ASCII码。用ant工具的情况下,可以执行以下方法加以转换:
<native2ascii encoding="utf-8" src="资源文件所在路径" dest="${classes.dir}" includes="**/*.properties" />