Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29948309
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2008-04-17 12:53:36

由于Struts框架直接把表单数据发送给了ActionForm,所以这里面没有对HttpRequestServlet进行SetCharacterEncoding,所以默认是按照ISO-8859-1(参见Tomcat 源代码中的org.apache.catalina.connector.HttpRequestBase中的protected void parseParameters()方法),

解决的方法,就是在表单提交到ActionForm之前对request进行编码。
第一种方法,就是写一个过滤器,对所有请求进行过滤


过滤器代码:
package jp.co.ricoh.gtis.others.profile.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;

public class SetCharacterEncodingFilter implements Filter {
 private String encoding;
 public void init(FilterConfig filterConfig) throws ServletException {
  // TODO Auto-generated method stub
  this.encoding=filterConfig.getInitParameter("encoding");
 }

 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  request.setCharacterEncoding(this.encoding);
  chain.doFilter(request,response);
 }

 public void destroy() {
  // TODO Auto-generated method stub

 }

}


 

配置文件web.xml
 
   SetCharacterEncodingFilter
   jp.co.ricoh.gtis.others.profile.filters.SetCharacterEncodingFilter
  
    encoding
    utf-8
  

 


  
   SetCharacterEncodingFilter
   /* 
 


 

第二种方法是替换默认的控制器org.apache.struts.action.ActionServlet

 


子类代码:
package jp.co.ricoh.gtis.others.profile.controllers;

 

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionServlet;

public class SetEncodingActionServlet extends ActionServlet {

 protected void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
  // TODO Auto-generated method stub
  String encoding = getInitParameter("encoding");
  request.setCharacterEncoding(encoding);
  super.process(request, response);
 }

}


 

配置文件web.xml
 
    testAction
    jp.co.ricoh.gtis.others.profile.controllers.SetEncodingActionServlet
   
      config
      /WEB-INF/struts-config.xml
   

   
      encoding
      utf-8
   

    2
 


 
    testAction
    *.testdo
 


此例,凡是通过*.testdo来请求的数据,都会经过参数encoding设定的值来编码。

阅读(1778) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~