用filter来解决Struts中文乱码的问题

关键词filter 中文乱码

Roy 网友指出,用Filter处理Struts中文乱码才是王道,原文请参考这里:

Struts Hack!解决中文参数在Form Bean中的乱码问题!

filter的用法,的确是比较有扩展性的一种方法...可以通过filter结合读取web.xml中的filter参数来完成一系列的动作,做法如下:

首先,实现javax.servlet.Filter接口,编写一个处理request编码的过滤器类...

     

  1. packagecom.thy.struts.filter;
  2. importjavax.servlet.Filter;
  3. importjavax.servlet.FilterConfig;
  4. importjavax.servlet.ServletException;
  5. importjavax.servlet.ServletRequest;
  6. importjavax.servlet.ServletResponse;
  7. importjavax.servlet.FilterChain;
  8. importjava.io.IOException;
  9. publicclassSetCharacterEncodingFilterimplementsFilter{
  10. protectedFilterConfigfilterConfig;
  11. protectedStringencodingName;
  12. protectedbooleanenable;
  13. publicSetCharacterEncodingFilter(){
  14. this.encodingName="UTF-8";
  15. this.enable=false;
  16. }
  17. publicvoidinit(FilterConfigfilterConfig)throwsServletException{
  18. this.filterConfig=filterConfig;
  19. loadConfigParams();
  20. }
  21. privatevoidloadConfigParams(){
  22. //encoding
  23. this.encodingName=this.filterConfig.getInitParameter("encoding");
  24. //filterenableflag
  25. StringstrIgnoreFlag=this.filterConfig.getInitParameter("enable");
  26. System.out.println("Filter");
  27. if(strIgnoreFlag.equalsIgnoreCase("true")){
  28. this.enable=true;
  29. }else{
  30. this.enable=false;
  31. }
  32. }
  33. publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,
  34. FilterChainchain)throwsIOException,
  35. ServletException{
  36. if(this.enable){
  37. request.setCharacterEncoding(this.encodingName);
  38. }
  39. chain.doFilter(request,response);
  40. }
  41. publicvoiddestroy(){
  42. }
  43. }

然后,需要在web.xml中注册我们的过滤器类:

     


  1. <filter>
  2. <filter-name>SetCharacterEncoding</filter-name>
  3. <filter-class>
  4. com.thy.struts.filter.SetCharacterEncodingFilter
  5. </filter-class>
  6. <init-param>
  7. <param-name>encoding</param-name>
  8. <param-value>UTF-8</param-value>
  9. </init-param>
  10. <init-param>
  11. <param-name>enable</param-name>
  12. <param-value>true</param-value>
  13. </init-param>
  14. </filter>
  15. <filter-mapping>
  16. <filter-name>SetCharacterEncoding</filter-name>
  17. <url-pattern>*.do</url-pattern>
  18. </filter-mapping>

这样,任何通过Struts,或是JSF的Controller Servlet处理的request,都会在过滤器中先行处理,才把控制权交还给Struts或是JSF,而且Filter中有一个Process Chain的概念,是一个很吸引人的东东~~!

你可能感兴趣的:(bean,Web,struts,servlet,JSF)