web.xm l配置詳解之Filter

1、xml配置

<filter>
<filter-name>encodingfilter</filter-name>
<filter-class>com.my.app.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

2、java 代碼

/**
 * 
 */
package com.myapp;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author louisliao
 *
 */
public class EncodingFilter implements Filter {

	/**
	 * 配置中默認的字符編碼
	 */
	protected String encoding = null;  
	protected FilterConfig filterConfig;
	/**
	 * 當沒有指定默認編碼時是否允許跳過過濾
	 */
	protected boolean ignore = true; 
	/**
	 * 
	 */
	public EncodingFilter() {
		// TODO Auto-generated constructor stub
	}
       
	/**
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		this.encoding=null;
		this.filterConfig=null;
	}
	
	/**
	 *(non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet         *.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest hRequest=(HttpServletRequest)request;
		HttpServletResponse hResponse=(HttpServletResponse)response;
		//Conditionally select and set the character encoding to be used  
		if(ignore || hRequest.getCharacterEncoding()==null){
			String coding=selectEncoding(hRequest);
			if(coding!=null){
				hRequest.setCharacterEncoding(coding);
				hResponse.setCharacterEncoding(coding);
			}
		}
		//將控制器傳向下一個filter
		chain.doFilter(hRequest, hResponse);

	}

	/**
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.filterConfig=filterConfig;
		this.encoding=filterConfig.getInitParameter("encoding");
		System.out.println(this.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;
		}
	}
	protected String selectEncoding(ServletRequest request) {
		return (this.encoding);
	}

}
//init方法是在WEB應用啓動就會調用,doFilter則是在訪問filter-mapping映射到的url時會調用。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章