【学习笔记】--Struts字符编码过滤器

来源:互联网 发布:qq三国50js装备满属性 编辑:程序博客网 时间:2024/04/30 09:19

 package com.yangtianb.web.action;


import java.io.BufferedWriter;
import java.io.FileWriter;
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;

public class SetCharacterEncodingFilter implements Filter{
 protected String encoding = null;
 protected FilterConfig filterConfig = null;

 protected boolean ignore = true;

 
 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  // Just puts "destroy" string in log
  // Put your code here
  this.encoding = null;
        this.filterConfig = null;

 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occure
  */
 public void init() throws ServletException {
  // Put your code here
 }

 public void doFilter(ServletRequest request,
         ServletResponse response,
         FilterChain chain)
         throws IOException, ServletException {

         //     Conditionally select and set the character encoding to be used
         if (ignore || (request.getCharacterEncoding() == null)) {
             String encoding = selectEncoding(request);
             if (encoding != null) {
                 request.setCharacterEncoding(encoding);
             }
         }
         chain.doFilter(request, response);
         BufferedWriter  bw = new BufferedWriter(new FileWriter("/LoginAction.java"));;

 

 }

 protected String selectEncoding(ServletRequest request) {

        return (this.encoding);

    }

 

 public void init(FilterConfig filterConfig) throws ServletException {

        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null) {
            this.ignore = true;
        } else if (value.equalsIgnoreCase("true")) {
            this.ignore = true;
        } else if (value.equalsIgnoreCase("yes")) {
            this.ignore = true;
        } else {
            this.ignore = false;
        }

    }

 

}

 

 

web.xml

 


   <filter>
    <filter-name>SetCharacterEncoding</filter-name>
   <filter-class>
    com.yangtianb.web.action.SetCharacterEncodingFilter
   </filter-class>
   <init-param>
    <param-name>encoding</param-name>
    <param-value>utf-8</param-value>
   </init-param>
  </filter>
  <filter-mapping>
   <filter-name>SetCharacterEncoding</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>

 

 

原创粉丝点击