论坛首页 Java企业应用论坛

struts 的中文乱码问题解决方案(3个)

浏览 2767 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-01-31  

解决: 推荐使用 Filter.
  ①. 使用 Filter.

public class EncodeFilter implements Filter {

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

 }
 @Override
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
  // TODO Auto-generated method stub
  //从浏览器中的到的二进制数据用utf-8编码
  request.setCharacterEncoding("UTF-8");
  chain.doFilter(request, response); 
 }

 @Override
 public void init(FilterConfig arg0) throws ServletException {
  // TODO Auto-generated method stub

 }

}

 在web.xml文件中配置filter:

<filter>
   <filter-name>encoding</filter-name>
   <filter-class>cn.itcase.strutsdemo.user.domain.EncodeFilter</filter-class>
  </filter>
  <filter-mapping>
   <filter-name>encoding</filter-name>
   <servlet-name>action</servlet-name>
  </filter-mapping>

 

②. 提供自定义的 ActionServlet

public class MyActionServlet extends ActionServlet {

    private static final long serialVersionUID = 5165092497954010055L;
   
    @Override
    protected void process(HttpServletRequest request,
      HttpServletResponse response) throws IOException, ServletException {
     request.setCharacterEncoding("UTF-8");
     super.process(request, response);
    }
    
   }
   
   web.xml 文件中
   <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
   改为
         <servlet-class>cn.itcast.struts.servlet.MyActionServlet</servlet-class>
   
  ③. 提供自定义的 RequestProcessor             
  
  public class MyRequestProcessor extends RequestProcessor {

   @Override
   public void process(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
    request.setCharacterEncoding("UTF-8");
    super.process(request, response);
   }
   
  }       
  
  在 struts-config.xml 文件中加入如下内容:
  <controller processorClass="cn.itcast.struts.servlet.MyRequestProcessor"/>    
   发表时间:2010-05-07  
个人觉得还是用Filter比较方便
0 请登录后投票
   发表时间:2010-05-07  
过滤器还好吧。
在Struts中是使用拦截器。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics