Java Web Learning - filters and listeners

Keywords: Session Java xml JSP

Filter

The basic knowledge is introduced in detail in the rookie course

Rookie tutorial filter

 

  <!--Prepare the first filter-->
  <filter>
		<filter-name>Filter1</filter-name>
		<filter-class>com.servlet.filter.Filter1</filter-class>
  </filter>
  <filter-mapping>
		<filter-name>Filter1</filter-name>
		<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!--Prepare the first filter-->
  <filter>
		<filter-name>Filter2</filter-name>
		<filter-class>com.servlet.filter.Filter2</filter-class>
  </filter>
  <filter-mapping>
		<filter-name>Filter2</filter-name>
		<url-pattern>/*ed</url-pattern>
  </filter-mapping>

  <!--Prepare the first filter-->  
  <filter>
		<filter-name>Filter3</filter-name>
		<filter-class>com.servlet.filter.Filter3</filter-class>
  </filter>
  <filter-mapping>
		<filter-name>Filter3</filter-name>
		<url-pattern>/filtertest</url-pattern>
  </filter-mapping>
  
package com.servlet.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.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Use of filter:
 *  Function: manage the request resources accepted by the server and the resources responded to the browser
 *  	Protecting servlet s	
 *  Use:
 *  	A common java class is created to implement the Filter interface
 *  	Override method in interface: init dofilter destory
 *  	Configuring filter filters in web.xml
 *  	Be careful:
 *  		url-pattern: /* 
 *  				To block all requests
 *   		url-pattern: /*.ed 
 *  				Indicates blocking requests ending in ed
 *   		url-pattern: /filtertest 
 *  				Indicates blocking requests for specific servlet s‘
 *  	Filter life cycle:
 *  		Browser on - browser off
 *  	Conclusion:
 *  		The filter programmer declares and configures that the server calls based on the uri in the request
 *  	Implementation:
 *  	      The browser initiates the request to the server. After the server receives the request, it is on the web according to the URI information. Find the corresponding filter in xml and execute the doFilter method
 *  	After the request is processed, it will be released if it meets the requirements. After the release, how can the filter continue to filter? Find the servlet to process the request. After the servlet completes the request, that is to say
 *  	service Method, you should continue to return the code in the corresponding doFilter method
 *  	
 *  	Case study:
 *  		1.Unified coding format
 *  		2.session Processing
 *  		3.Privilege management
 *  		4.Resource Management (Unified watermark, harmonious vocabulary, etc.)
 *  	
 */
public class Filter1 implements Filter{

    @Override
    public void destroy() {
	System.out.println("The first filter is initialized");
	
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
	    FilterChain chain) throws IOException, ServletException {
	
	//Unified coding format
	req.setCharacterEncoding("utf-8");
	resp.setContentType("text/html;charset=utf-8");
	
	//Session processing; if session data is out of date or does not exist, we will let it save session from New
	HttpSession hs = ((HttpServletRequest)req).getSession();
	if(hs.getAttribute("user")==null){
	    //redirect
	    ((HttpServletResponse)resp).sendRedirect("/Users/login.jsp");
	}else{
	    
		System.out.println("I was the first filter");
		chain.doFilter(req, resp);
	}
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
	
	System.out.println("The first filter is dead");
    }

}
package com.servlet.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;

public class Filter2 implements Filter {

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

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
	    FilterChain arg2) throws IOException, ServletException {
	System.out.println("Perform second filter");
	arg2.doFilter(arg0, arg1);
	
    }

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

}
package com.servlet.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;

public class Filter3 implements Filter {

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

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
	    FilterChain arg2) throws IOException, ServletException {
	System.out.println("Perform the third filter");
	arg2.doFilter(arg0, arg1);
	
    }

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

}

 

 

Monitor

Problem: in Servlet Technology, we learned request, session and application scope objects, whose main function is to realize the flexible flow of data in different scenarios. But we can't see the specific data flow process, such as when the scope object is created and destroyed, when the data is accessed, changed and deleted. Because the specific flow process cannot be seen, it is impossible to operate the data and objects at the specified time, such as when the session is destroyed, the number of online people is - 1.
Solution: use the listener
Concept: Servlet listener is a special class defined in the Servlet specification, which is used to listen to the fields such as ServletContext, HttpSession and ServletRequest
Object creation and destruction events, as well as listening for the event of modifying properties in these domain objects.
Listening objects: Request, Session, Application
Listening content: create, destroy, property change events
Monitoring function: before and after the event, perform some processing, such as counting the number of people online
Use: listen to request listen to session listen to application
Case: count the number of people online.

package com.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Function of the monitor:
 * 	Effect:
 * 	  Listen for the creation, destruction, and content change of the scope objects request, session, and application
 * 	Use:
 * 	web Configure < listener > < listener class >
 * 	Create a java class that implements the specified interface
 * 	Request
 * 		1.Listen to request = = > ServletRequestListener listen to the destruction and initialization of request
 * 		2.Listen for request = = > ServletRequestAttributeListener listens for changes in request scope data
 * 			Formal parameter
 * 			getName()  Key to get listening data
 * 			getValue() Get the value of listening data
 * 
 * 	Session
 * 		1.Listening session = = > HttpSessionListener   
 * 		2.Listening session = = > HttpSessionAttributeListener  
 * 			Formal parameter
 * 			getName()
 * 			getValue()
 * 	Application
 * 		1.Listen to servletcontextlistener = = > HttpSessionListener   
 * 		2.Listen to ServletContextAttributeListener = = > HttpSessionAttributeListener  
 * 			Formal parameter
 * 			getName()
 * 			getValue()
 * 			
 * 	
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * @Desciption :
 * @date :2019-4-3 6:53:09 PM
 * @author :Tian Kun
 */

public class Listener implements ServletRequestListener,ServletRequestAttributeListener,HttpSessionListener,HttpSessionAttributeListener,ServletContextListener,ServletContextAttributeListener{

    
    @Override
    public void requestDestroyed(ServletRequestEvent arg0) {
	System.out.println("reuest Destroyed.");
	
    }

    @Override
    public void requestInitialized(ServletRequestEvent arg0) {
	System.out.println("request Initialization");
	
    }

    @Override
    public void attributeAdded(ServletRequestAttributeEvent arg0) {

	System.out.println("request Attribute added to:"+arg0.getName()+"--"+arg0.getValue());
	
    }
    
    /******************SESSION******************************************/
    
    @Override
    public void sessionCreated(HttpSessionEvent arg0) {
	System.out.println("Session It's initialized");
	
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
	System.out.println("Session Destroyed.");
	
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent arg0) {
	// TODO Auto-generated method stub
	
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent arg0) {
	// TODO Auto-generated method stub
	
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent arg0) {
	System.out.println("Session Added properties:"+arg0.getName()+"---"+arg0.getValue());
	
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent arg0) {
	// TODO Auto-generated method stub
	
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent arg0) {
	// TODO Auto-generated method stub
	
    }
    
    /****************Application*********************/
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
	System.out.println("application Destroyed.");
	
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
	System.out.println("application It's initialized");
	
    }

    @Override
    public void attributeAdded(ServletContextAttributeEvent arg0) {
	System.out.println("Application Added properties:"+arg0.getName()+"---"+arg0.getValue());
	
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent arg0) {
	// TODO Auto-generated method stub
	
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent arg0) {
	// TODO Auto-generated method stub
	
    }

   


   
}

 

 

 

 

 

 

 

 

 

 

 

Posted by snorky on Sat, 07 Dec 2019 13:56:58 -0800