目录​​​​​​​

1.Servlet过滤器

2.Servlet监听器


1.Servlet过滤器

主要是过滤用户请求;

在前面的Login.jsp访问页面时,会出现登陆界面;

那么我们直接访问main.jsp主页面时,就直接出现了主页面的内容,这样Logi.jsp就没起到作用了;

为了防止这种情况,Servlet里面有一个过滤器Filter,可以过滤掉直接访问main.jsp就出现主页面的情况; 

package com.java.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{

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

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		//将ServletRequest强转成HttpServletRequest
		HttpServletRequest request=(HttpServletRequest)servletRequest;
		//获取session
		HttpSession session=request.getSession();
		//获取当前用户登录信息
		Object o=session.getAttribute("currentUser");
		//将正确用户登录去除掉
		String path=request.getServletPath();
		if(o==null&&path.indexOf("login")<0){
			//重定向返回到登录界面
			request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
		}else{
			//递归,重新返回到判断过程
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

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

}

web.xml配置信息:

 Servlet(四)——Servlet过滤器和监听器_JavaScript

这里是过滤掉了所有非访问请求!

这时我们直接访问mian.jsp时:

Servlet(四)——Servlet过滤器和监听器_servlet_02

直接返回到了登录界面!

 

2.Servlet监听器

监听 web 事件;如 application,session,request 

package com.java.listener;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class SessionAttributeListener implements HttpSessionAttributeListener{

	public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
		// TODO Auto-generated method stub
		System.out.println("添加的属性名:"+httpSessionBindingEvent.getName()+", 属性值:"+httpSessionBindingEvent.getValue());
	}

	public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
		// TODO Auto-generated method stub
		System.out.println("删除的属性名:"+httpSessionBindingEvent.getName()+", 属性值:"+httpSessionBindingEvent.getValue());
	}

	public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
		// TODO Auto-generated method stub
		
	}

	
}

web.xml配置信息:

Servlet(四)——Servlet过滤器和监听器_●  Jsp和Servlet动态网页_03 

我们重回浏览器进行登录,登录成功之后会发现已经监听到了登录信息:

Servlet(四)——Servlet过滤器和监听器_JavaScript_04