---
title: "struts中文问题"
author: "misswolf"
date: "2005-10-29T15:32:00Z"
tags: []
slug: "struts"
draft: false
lastmod: "2005-10-29T15:32:00Z"
id: 270450
url: "https://misswolf.iteye.com/blog/270450"
---

最近在学习struts时碰到了struts问题，在网上找了很多资料 我在此记下来吧！(Eclipse3.1+tomcat5.59  
首先是：资源文件的中文乱码问题  
第二是:从Mysql数据库中读取出来的数据是乱码  
第三是:从Form里get的数据是乱码

第一个问题的解决方案，下载一个属性编辑文件的插件在哪儿下载的我不记得了反正下载有很久了！各位就search一下吧！

第二问题的解决方案，MySql数据库中文问题:最简单的方法使用以下命令登陆到数据库

mysql --default-character-set=gbk -u root -p

输入密码后就进入了数据库然后再创建数据库和表插入中文数据吧！

在连接数据库时使用jdbc:mysql://localhost:3306/admin?useunicode=true&amp;characterEncoding=GBK

第三个是从form获取的是乱码解决方案从网找来的治标的方法！一劳永逸！用Filter

package edu.jsu.firewolf.filter;  
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;

public class SetCharacterEncodingFilter implements Filter {  
  protected String encoding = null;  
  protected FilterConfig filterConfig = null;  
  protected boolean ignore = true;

  public void destroy() {  
    this.encoding = null;  
    this.filterConfig = null;  
  }

  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);

  }

  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 String selectEncoding(ServletRequest request) {  
   return (this.encoding);  
  }  
}

以上是Fiter的代码然而修改web.xml增加如下代码

&lt;filter&gt;  
  &lt;filter-name&gt;SetCharacterEncoding&lt;/filter-name&gt;  
  &lt;filter-class&gt;edu.jsu.firewolf.filter.SetCharacterEncodingFilter&lt;/filter-class&gt;  
  &lt;init-param&gt;  
   &lt;param-name&gt;encoding&lt;/param-name&gt;  
   &lt;param-value&gt;GBK&lt;/param-value&gt;  
  &lt;/init-param&gt;  
 &lt;/filter&gt;  
 &lt;filter-mapping&gt;  
  &lt;filter-name&gt;SetCharacterEncoding&lt;/filter-name&gt;  
  &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;  
 &lt;/filter-mapping&gt;