JavaWeb-10 lesson Filter

catalogue

1, Core tag library in JSTL

1. Label

2. Label

2, Filter filter  

  1. What is a Filter

  2. How does the filter intercept?

3.Filter life cycle

1. Three important methods in the Filter interface

          2.Filter mapping

1. Use the wildcard "*" to intercept all user requests

2. Intercept access requests in different ways

3.Filter chain

  4.FilterConfig interface

3, Automatic user login using Filter

4, Use Filter to realize unified whole station coding

1, Core tag library in JSTL

1. < C: foreach > label

In JSP pages, it is often necessary to iterate over the collection objects. Therefore, the Core tag library provides a
The < C: foreach > tag is specially used to iterate the elements in the collection object, such as Set, List, Map, array, etc., and can repeatedly execute the contents in the tag body. It has two syntax formats, as follows.
Syntax 1: iterate over a collection containing multiple objects

<c:forEach [var="varName"] items="collection" [varStatus="varStatusName"]
[begin="begin"] [end="end"] [step="step"]>
body content
</c:forEach>

Syntax 2: iterates over a set within a specified range

<c:forEach [var="varName"] [varStatus="varStatusName"] begin="begin"

end="end" [step="step"]>
body content
</c:forEach>

  • The var attribute specifies the name of the element to which the current iteration is saved in the page field.
  • The items property is used to specify the collection object to iterate over.
  • The varStatus attribute specifies the name of the current generation status information object saved in the page field.
  • The begin attribute is used to specify the number of elements in the collection to start the iteration, and the index value of begin starts from 0. If the items property is not specified, the iteration starts from the value specified in begin until the end of the iteration.
  • The step attribute is used to specify the step size of the iteration, that is, the increment of the iteration factor.
  • <%@ page language="java" contentType="text/html; charset=utf-8"
    	pageEncoding="utf-8" import="java.util.*"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head></head>
    <body>
    	<%
    		String[] fruits = { "apple", "orange", "grape", "banana" };
    	%>
    	String Elements in array:
    	<br />
    	<c:forEach var="name" items="<%=fruits%>">
     		${name}<br />
    	</c:forEach>
    	<%
    		Map userMap = new HashMap();
    		userMap.put("Tom", "123");
    		userMap.put("Make", "123");
    		userMap.put("Lina", "123");
    	%>
    	<hr/>
    	HashMap Elements in collection:
    	<br />
    	<c:forEach var="entry" items="<%=userMap%>">
    			${entry.key}&nbsp;${entry.value}<br />
    	</c:forEach>
    </body>
    </html>
    

     

    The begin, end, and step attributes of the < C: foreach > tag are used to specify the start index, end index, and step size of the loop, respectively. Use these attributes to iterate over a range of elements in a collection object.
     

    <%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" import="java.util.*"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head></head>
    <body>
      colorsList Set (specify iteration range and step size)<br />
    	<%
    		List colorsList=new ArrayList();
    		colorsList.add("red");
    		colorsList.add("yellow");
    		colorsList.add("blue");
    		colorsList.add("green");
    		colorsList.add("black");
    	%>
    	<c:forEach var="color" items="<%=colorsList%>" begin="1" 
         end="3" step="2">
    		${color}&nbsp;
    	</c:forEach>
    </body>
    </html>
    

  • count: indicates the sequence number of elements in the collection, counting from 1.
  • Index: indicates the index of the current element in the collection, counting from 0.
  • First: indicates whether it is currently the first element in the collection.
  • Last: indicates whether the current is the last element in the collection.  
    <%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" import="java.util.*"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <html>
    <head></head>
    <body style="text-align: center;">
    	<%
    		List userList = new ArrayList();
    		userList.add("Tom");
    		userList.add("Make");
    		userList.add("Lina");
    	%>
    	<table border="1">
    		<tr>
    			<td>Serial number</td>
    			<td>Indexes</td>
    			<td>Is it the first element</td>
    			<td>Is it the last element</td>
    			<td>The value of the element</td>
    		</tr>
    		<c:forEach var="name" items="<%=userList%>" varStatus="status">
    			<tr>
    				<td>${status.count}</td>
    				<td>${status.index}</td>
    				<td>${status.first}</td>
    				<td>${status.last}</td>
    				<td>${name}</td>
    			</tr>
    		</c:forEach>
    	</table>
    </body>
    </html>
    

    2. < C: URL > tag

When accessing a JSP page, some parameter information is usually passed in the URL. To facilitate this function, Core
A < C: URL > tag is provided in the tag library, which can construct a new address in the JSP page to rewrite the URL< c: The URL > tag has two syntax formats, as follows.
Syntax 1: no label entity

<c:url value="value" [context="context"] [var="varName"]
[scope="{page|request|session|application}"]>

Syntax 2: if there is a label entity, specify the construction URL parameter in the label body

<c:url value="value"[context="context"] [var="varName"]
[scope="{page|request|session|application}"]>
< C: param > label
</c:url>

  • The value attribute specifies the URL of the construct.
  • The context property is used to specify the name of other Web applications imported from the same server.
  • The Var property specifies the name of the property that saves the constructed URL address to the domain object.

The scope property is used to specify that the constructed URL is saved to the domain object.

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head></head>
<body>
	Use absolute path construction URL:<br />
	<c:url var="myURL" 
     value="http://localhost:8080/chapter07/register.jsp">
		<c:param name="username" value="Zhang San" />
		<c:param name="country" value="China" />
	</c:url>
	<a href="${myURL}">register.jsp</a><br />
	Use relative path construction URL:<br />
	<c:url var="myURL" 
     value="register.jsp?username=Tom&country=France" />
	<a href="${ myURL}">register.jsp</a>
</body>
</html>

2, Filter filter  

  1. What is a Filter

Filter is called a filter. Its basic function is to intercept the process of Servlet container calling Servlet, so as to
Servlet realizes some special functions before and after response processing.

  be careful:
Filters are used to intercept requests and responses and cannot generate responses, while servlet s are used to process requests and generate responses.

  2. How does the filter intercept?

1. After the client makes a request, the filter intercepts the client's HttpServletRequest before the HttpServletRequest reaches the Servlet
2. Check HttpServletRequest as needed, or modify HttpServletRequest header and data
3, call the doFilter method in the filter to release the request. After the request reaches the Servlet, it processes the request and generates an HttpServletResponse to send to the client
4. The filter intercepts the HttpServletResponse before it reaches the client
5. Check the HttpServletResponse as needed, and modify the HttpServletResponse header and data
6. Finally, the HttpServletResponse arrives at the client

3.Filter life cycle

1. Three important methods in the Filter interface

  • init() method: initialization parameters, which are called automatically when creating Filter. When we need to set initialization parameters, we can write them to this method.
  • doFilter() method: when the request to be executed is intercepted, doFilter will execute. This describes our preprocessing of requests and responses
  • Destroy () method: called automatically when destroying Filter
  • package cn.itcast.chapter08.filter;
    import java.io.IOException;
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    public class MyFilter extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        
        public MyFilter() {
            
        }
        public void destroy() {
        	
        }
    	
    	protected void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws  IOException, ServletException {
    		response.setContentType("text/html;charset=utf-8");
    		System.out.println("The output indicates that the response was intercepted");
    		response.getWriter().print("This is filter Content output to web page");
    		
    		if(true)
    		{
    			chain.doFilter(request, response);
    		}
    	}
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    
    }

    Configure the servlet in the web.xml file

  Block MyServlet

package cn.itcast.chapter08.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MyFilter extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
    public MyFilter() {
        
    }
    public void destroy() {
    	
    }
	
	protected void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws  IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		System.out.println("The output indicates that the response was intercepted");
		response.getWriter().print("This is filter Content output to web page");
		
		if(true)
		{
			chain.doFilter(request, response);
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Configure the servlet in the web.xml file

<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>cn.itcast.chapter08.filter.MyFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/MyServlet</url-pattern>
  </filter-mapping>
    

configuration information  

(1) The < Filter > root element is used to register a filter.
(2) The < Filter name > sub element is used to set the Filter name.
(3) The < Filter class > sub element is used to set the full name of the Filter class.
(4) The < filter mapping > root element is used to set the resources intercepted by a filter.
(5) The < filter name > child element must be the same as the < filter name > child element in < Filter >.
(6) The < URL pattern > sub element is used to match the URL requested by the user, such as "/ MyServlet". This URL can also be represented by the wildcard "*". For example "*. do" is applicable to all Servlet paths ending in ". do".

2.Filter mapping

1. Use the wildcard "*" to intercept all user requests

The < Filter mapping > element of Filter is used to configure the resource information intercepted by the Filter. If you want the Filter to intercept all requests for access, you need to use the wildcard "*". The specific example is as follows.

<filter>
<filter-name>Filterl</filter-name>
<filter-class>cn.itcast.chapter08.filter.MyFilter</filter-class></filter>
<filter-mapping>
<filter-name>Filterl</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>

2. Intercept access requests in different ways

stay   In the web.xml file, a < Filter mapping > element is used to configure the resources intercepted by a Filter< There is a special sub element < dispatcher > in the Filter mapping > element, which is used to specify how the resources intercepted by the Filter are called by the Servlet container. There are four values of the < dispatcher > element, as follows.
1) REQUEST
When the user directly accesses the page, the Web container invokes the filter. If the target resource is through RequestDispatcher   If it is accessed by the include() or forward() methods, the filter will not be called.
2) INCLUDE
If the target resource is accessed through the include() method of RequestDispatcher, the filter will be called.
program
In addition, the filter will not be called.
1.
3) FORWARD
If the target resource is accessed through the forward() method of RequestDispatcher, the filter will be called.
In addition, the filter will not be called.
If the target resource is called through the declarative exception handling mechanism, the filter will be called. In addition, filtering
4) ERROR
The handler will not be called.

The servlet class of the example forwardservlet is used to forward the request to first.jsp

package cn.itcast.chapter08.filter;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ForwardServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request,
           HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/first.jsp").forward(request,
       response);
	}
	public void doPost(HttpServletRequest request, 
      HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

Create a first.jsp page

Create a forward filter to intercept the first.jsp page

Configure filter mapping information

  This indicates that the first.jsp forwarded by the forwardservlet is not intercepted

You need to add a < dispatcher >

3.Filter chain

In a web application, multiple filters can be developed and written. These filters are called a Filter chain

The Web server determines which Filter to call first according to the registration order < mapping > of the Filter in the web.xml file. When the doFilter method of the first Filter is called, the Web server will create a FilterChain object representing the Filter chain and pass it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, The Web server will check whether there is a Filter in the FilterChain object. If so, call the second Filter. If not, call the target resource

be careful:

    1.FilterChain.doFilter(request,response) represents downward execution. If the next filter is still a filter, access this filter. If the current filter is already the end of the whole chain, access web resources

    2. The order of filters is determined by the configuration order of < filter mapping >

< URL pattern > can be written in several ways:

    1. Perfect match     Must start with '/'

    2. You can use the * wildcard

        --> 1. Directory matching        / a/*        /*         Requirement must start with '/'

        --> 2. Extension matching

            *. do        *. action     Required, cannot start with "/", but end with *. XXX

 
For example, create two new filters, myfiltero1 and myfiltero2

package cn.itcast.chapter08.filter;
import java.io.*;
import javax.servlet.*;
public class MyFilter01 implements Filter {
	public MyFilter01() {
		super();
		// TODO Auto-generated constructor stub
	}
	public void init(FilterConfig fConfig) throws ServletException {
		// The filter object is called during initialization, and some initialization parameters can be configured
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// It is used to intercept the user's request. If it matches the interception path of the current filter, this method will be called
		PrintWriter out=response.getWriter();
		out.write("Hello MyFilter01<br />");
		chain.doFilter(request, response);
	}
	public void destroy() {
		// The filter object is automatically called when it is destroyed to release resources
	}
}

package cn.itcast.chapter08.filter;
import java.io.*;
import javax.servlet.Filter;
import javax.servlet.*;
public class MyFilter02 implements Filter {
	public void init(FilterConfig fConfig) throws ServletException {
		// The filter object is called during initialization, and some initialization parameters can be configured
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// It is used to intercept the user's request. If it matches the interception path of the current filter, this method will be called
		PrintWriter out=response.getWriter();
		out.write("MyFilter02 Before<br />");
		chain.doFilter(request, response);
		out.write("<br />MyFilter02 After<br />");	
	}
	public void destroy() {
		// The filter object is automatically called when it is destroyed to release resources
	}
}

  Configure filters myfiltero1,myfiltero2 mapping

 

  4.FilterConfig interface

To get   Filter program in   Configuration information in web.xml file, Servlet   The API provides a FilterConfig   Interface, which encapsulates all the registration information of the Fiter program in web.xml and provides a series of methods to obtain these configuration information

example

package cn.itcast.chapter08.filter;
import java.io.*;
import javax.servlet.*;
public class MyFilter03 implements Filter {
	public MyFilter03() {
		super();
		// TODO Auto-generated constructor stub
	}
	private String characterEncoding;
	FilterConfig fc;
	public void init(FilterConfig fConfig) throws ServletException {
		// Get FilterConfig object
		this.fc = fConfig;
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// Output parameter information
		characterEncoding=fc.getInitParameter("encoding");
		System.out.println("encoding The values of initialization parameters are:"+characterEncoding);
		chain.doFilter(request, response);
	}
	public void destroy() {
	}
}

  Configure filter myfilter03 mapping

3, Automatic user login using Filter

1. Write user class

2. Realize the login page and home page

  Used to display the user's login information. If no user logs in, a hyperlink for user login is displayed in the index.jsp page. If the user has logged in, the login user name and a logout hyperlink are displayed in the index.jsp page

 

3. Write the login servlet to process the user's login request

  Log off user login

  4. Create filter

This class is used to intercept the access request of User login and judge whether the request contains the Cookie of User automatic login. If yes, obtain the User name and password in the Cookie and verify that the User name and password are correct. If it is correct, encapsulate the User's login information into the User object and store it in the Session domain to complete the User's automatic login

  5. Configure mapping information

In the web.xml file, configure all relevant Servlet and AutoLoginFilter filter information. Since you want to intercept all requests from users to access resources, set the path intercepted by the filter < filter mapping > element to "/ *"

  6. Operation project

4, Use Filter to realize unified whole station coding

1. Write form.jsp

  2. Create servlet

3. Create a filter

4. Configure mapping information

5. Start the project and test results

 

  The login button realizes the POST used for login, which can solve the Chinese garbled code. Click the GET used for hyperlink login to solve the Chinese garbled code

It can be seen that the effect of submitting a form by GET is the same as that by POST, and it will not change
There is a garbled code problem. Therefore, it can be explained that the function of unified whole station coding can be easily completed by using Fiter filter.

Keywords: Java Tomcat request

Added by Shamrox on Fri, 19 Nov 2021 18:59:10 +0200