Tomcat中的中文问题解决

这些天开发一个项目,服务器是tomcat,操作系统是xp,采用的是MVC架构,模式是采用Facade模式,总是出现乱码,自己也解决了好多天,同事 也帮忙解决,也参考了网上众多网友的文章和意见,总算是搞定。但是好记性不如烂笔杆,所以特意记下,以防止自己遗忘,同时也给那些遇到同样问题的人提供一 个好的参考途径:
(一) JSP页面上是中文,但是看的时候是乱码:
解 决的办法就是在JSP页面的编码的地方<% @ page language="java" contentType="text/html;charset=GBK" %>,因为Jsp转成 Java文件时的编码问题,默认的话有的服务器是ISO-8859-1,如果一个JSP中直接输入了中文,Jsp把它当作ISO8859-1来处理是肯定 有问题的,这一点,我们可以通过查看Jasper所生成的Java中间文件来确认
(二) 当用Request对象获取客户提交的汉字代码的时候,会出现乱码:
解决的办法是:要配置一个filter,也就是一个Servelet的过滤器,代码如下:


001 
002 package com.xxx.utils;
003 
004 import org.apache.commons.logging.Log;
005 import org.apache.commons.logging.LogFactory;
006 
007 import java.io.IOException;
008 import javax.servlet.Filter;
009 import javax.servlet.FilterChain;
010 import javax.servlet.FilterConfig;
011 import javax.servlet.ServletException;
012 import javax.servlet.ServletRequest;
013 import javax.servlet.ServletResponse;
014 
015 
016 /**
017  <p>Filter that sets the character encoding to be used in parsing the
018  * incoming request.</p>
019  <p>Configuration of this filter is based on
020  * the following initialization parameters:</p>
021  <ul>
022  <li><strong>encoding</strong> - The character encoding to be configured
023  * for this request, either conditionally or unconditionally based on
024  * the <code>ignore</code> initialization parameter.  This parameter
025  * is required, so there is no default.</li>
026  <li><strong>ignore</strong> - If set to "true", any character encoding
027  * specified by the client is ignored, and the value returned by the
028  <code>selectEncoding()</code> method is set.  If set to "false,
029  <code>selectEncoding()</code> is called <strong>only</strong> if the
030  * client has not already specified an encoding.  By default, this
031  * parameter is set to "true".</li>
032  </ul>
033  <p/>
034  <p>Although this filter can be used unchanged, it is also easy to
035  * subclass it and make the <code>selectEncoding()</code> method more
036  * intelligent about what encoding to choose, based on characteristics of
037  * the incoming request (such as the values of the <code>Accept-Language</code>
038  * and <code>User-Agent</code> headers, or a value stashed in the current
039  * user's session.</p>
040  *
041  */
042 
043 public class SetCharacterEncodingFilter implements Filter {
044     /**
045      * Logger for this class
046      */
047     private static final Log logger = LogFactory
048             .getLog(SetCharacterEncodingFilter.class);
049 
050 
051     // ----------------------------------------------------- Instance Variables
052 
053 
054     /**
055      * The default character encoding to set for requests that pass through
056      * this filter.
057      */
058     protected String encoding = null;
059 
060 
061     /**
062      * The filter configuration object we are associated with.  If this value
063      * is null, this filter instance is not currently configured.
064      */
065     protected FilterConfig filterConfig = null;
066 
067 
068     /**
069      * Should a character encoding specified by the client be ignored?
070      */
071     protected boolean ignore = true;
072 
073 
074     // --------------------------------------------------------- Public Methods
075 
076 
077     /**
078      * Take this filter out of service.
079      */
080     public void destroy() {
081         this.encoding = null;
082         this.filterConfig = null;
083     }
084 
085 
086     /**
087      * Select and set (if specified) the character encoding to be used to
088      * interpret request parameters for this request.
089      *
090      @param request  The servlet request we are processing
091      @param response The servlet response we are creating
092      @param chain    The filter chain we are processing
093      @throws IOException      if an input/output error occurs
094      @throws ServletException if a servlet error occurs
095      */
096     public void doFilter(ServletRequest request, ServletResponse response,
097                          FilterChain chain)
098         throws IOException, ServletException {
099         try {
100         // Conditionally select and set the character encoding to be used
101         if (ignore || (request.getCharacterEncoding() == null)) {
102             String encoding = selectEncoding(request);
103             if (encoding != null)
104                 request.setCharacterEncoding(encoding);
105         }
106 
107         // Pass control on to the next filter
108         chain.doFilter(request, response);
109         catch (IOException e) {
110             logger.warn(e.getMessage(), e);
111             throw e;
112         catch (ServletException e) {
113             logger.warn(e.getMessage(), e);
114             throw e;
115         }
116     }
117 
118 
119     /**
120      * Place this filter into service.
121      *
122      @param filterConfig The filter configuration object
123      */
124     public void init(FilterConfig filterConfigthrows ServletException {
125         this.filterConfig = filterConfig;
126         this.encoding = filterConfig.getInitParameter("encoding");
127         String value = filterConfig.getInitParameter("ignore");
128         if (value == null)
129             this.ignore = true;
130         else if (value.equalsIgnoreCase("true"))
131             this.ignore = true;
132         else if (value.equalsIgnoreCase("yes"))
133             this.ignore = true;
134         else
135             this.ignore = false;
136     }
137 
138 
139     // ------------------------------------------------------ Protected Methods
140 
141 
142     /**
143      * Select an appropriate character encoding to be used, based on the
144      * characteristics of the current request and/or filter initialization
145      * parameters.  If no character encoding should be set, return
146      <code>null</code>.
147      <p/>
148      * The default implementation unconditionally returns the value configured
149      * by the <strong>encoding</strong> initialization parameter for this
150      * filter.
151      *
152      @param request The servlet request we are processing
153      */
154     protected String selectEncoding(ServletRequest request) {
155         return (this.encoding);
156     }
157 
158 }
Java2html
配置web.xml
<filter>
    <filter-name>Set Character Encoding</filter-name>
    <filter-class>
      com.ipedo.utils.SetCharacterEncodingFilter
    </filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>gb2312</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>Set Character Encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

如果你的还是出现这种情况的话你就往下看看是不是你出现了第四中情况,你的Form提交的数据是不是用get提交的,一般来说用post提交的话是没有问题的,如果是的话,你就看看第四中解决的办法。
还有就是对含有汉字字符的信息进行处理,处理的代码是:

01 package dbJavaBean;
02 
03 public class CodingConvert
04 {
05 public CodingConvert()
06 {
07 //
08 }
09 public String toGb(String uniStr){
10 String gbStr = "";
11 if(uniStr == null){
12 uniStr = "";
13 }
14 try{
15 byte[] tempByte = uniStr.getBytes("ISO8859_1");
16 gbStr = new String(tempByte,"GB2312");
17 }
18 catch(Exception ex){
19 }
20 return gbStr;
21 }
22 
23 public String toUni(String gbStr){
24 String uniStr = "";
25 if(gbStr == null){
26 gbStr = "";
27 }
28 try{
29 byte[] tempByte = gbStr.getBytes("GB2312");
30 uniStr = new String(tempByte,"ISO8859_1");
31 }catch(Exception ex){
32 }
33 return uniStr;
34 }
35 }
Java2html
你也可以在直接的转换,首先你将获取的字符串用ISO-8859-1进行编码,然后将这个编码存放到一个字节数组中,然后将这个数组转化成字符串对象就可以了,例如:
String str=request.getParameter(“girl”);
Byte B[]=str.getBytes(“ISO-8859-1”);
Str=new String(B);
通过上述转换的话,提交的任何信息都能正确的显示。
(三) 在Formget请求在服务端用request. getParameter(“name”)时返回的是乱码;按tomcat的做法设置Filter也没有用或者用 request.setCharacterEncoding("GBK");也不管用问题是出在处理参数传递的方法上:如果在servlet 中用doGet(HttpServletRequest request, HttpServletResponse response)方法进行处理的话前面即使是写了:
request.setCharacterEncoding("GBK");
response.setContentType("text/html;charset=GBK");
也是不起作用的,返回的中文还是乱码!!!如果把这个函数改成doPost(HttpServletRequest request, HttpServletResponse response)一切就OK了。
同样,在用两个JSP页面处理表单输入之所以能显示中文是因为用的是post方法传递的,改成get方法依旧不行。
由此可见在servlet中用doGet()方法或是在JSP中用get方法进行处理要注意。这毕竟涉及到要通过浏览器传递参数信息,很有可能引起常用字符集的冲突或是不匹配。
解决的办法是:
1) 打开tomcat的server.xml文件,找到区块,加入如下一行:
URIEncoding=”GBK”
完整的应如下:
<Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="GBK"/>

2)重启tomcat,一切OK。
需要加入的原因大家可以去研究 $TOMCAT_HOME/webapps/tomcat-docs/config/http.html下的这个文件就可以知道原因了。需要注意的是:这 个地方如果你要是用UTF-8的时候在传递的过程中在Tomcat中也是要出现乱码的情况,如果不行的话就换别的字符集。

(四) JSP页面上有中文,按钮上面也有中文,但是通过服务器查看页面的时候出现乱码:
解 决的办法是:首先在JSP文件中不应该直接包含本地化的消息文本,而是应该通过<bean:message>标签从 Resource Bundle中获得文本。应该把你的中文文本放到Application.properties文件中,这个文件放在WEB- INF/classes/*下,例如我在页面里有姓名,年龄两个label,我首先就是要建一个Application.properties,里面的内 容应该是name=”姓名” age=”年龄”,然后我把这个文件放到WEB-INF/classes/properties/下,接下来根据 Application.properties文件,对他进行编码转化,创建一个中文资源文件,假定名字是 Application_cn.properties。在JDK中提供了native2ascii命令,他能够实现字符编码的转换。在DOS环境中找到你 放置Application.properties的这个文件的目录,在DOS环境中执行一下命令,将生成按GBK编码的中文资源文件 Application_cn.properties: native2ascii –encoding gbk Application.properties Application_cn.properties 执行以上命令以后将生成如下内容的Application_cn.properties文件:name=/u59d3/u540d age=/u5e74 /u9f84,在Struts-config.xml中配置:<message-resources parameter= "properties.Application_cn"/>。到这一步,基本上完成了一大半,接着你就要在JSP页面上写<% @ page language="java" contentType="text/html;charset=GBK" %>,到名字的那个 label是要写<bean:message key=”name”>,这样的化在页面上出现的时候就会出现中文的姓名,年龄这个也是一样,按钮上汉字的处理也是同样的。
(五) 写入到数据库是乱码:
解决的方法:要配置一个filter,也就是一个Servelet的过滤器,代码如同第二种时候一样。
如果你是通过JDBC直接链接数据库的时候,配置的代码如下:jdbc:mysql://localhost:3306/workshopdb?useUnicode=true&characterEncoding=GBK,这样保证到数据库中的代码是不是乱码。
如 果你是通过数据源链接的化你不能按照这样的写法了,首先你就要写在配置文件中,在tomcat 5.0.19中配置数据源的地方是在C:/ Tomcat 5.0/conf/Catalina/localhost这个下面,我建立的工程是workshop,放置的目录是webapp下面, workshop.xml的配置文件如下:
<!-- insert this Context element into server.xml -->

<Context path="/workshop" docBase="workshop" debug="0"
reloadable="true" >

<Resource name="jdbc/WorkshopDB"
auth="Container"
type="javax.sql.DataSource" />

<ResourceParams name="jdbc/WorkshopDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>


<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>

<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value></value>
</parameter>

<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>url</name>
<value><![CDATA[jdbc:mysql://localhost:3306/workshopdb?useUnicode=true&characterEncoding=GBK]]></value>
</parameter>
</ResourceParams>

</Context>
粗 体的地方要特别的注意,和JDBC直接链接的时候是有区别的,如果你是配置正确的化,当你输入中文的时候到数据库中就是中文了,有一点要注意的是你在显示 数据的页面也是要用<%@ page language="java" contentType="text/html;charset= GBK" %>这行代码的。需要注意的是有的前台的人员在写代码的是后用Dreamver写的,写了一个Form的时候把他改成了一个jsp,这样有一个地方 要注意了,那就是在Dreamver中Action的提交方式是request的,你需要把他该过来,因为在jsp的提交的过程中紧紧就是 POST和GET两种方式,但是这两种方式提交的代码在编码方面还是有很大不同的。

发布了63 篇原创文章 · 获赞 24 · 访问量 23万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章