Struts2的中文乱码的解决方案

原因:

1.乱码问题是由于不统一的编码而产生的。所以在解决乱码的时候,就是要从页面到数据库都采用统一的编码。

2.tomcat的j2ee实现对表单提交即post方式提示时处理参数采用缺省的iso-8859-1来处理

3.tomcat对get方式提交的请求,对query-string处理时采用了和post方法不一样的处理方式。(与tomcat4不一样,所以设置setCharacterEncoding(“gbk”)不起作用。)

解决办法:

1.MySql数据库

安装MySql时,数据库的编码,要选择gbk。在创建表的时候也要选择用gbk;

2.在所有的JSP文件头部加上如下代码,并保证文件的编码方式与此相同:

<%@ page contentType="text/html;charset=gbk"%>

3.实现一个Filter,设置处理字符集为GBK。(在tomcat的webapps/servlet-examples目录有一个完整的例子,完整代码如下。)

/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
 
package filters;
 
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
 
 
/**
 * <p>Example filter that sets the character encoding to be used in parsing the
 * incoming request, either unconditionally or only if the client did not
 * specify a character encoding.  Configuration of this filter is based on
 * the following initialization parameters:</p>
 * <ul>
 * <li><strong>encoding</strong> - The character encoding to be configured
 *     for this request, either conditionally or unconditionally based on
 *     the <code>ignore</code> initialization parameter.  This parameter
 *     is required, so there is no default.</li>
 * <li><strong>ignore</strong> - If set to "true", any character encoding
 *     specified by the client is ignored, and the value returned by the
 *     <code>selectEncoding()</code> method is set.  If set to "false,
 *     <code>selectEncoding()</code> is called <strong>only</strong> if the
 *     client has not already specified an encoding.  By default, this
 *     parameter is set to "true".</li>
 * </ul>
 *
 * <p>Although this filter can be used unchanged, it is also easy to
 * subclass it and make the <code>selectEncoding()</code> method more
 * intelligent about what encoding to choose, based on characteristics of
 * the incoming request (such as the values of the <code>Accept-Language</code>
 * and <code>User-Agent</code> headers, or a value stashed in the current
 * user's session.</p>
 *
 * @author Craig McClanahan
 * @version $Revision: 267129 $ $Date: 2004-03-18 10:40:35 -0600 (Thu, 18 Mar 2004) $
 */
 
public class SetCharacterEncodingFilter implements Filter {
 
 
    // ----------------------------------------------------- Instance Variables
 
 
    /**
     * The default character encoding to set for requests that pass through
     * this filter.
     */
    protected String encoding = null;
 
 
    /**
     * The filter configuration object we are associated with.  If this value
     * is null, this filter instance is not currently configured.
     */
    protected FilterConfig filterConfig = null;
 
 
    /**
     * Should a character encoding specified by the client be ignored?
     */
    protected boolean ignore = true;
 
 
    // --------------------------------------------------------- Public Methods
 
 
    /**
     * Take this filter out of service.
     */
    public void destroy() {
 
        this.encoding = null;
        this.filterConfig = null;
 
    }
 
 
    /**
     * Select and set (if specified) the character encoding to be used to
     * interpret request parameters for this request.
     *
     * @param request The servlet request we are processing
     * @param result The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException {
 
        // Conditionally select and set the character encoding to be used
        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null)
                request.setCharacterEncoding(encoding);
        }
 
        // Pass control on to the next filter
        chain.doFilter(request, response);
 
    }
 
 
    /**
     * Place this filter into service.
     *
     * @param filterConfig The filter configuration object
     */
    public void init(FilterConfig filterConfig) throws ServletException {
 
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null)
            this.ignore = true;
        else if (value.equalsIgnoreCase("true"))
            this.ignore = true;
        else if (value.equalsIgnoreCase("yes"))
            this.ignore = true;
        else
            this.ignore = false;
 
    }
 
 
    // ------------------------------------------------------ Protected Methods
 
 
    /**
     * Select an appropriate character encoding to be used, based on the
     * characteristics of the current request and/or filter initialization
     * parameters.  If no character encoding should be set, return
     * <code>null</code>.
     * <p>
     * The default implementation unconditionally returns the value configured
     * by the <strong>encoding</strong> initialization parameter for this
     * filter.
     *
     * @param request The servlet request we are processing
     */
    protected String selectEncoding(ServletRequest request) {
 
        return (this.encoding);
 
    }
 
 
}

4.在你的在web.xml中配置过滤器,使之能起过滤作用。在web.xml里加入以下几行:

    <filter>
        <filter-name>SetCharacterEncoding</filter-name>
        <filter-class>util.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>SetCharacterEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

5.连接数据的属性项修改成如下代码

jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk

以上即为完整解决方案。另外,如果还有问题也可以试试以下方法(在虚拟主机上的server文件一般无法直接进行修改):

打开tomcat的server.xml文件,找到区块,加入如下一行:

URIEncoding=”GBK”

完整代码如下:

<Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true"
           URIEncoding="GBK"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值