---
title: "struts中文过滤器"
author: "cui09"
date: "2007-08-04T17:28:05Z"
tags: []
slug: "struts"
draft: false
lastmod: "2007-08-04T17:28:05Z"
id: 108934
url: "https://cui.iteye.com/blog/108934"
---

//生成自己的过滤器

package org.perfect.struts.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;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;

public class ChineseFilter extends HttpServlet implements Filter {  
     
      private FilterConfig filterConfig;

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

      public void doFilter(ServletRequest request, ServletResponse response,  
              FilterChain filterChain) {  
          try {  
             
              String encoding=filterConfig.getInitParameter("encoding");//从WEB.xml配置文件中取出参数，这样我们可以通过配置修改编码格式．  
              request.setCharacterEncoding(encoding);//设置请求的编码格式  
              System.out.println(encoding);  
              filterChain.doFilter(request, response);  
          } catch (ServletException sx) {  
              filterConfig.getServletContext().log(sx.getMessage());  
          } catch (IOException iox) {  
              filterConfig.getServletContext().log(iox.getMessage());  
          }  
      }  
   

      public void destroy() {  
      }  
     
      protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {  
          super.doGet(arg0, arg1);  
      }  
     
      protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {  
          super.doPost(arg0, arg1);  
      }  
}

 

 ===============================

在web.xml中做结扎.

        &lt;filter&gt;  
          &lt;filter-name&gt;ChineseFilter&lt;/filter-name&gt;  
          &lt;filter-class&gt;org.perfect.struts.filters.ChineseFilter&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;ChineseFilter&lt;/filter-name&gt;  
          &lt;url-pattern&gt;/\*&lt;/url-pattern&gt;  
      &lt;/filter-mapping&gt;

 

=================================

jsp中

&lt;%@ page  contentType="text/html; charset=GBK" language="java" %&gt;