日期:2014-05-16  浏览次数:20356 次

(四)Jsp filter的简单使用

filter是Servlet的一种变种,主要用于对用户请求进行预处理,也可以对HttpServletResponse进行后处理:filter的执行时机:http://yxwang0615.iteye.com/blog/1003880

?

下面是使用filer过滤用户请求的一个实例:

?

【验证用户是否登录,如果未登录跳转到登录页面】

LoginFilter.java:创建Filter类必须实现Filter接口

package com.wyx.filter;

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.HttpSession;

public class LoginFilter implements Filter{
	private FilterConfig config;
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		 String encoding = config.getInitParameter("encoding");
		 String loginPage = config.getInitParameter("loginPage");
		 
		request.setCharacterEncoding(encoding);
		//将请求转换成HttpServletRequest请求
		HttpServletRequest hrequest = (HttpServletRequest)request;
		HttpSession session = hrequest.getSession(true);//获取session,参数为true表示没有的时候创建一个,false返回null。
		if( !hrequest.getServletPath().endsWith(loginPage) && session.getAttribute("user")== null){
			request.setAttribute("tip", "您还没有登录!");
			request.getRequestDispatcher(loginPage).forward(request, response);
			
		}else{
			//放行请求
			chain.doFilter(request, response);
			
		}
	}
	public void init(FilterConfig filterConfig) throws ServletException {
		this.config = filterConfig;
	}
	public void destroy() {
		this.config = null;
	}
}

?

?

web.xml,在跟节点下加入:

<!-- 定义Filter -->
 <filter>
 	<filter-name>checkIsLogin</filter-name>
 	<filter-class>com.wyx.filter.LoginFilter</filter-class>
 	<!-- 为filter配置参数 -->
 	<init-param>
 		<param-name>encoding</param-name>
 		<param-value>GBK</param-value>
 	</init-param>
 	<init-param>
 		<param-name>loginPage</param-name>
 		<param-value>/login.jsp</param-value>
 	</init-param>
 </filter>
 <!-- 定义Filter拦截的URL地址 -->
 <filter-mapping>
 	<filter-name>checkIsLogin</filter-name>
 	<!-- 要拦截的URL -->
 	<url-pattern>/*</url-pattern>
 </filter-mapping>

?