Filter (beginner)

Filter filter

1 Filter what is a filter

  1. Filter filter is one of the three major components of Java Web. The three components are: Servlet program, Listener listener and filter filter
  2. Filter filter, which is the specification of Java EE. That is, the interface
  3. Filter filter is used to intercept requests and filter responses.

Common application scenarios for intercepting requests include:

  1. . permission check
  2. Journal operation
  3. transaction management
  4. ... wait

2. Initial experience of filter

Requirement: under your web project, there is an admin directory. All resources (html pages, jpg images, jsp files, etc.) in the admin directory must be accessed after the user logs in.

Thinking: Based on what we have learned before. We know that after logging in, users will save the login information to the Session domain. Therefore, to check whether the user logs in, you can judge whether the Session contains the user login information!!!

<% 
	Object user = session.getAttribute("user"); 
	// If it is equal to null, it indicates that you have not logged in 
	if (user == null) { 			
		request.getRequestDispatcher("/login.jsp").forward(request,response); return; 
	} 
%>

Workflow diagram of Filter:

Code of Filter:

public class AdminFilter implements Filter { 
	/**
	* doFilter Method, specifically used to intercept requests. Permission check can be done 
	*/ 
	@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 

		HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; 
		HttpSession session = httpServletRequest.getSession(); 
		Object user = session.getAttribute("user"); 
		// If it is equal to null, it indicates that you have not logged in 
		if (user == null) { 
			servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse); 
			return; 
		} else { 
			// Let the program continue to access the user's target resources 
			filterChain.doFilter(servletRequest,servletResponse); 
		} 
	} 
}

web. Configuration in XML:

<!--filter Label is used to configure a Filter filter--> 
<filter> 
	<!--to filter Create an alias--> 
	<filter-name>AdminFilter</filter-name> 
	<!--to configure filter Full class name of--> 
	<filter-class>com.atguigu.filter.AdminFilter</filter-class> 
</filter>

<!--filter-mapping to configure Filter Interception path of filter--> 
<filter-mapping> 
	<!--filter-name Indicates to which of the current interception paths filter use--> 
	<filter-name>AdminFilter</filter-name> 
	<!--
		url-pattern Configure interception path / Indicates that the request address is: http://ip:port / Project path / web Directory mapped to IDEA 
		/admin/* Indicates that the request address is: http://ip:port / Project path / admin/* 
	--> 
	<url-pattern>/admin/*</url-pattern> 
</filter-mapping>

Use steps of Filter:

  1. Write a class to implement the Filter interface
  2. Implement the filtering method doFilter()
  3. To the web Configure the interception path of Filter in XML

Complete user login

login.jsp page = = login form

This is the login page. login.jsp page <br> 
<form action="http://localhost:8080/15_filter/loginServlet" method="get"> 
	user name:<input type="text" name="username"/> <br> 
	password:<input type="password" name="password"/> <br> 
	<input type="submit" /> 
</form>

LoginServlet program

public class LoginServlet extends HttpServlet { 
	@Override 
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
		resp.setContentType("text/html; charset=UTF-8"); 
		String username = req.getParameter("username"); 
		String password = req.getParameter("password"); 
		if ("wzg168".equals(username) && "123456".equals(password)) { 
			req.getSession().setAttribute("user",username); 
			resp.getWriter().write("Login succeeded!!!"); 
		} else { 
			req.getRequestDispatcher("/login.jsp").forward(req,resp); 
		} 
	} 
}

3. Life cycle of filter

The life cycle of Filter contains several methods

  1. Constructor method
  2. init initialization method
    Step 1 and 2: execute when the web project starts (Filter has been created)
  3. doFilter filtering method
    Step 3: every time a request is intercepted, it will be executed
  4. Destroy destroy
    Step 4: when the web project is stopped, it will be executed (stop the web project and destroy the Filter)

4 FilterConfig class

The FilterConfig class, as its name implies, is the configuration file class of Filter filter.
Every time Tomcat creates a Filter, it will also create a FilterConfig class, which contains the configuration information of the Filter configuration file

The function of FilterConfig class is to obtain the configuration content of filter filter

  1. Get the name of Filter and the content of Filter name
  2. Get init param initialization parameters configured in Filter
  3. Get ServletContext object
    java code:
@Override public void init(FilterConfig filterConfig) throws ServletException { 
	System.out.println("2.Filter of init(FilterConfig filterConfig)initialization"); 

	// 1. Get the name of Filter and the content of Filter name 
	System.out.println("filter-name The values are:" + filterConfig.getFilterName()); 
	// 2. Get on the web Init param initialization parameters configured in XML 
	System.out.println("Initialization parameters username The values are:" + filterConfig.getInitParameter("username")); 
	System.out.println("Initialization parameters url The values are:" + filterConfig.getInitParameter("url")); 
	// 3. Get ServletContext object 
	System.out.println(filterConfig.getServletContext()); 
}

web.xml configuration:

<!--filter Label is used to configure a Filter filter--> 
<filter> 
	<!--to filter Create an alias--> 
	<filter-name>AdminFilter</filter-name> 
	<!--to configure filter Full class name of-->
	<filter-class>com.atguigu.filter.AdminFilter</filter-class> 

	<init-param> 
		<param-name>username</param-name> 
		<param-value>root</param-value> 
	</init-param> 

	<init-param> 
		<param-name>url</param-name> 
		<param-value>jdbc:mysql://localhost3306/test</param-value> 
	</init-param> 
</filter>

5 FilterChain filter chain

Filter filter
Chain chain
FilterChain is the filter chain (how multiple filters work together)

6 interception path of filter

– exact match

<url-pattern>/target.jsp</url-pattern>

The path configured above indicates that the request address must be: http://ip:port/ Project path / target jsp

– directory matching

<url-pattern>/admin/*</url-pattern>

The path configured above indicates that the request address must be: http://ip:port/ Project path / admin/*

– suffix matching

<url-pattern>*.html</url-pattern> 

The path configured above indicates that the request address must be in The end of html will be intercepted

<url-pattern>*.do</url-pattern> 

The path configured above indicates that the request address must be in It will be intercepted at the end of do

<url-pattern>*.action</url-pattern> 

The path configured above indicates that the request address must be in It will be intercepted at the end of action

Filter filter only cares about whether the requested address matches, not whether the requested resource exists!!!

Tags: Java servlet filter

Posted by Master Zen on Tue, 24 May 2022 04:24:00 +0300