Structs2 2.1.6 action传值中文乱码问题

  今天在做一个小项目时,遇到了Structs2 action传值中文乱码问题,折腾了两个多小时,终于解决了,希望给大家一点借鉴..
 
   首先自己使用的是Structs2 2.1.6版本,通过看其官方文档中介绍,
通过在structs.xml中配置<constant name="struts.i18n.encoding" value="GBK" />属性就可以解决该问题,但是在测试时却死活不成功,通过网上搜索,得知,这是由于其中的bug造成的。
因为没有办法,则只能进行手写一个过滤器,对所有的action操作都进行转码过滤;
具体代码如下:

首先手写一个类实现filter接口;

package com.action.common;

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 FilterConfig filterConfig;

	 public void init(FilterConfig filterConfig) throws ServletException {
         this.filterConfig = filterConfig;
     }

     //Process the request/response pair
     public void doFilter(ServletRequest request, ServletResponse response,
                          FilterChain filterChain) {
         try {
             request.setCharacterEncoding("utf-8");
             response.setCharacterEncoding("utf-8");
             filterChain.doFilter(request, response);
         } catch (ServletException sx) {
             filterConfig.getServletContext().log(sx.getMessage());
         } catch (IOException iox) {
             filterConfig.getServletContext().log(iox.getMessage());
         }
     }

     //Clean up resources
     public void destroy() {
     }

}



然后在web.xml中配置:因为SetCharacterEncodingFilter.java是tomcat自带的
路径:C:\tomcat 6\webapps\examples\WEB-INF\classes\filters下
所以此段代码必须在struts2的dispatcher.FilterDispatcher之前配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
     <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>
              com.action.common.SetCharacterEncodingFilter
        </filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>
  
  
    <filter> 
     <filter-name>struts2</filter-name> 
       <filter-class> 
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
       <!--<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>-->
    </filter>
    
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  
</web-app>




然后重启服务器,重新测试,问题解决;

你可能感兴趣的:(apache,tomcat,xml,Web,servlet)