JavaWeb study notes 9: Listener & Filter

1-Listener introduces the principle and interface calls

Listener- listener: use of interface calls, listen for the occurrence of a certain event, it changes the state of the
listener a total of 8, into three types ↓
一类:监听作用域的创建和销毁
二类:监听作用域中属性的创建销毁和替换
三类:Session值的钝化和活化(Activation)
interface call: assuming class A process parameters for an interface, you Test class a method to be called, then a can only be invoked by writing interfaces and examples of methods
Call principle Interface

2-Listener listens created and destroyed three scopes

To create a new listener in web.xml configure the
first recall what the object which several scopes and scopes are:
1、pageContext - PageContext
2、request - HttpServletRequest
3、session - HttpSession
4、application - ServletContext
We are mainly for the following three scopes 2,3,4 listening, for each scope the listener object is in fact the scope object name + listener

  • ServletContextListener
    the ServletContext created:
    启动服务器的时候
    servletContext destroyed:
    关闭服务器、从服务器移除项目

  • ServletRequestListener (rarely used)
    Request creation:
    访问服务器上的任意资源都会有请求出现。 访问 html、访问 jsp、访问 servlet
    Request destroyed:
    服务器已经对这次请求作出了响应之后

    public class MyRequestListener implements ServletRequestListener {
    	@Override
    	public void requestDestroyed(ServletRequestEvent sre) {
    		System.out.println("servletrequest 销毁了");
    	}
    	@Override
    	public void requestInitialized(ServletRequestEvent sre) {
    		System.out.println("servletrequest 初始化了");
    	}
    }
    
  • HttpSessionListener
    create session of the
    只要有调用getSession就创建。 html:(没有Session的调用) jsp:(默认调用getSession) servlet:(默认调用getSession)
    session Destruction
    1、超时,30分钟 2、非正常关闭,销毁 3、正常关闭服务器(序列化)

    public class MySessionListener implements HttpSessionListener {
    	@Override
    	public void sessionCreated(HttpSessionEvent se) {
    		System.out.println("创建session了");
    	}
    	@Override
    	public void sessionDestroyed(HttpSessionEvent se) {
    		System.out.println("销毁session了");
    	}
    }
    

    Listener role:
    use it to, when the scope of objects created
    1. want to complete their initialization
    2. Perform a custom task scheduler to perform a certain task Timer (timer)

3-Listener Listener three scopes property status changes

Use AttributeListener rewrite and view the status change
which attributes: Add (set), replace (set: key Like), removal (remove) three states

  • servletContext — ServletContextAttributeListene
    servletContext
  • request — ServletRequestAttributeListener
    request
  • session — HttpSessionAttributeListener
    session

The HttpSessionBindingListener (less used, a similar effect is to see whether the addition or removal of property)
> 监听对象与session绑定和解除绑定的动作

@Override
public void valueBound(HttpSessionBindingEvent event) {
	System.out.println("对象被绑定进来了");
}

@Override
public void valueUnbound(HttpSessionBindingEvent event) {
	System.out.println("对象被解除绑定");
}

Here it is necessary to explain the difference between the HttpSessionBindingListener and HttpSessionAttributeListener.
First, similar to the role of the two, are intercepted object is added to the lift, the biggest difference is, BindingListener to be a listener objects to implement this interface, and then add the object in the Session of the time will trigger the listener, but if you add another object, the listener will not be triggered.
Instead, AttributeListener also to a class to implement, configure Session object to listen in web.xml, note the Session object, that is, as long as the Session no matter what the object is added, this will trigger the listener, this can be understood as It is a security gate.

4-Listener listens HttpSession passivation activation

Said the above two listeners must be registered in the xml file, and the last listener does not need to register, you only need to implement the interface

HttpSessionActivationListener
用于监听现在session的值是钝化(序列化)还是活化(反序列化)的动作
. 1, a passivation (serialization)
把内存中的数据 存储到硬盘上
2, activated (deserialization)
一定要实现Serializable接口 若已经钝化,则重启服务器就自动活化了 即把硬盘中的数据读取到内存中

Why should there be passive activation?
Session stored in memory will increase the value too much burden, so we can temporarily do something before passive, use the time to activation
events automatically performs the passivation of default is 30 minutes, we can manually configure events and paths

How to configure Session automatic passivation?
 1, in tomcat / conf / context.xml configuration inside
对所有的运行在这个服务器的项目生效
 2 in conf / Catalina / localhost / context.xml configuration
对 localhost生效 localhost:8080
 3, META-INF in web engineering projects / context.xml configuration
只对当前的工程生效

	#maxIdleSwap : 1分钟不用就钝化
	#directory :  钝化后的那个文件存放的目录位置。
	#D:\tomcat\apache-tomcat-7.0.52\work\Catalina\localhost\ListenerDemo\helloworld
<Context>
	<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
		<Store className="org.apache.catalina.session.FileStore" directory="helloworld"/>
	</Manager>
</Context>
5-Filter Introduction and simple to use

Filter filter is actually sent to the client's request, the browser issue, and the server to send servlet to handle, you can filter in the middle, in fact, play a filter role is to intercept
such as what it can do?
  1. For some sensitive words filtered
  2. unified set coding
  3. Automatic login
  ...

Filter life cycle: the server is created when the project is loaded, shut down or destroyed when the item is removed from servers in the
order of execution of Filter:
 1, the client makes a request, first through the filter If the filter is released, then get to the servlet
 2, if there are a plurality of filters, will be registered according to the mapping order of the queue, if only a filter is not released, then the back of the queue, and the filter will not be requested servlet


Filter the simple use of:
filter1, the definition of a class that implements Filter

public class FilterDemo implements Filter {
	public void destroy() {}
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		System.out.println("doFilter……");
		chain.doFilter(request, response);
	}
	public void init(FilterConfig fConfig) throws ServletException {}
}

2, the filter register

#在web.xml里面注册 注册的手法与servlet基本一样
<filter>
	<display-name>FilterDemo</display-name>
	<filter-name>FilterDemo</filter-name>
	<filter-class>com.itheima.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
	<filter-name>FilterDemo</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

Filter the details:
1, if you want to release, which then doFilter operation method, the parameters of the chain
chain.doFilter (request, response); released, so that the next request arrives at a target
2, <url-pattern>/*</url-pattern>written format servlet as
  1. 全路径匹配 以 / 开始
  2. 以目录匹配 以 / 开始 以 * 结束
  3. 以后缀名匹配 以 * 开始 以后缀名结束
3, for the dispatcher set up
  REQUEST : 只要是请求过来,都拦截,默认就是REQUEST
  FORWARD : 只要是转发都拦截
  ERROR : 页面出错发生跳转
  INCLUDE : 包含页面的时候就拦截

6-Filter automatically log

1, Case Study
case study
2, build a good database (user information), Page (JSP)
3, AutoLoginFilter (major code):

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	try {
		//1.首先,无论用户进入什么页面,先判断用户是否登陆并且没关闭浏览器
		HttpServletRequest req = (HttpServletRequest) request;
		//如果已登录且没关闭浏览器,则自动放行
		if(req.getSession().getAttribute("user")!=null){
			chain.doFilter(request, response);
		}else{//session值不存在
			Cookie[] cookies = req.getCookies();
			Cookie cookie = CookieUtil.findCookie(cookies, "autologin");
			if(cookie!=null){//如果cookie存在,则说明用户已经登录过
				String value = cookie.getValue();
				String username = value.split("#")[0];
				String password = value.split("#")[1];
				UserDao dao = new UserDaoImpl();
				UserBean user = dao.login(username, password);
				req.getSession().setAttribute("user", user);
				chain.doFilter(request, response);
			}else{
				//cookie和session都不存在,直接放行要求登录
				chain.doFilter(request, response);
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
		chain.doFilter(request, response);
	}
}

4, LoginServlet (major code):

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	try {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String auto_login = "";
		auto_login+=request.getParameter("autologin");
		System.out.println(auto_login);
//			System.out.println(username+"=="+password+"=="+aotologin);
		UserDao dao = new UserDaoImpl();
		UserBean user = dao.login(username,password);
		if(user != null){
			//将user存储到session中
			request.getSession().setAttribute("user", user);
			if(auto_login.equals("on")){
				//设置autologin的Cookie,包含账号密码,准备自动登录
				Cookie autologin = new Cookie("autologin", (username+"#"+password));
				//设置最长存活时间
				autologin.setMaxAge(60*2);
				//设置保存路径
				autologin.setPath(request.getContextPath());
				response.addCookie(autologin);
			}
			response.sendRedirect("index.jsp");
		}else{
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write("账号或密码错误!请重新登录!");
			response.setHeader("refresh", "3;login.jsp");
		}
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
HPF- self-summary

  When first contact with listeners, especially filters, automatic login for this particular case is not in place to understand, but to write this blog, I made changes to the code that case, and for the modified code with the original code were compared, and finally found the problem. All in all, I hope these two components of a deep understanding can write down!
  --- short step, a thousand miles; not small streams into a mighty torrent.

Published 15 original articles · won praise 18 · views 4568

Guess you like

Origin blog.csdn.net/oZuoShen123/article/details/105338631