Filter filtering and Listener listening

Use of Filter

To match the specified resource. For example "/ index.jsp"
Match with directory. For example "/ servlet / *"
Match with suffix, for example "*. jsp"
Wildcard to intercept all web resources. "/*"

1. What is a filter?

Filter is one of the three major components of javalistener and filter application
Filter filter is the specification of Java EE, that is, the interface.
Filter filter is used to intercept requests and filter responses
It is executed in front of a set of resources (jsp, servlet,. css,. html, etc.)
 

2. Usage scenario of filter

a. prevent from entering the login interface
b. control application code
c. filter sensitive words and other scenes

3. How to write a filter?

a. the user-defined class implements the Filter interface and rewrites the abstract methods in the interface (3)
b. on the web XML
    <filter>
    <filter-name>DemoFilter</filter-name>
    <filter-class>com.zking.filter.DemoFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>DemoFilter</filter-name>
    <url-pattern>/as.do</url-pattern>
    </filter-mapping>


< URL pattern > / a.jsp < / url pattern >: what is the content you want to intercept?
<url-pattern>/*.jsp</url-pattern>
<url-pattern>/*.do</url-pattern>
<url-pattern>/*</url-pattern>
 

4. Life cycle of filter interface

  void init(FilterConfig)
* execute immediately after creation: the Filter will be created when the server starts
    void destory()
* before destruction! Destroy on server shutdown
    void doFilter(ServletRequest,ServletResponse,FilterChain)
* performed every time the filter is
 

5. Introduction to related classes in filter interface

Filterconfig ---- similar to ServletConfig
* get initialization parameters: getInitParameter
* get filter name: getFilterName
* get application: getServletContext

    FilterChain
* doFilter(ServletRequest,ServletResponse): release request
 

6. Execution sequence of multiple filters

The execution order of filters has nothing to do with the accuracy of URL pattern tag matching, only with their filter mapping tag on the web The order in the XML file is related, and the upper configuration is executed first.

7. Four interception methods of filter (understand)

 REQUEST,FORWARD,INCLUDE,ERROR.

REQUEST: execute the filter when accessing the target resource directly. Including: direct access, form submission, hyperlink and redirection in the address bar. As long as you can see the path of the target resource in the address bar, it is REQUEST;
    
FORWARD: FORWARD access execution filter. Including RequestDispatcher#forward() method and < jsp: FORWARD > tag, all of which are FORWARD access;

INCLUDE: contains access execution filters. Including RequestDispatcher#include() method and < jsp: INCLUDE > tag, all of which contain access;
    
ERROR: when the target resource is on the web When XML is configured as < ERROR page >, and an exception really occurs, the filter will be executed when forwarding to the target resource.

You can add 0~n < dispatcher > sub elements to < filter mapping > to describe the interception method of current access.

Example:
 

<filter-mapping>
	
			<filter-name>myfilter</filter-name>
	
			<url-pattern>/b.jsp</url-pattern>
	
			<dispatcher>REQUEST</dispatcher>
	
			<dispatcher>FORWARD</dispatcher>
 
		</filter-mapping>
In this configuration, b.jsp Is the target resource.
	When direct request b.jsp When, the filter is executed.
	When forwarded to b.jsp The filter is executed when the page is.

 

Automatic login is not blocked to the login interface

Servlet interface

package com.zking.servlet;
 
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class LoginServlet extends HttpServlet {
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String auto = request.getParameter("auto"); // Auto login
 
		if ("admin".equals(username) && "123".equals(password)) {// If login is successful
			request.getSession().setAttribute("username", username);
			if (auto == null) {// Automatic login is not checked
				Cookie cookie = new Cookie("auto", null);
				cookie.setMaxAge(60 * 60 * 24);// cookie validity time
				response.addCookie(cookie);
			} else {// Check auto login
				Cookie cookie = new Cookie("auto", username + "_" + password);
				cookie.setMaxAge(60 * 60 * 24);// cookie validity time
				response.addCookie(cookie);
			}
			// Login succeeded, jump
			response.sendRedirect("index.jsp");
		} else {
			// Login failed, please login again
			response.sendRedirect("login.jsp");
		}
	}
 
}

Listener Filter

package com.zking.servlet;
 
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 com.zking.utils.CookieUtil;
 
public class LoginFilter implements Filter {
 
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
 
        if(req.getRequestURI().contains("login.jsp")) {//If you access login, release directly
            chain.doFilter(req, resp);
            return;
        }else {
            String username = (String) req.getSession().getAttribute("username");
            if(username==null) {//Not in session. Go to the Cookie
                String val = CookieUtil.getCookieValByKey("auto", req);
                if(val!= null&& !val.equals("")) {
                    String name = val.split("_")[0];
                    String pass = val.split("_")[1];
 
                    if("admin".equals(name) && "123".equals(pass)) {//Revalidate login
                        req.getSession().setAttribute("username", name);//Log in successfully, put it into the Session and release it
                        chain.doFilter(req, resp);
                        return;
                    }else {//Authentication failed, login again
                        resp.sendRedirect("login.jsp");
                    }
                }else {//There is no in the Cookie. For the first visit, jump to the login page
                    resp.sendRedirect("login.jsp");
                }
            }else {//In the session, please release
            	 chain.doFilter(req, resp);
                return;
            }
        }
	}
 
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
 
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}
 
 
}

The configuration file in xml is valid only if it is wrapped in < / web app >

<servlet>
		<servlet-name>LoginServlet</servlet-name>
		<servlet-class>com.zking.servlet.LoginServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>LoginServlet</servlet-name>
		<url-pattern>/login.do</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>LoginFilter</filter-name>
		<filter-class>com.zking.servlet.LoginFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>LoginFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

Note that the xml file will be available only after clicking next twice when creating a web project

 

Functions of three methods in filter

package com.zking.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;
 
//This class is called a Filter class, and implements the Filter interface to inherit HttpFilter
public class FilterDemo implements Filter{
 
	@Override
	public void destroy() {
		System.out.println("The filter was destroyed~~~~~~");
	}
 
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		//  Level set   
		System.out.println("Here we are, brother~~~Let me go!!!!!!!!!!");
		System.out.println("Release  start");
		//There's nothing to ask me to let you go directly
		arg2.doFilter(arg0, arg1);
		System.out.println("Release  end");
	}
 
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("The filter is initialized~~~");
	}
 
}

Use of liaten listener

Servlet program: listen to servlet Listener
The main function is to monitor various Web operations. When relevant events are triggered, events will be generated and handled.

There are three types of listeners:
application listener
session listener
request listener

Event: click, move, keyboard, touch

1.application listener servlet -- ServletContext

Implementation: ServletContextListener (common)
Rewrite:

/ / called when the container starts
  public void contextInitialized(ServletContextEvent event){
    
  }

/ / called when the container is destroyed
  public void contextDestroyed(ServletContextEvent event){
    
  }


ServletContextEvent event method:
    . getServletContext() / / get the ServletContext object, that is, the context

Example:
    event.getServletContext().getContextPath();

2.Session listener
Implementation: HttpSessionListener (occasionally used)
Rewrite:
/ / called when the session is created
  public void sessionCreated(HttpSessionEvent event){

  }

/ / called when the session is destroyed
  public void sessionDestroyed(HttpSessionEvent event){

  }


HttpSessionEvent event method:
    . getSession() / / get the current session

Example:
    event.getSession().getId(); / / get the session ID

Implementation: HttpSessionAttributeListener (no, poor performance)
Rewrite:
/ / triggered when adding attributes
  public void attributeAdded(HttpSessionBindingEvent event){
    
  }

/ / triggered when the attribute is deleted
  public void attributeRemoved(HttpSessionBindingEvent event){
    
  }

/ / triggered when replacing attributes
  public void attributeReplaced(HttpSessionBindingEvent event){
    
  }


HttpSessionBindingEvent event method:
    . getSession() / / get session
    . getName() / / get the name of the attribute
    . getValue() / / get the content of the property

Example:
    event.getSession() / / get session
    event.getName() / / get the name of the attribute
    event.getValue() / / get the content of the property
    

3.request listener
Implementation: ServletRequestListener (no, poor performance)
Rewrite:
/ / called at the beginning of the request
  public requestInitialized(ServletRequestEvent event){

  }

/ / called at the end of the request
  public requestDestroyed(ServletRequestEvent event){

  }


ServletRequestEvent event event method:
    . getServletRequest() / / get the ServletRequest object
    . getServletContext() / / get the ServletContext object

Example:
    event.getServletRequest().getRemoteAddr(); / / get the IP address
    event.getServletContext().getContextPath(); / / get the current path

Instance statistics
 

package com.zking.listener;
 
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
 
public class OnlineCountListener implements HttpSessionListener,ServletContextListener {
 
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("The context object listener was destroyed....");
	}
 
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("The context object listener is initialized....");
		
		//Get context object
		ServletContext application = arg0.getServletContext();
		application.setAttribute("count", new Integer(0));
		
	}
 
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		System.out.println("The session object listener was created....");
		ServletContext application = arg0.getSession().getServletContext();
		
		Integer count = (Integer)application.getAttribute("count");
		if(count == null) {
			application.setAttribute("count", new Integer(1));
		}else {
			count++;
			application.setAttribute("count", count);
		}
		
	}
 
	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		System.out.println("The session object listener was destroyed...");
		ServletContext application = arg0.getSession().getServletContext();
		
		Integer count = (Integer)application.getAttribute("count");
		if(count == null) {
			application.setAttribute("count", new Integer(1));
		}else {
			count--;
			application.setAttribute("count", count);
		}
	
	}
 
}

After exiting, you need to manually call the destroyed method or arg0 getSession(). setMaxInactiveInterval(60); Automatic destruction

public class DestroySessionServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.invalidate();
    }
}
 

 

Why are session listeners and request listeners generally not used?
A: take the request listener as an example. If the request listener is used, it means that each request must trigger a listener, which greatly reduces the efficiency of the process rate, so it is rarely used.

Database help class util | entity class | method class and interface | dao Impl | business logic layer and interface biz Impl | servlet package | filter package | listener package | listen

Tags: Java Front-end Web Development html

Posted by tulleh on Sun, 15 May 2022 00:04:43 +0300