The mental journey of learning the front-end web------the three major components of the web: Servlet, Filter, Listener


insert image description here

Servlet

1. The role of Servlet:

  In the Java web b/s architecture, servlet plays an important role. As a transit processing container, it connects the client and server for information exchange and processing. Simply put, the client sends a request and passes it to the servlet container, and the servlet converts the data into data that the server can process and sends it to the server. After the data is processed, it is passed to the servlet container, and the servlet is translated to the client. An information exchange between the client and the server is completed.

  Servlet is written in Java, because it also has some characteristics of Java, such as cross-platform, high scalability, but its advantages are not limited to language, because the emergence of Servlet, we can make JSP pages Some of the JAVA codes in the Servlet are transplanted into the Servlet, which undoubtedly makes the front-end personnel deeply liked, which facilitates the modification and improvement of the project, and the use of the Servlet is also very simple.

  The life cycle of a servlet has four stages. The first stage is instantiation, which calls the constructor method, the second stage is initialization, which calls the init() method, the third stage is request processing, which calls the service method, and the fourth stage is initialization. In this stage, the service termination is the destruction stage, and the destroy method is called.

  How does the foreground pass data to the servlet? It is also very simple. It can be easily completed by just submitting the form. Servlet can use request.getParameter to accept it, and pass it to the front desk to assign value using request.setA or something.

  When the page is submitted, there are two methods: get and post. These two methods will be processed in the Servlet. If it is get, it will call doget, and post will dopost. When using it at the same time, it only needs to call the doget method for post.

2. Other knowledge points of Servlet

For more knowledge about Servlet, refer to the blog written by the blogger before:
  Servlet Blog 1
  Servlet Blog 2

Filter

1.Introduction of Filter:

  Filter can be considered as a "variant" of Servlet. It is mainly used to preprocess user requests (HttpServletRequest) and post-process server responses (HttpServletResponse), which is a typical processing chain. It differs from a servlet in that it cannot generate a response directly to the user. The complete process is as follows: Filter preprocesses the user request, then hands the request to the Servlet for processing and generates a response, and finally the Filter post-processes the server response.

2.Filter concept:

  • Filters in life: water purifiers, air purifiers, bandits,
    • Filters in the web: When accessing the resources of the server, the filter can intercept the request and complete some special functions.
    • The role of the filter:
      • Generally used to complete common operations. Such as: login verification, unified encoding processing, sensitive character filtering...

3.The role of Filter:

  Filter is used to intercept user requests. Before the server responds, the requestsum can be modified after interception response, so as to achieve many functions that developers want.

  A filter is a reusable code snippet that can be used to transform HTTP requests, responses and headers. Unlike Servlet, Filter cannot generate a request or response, it just modifies the request for a resource, or modifies the response from a certain resource.

4. Quick Start:

步骤:

1.定义一个类,实现接口Filter
2. 复写方法
3. 配置拦截路径
   a. web.xml
   b. 注解
   
例:代码
//第一种方式注释配解
@WebFilter("/*")//访问所有资源之前,都会执行该过滤器
		public class FilterDemo1 implements Filter {
    
    
		    @Override
		    public void init(FilterConfig filterConfig) throws ServletException {
    
    }
		    @Override
		    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
		        System.out.println("filterDemo1被执行了....");
		        //放行
	            filterChain.doFilter(servletRequest,servletResponse);
		    }
		    @Override
		    public void destroy() {
    
    }
		}
//第二种方式 web.xml配置	
		<filter>
	        <filter-name>demo1</filter-name>
	        <filter-class>cn.itcast.web.filter.FilterDemo1</filter-class>
	    </filter>
	    <filter-mapping>
	        <filter-name>demo1</filter-name>
			<!-- 拦截路径 -->
	        <url-pattern>/*</url-pattern>
	    </filter-mapping>
5. 过滤器执行流程
	1. 执行过滤器
	2. 执行放行后的资源
	3. 回来执行过滤器放行代码下边的代码
6. 过滤器生命周期方法
	1. init:在服务器启动后,会创建Filter对象,然后调用init方法。只执行一次。用于加载资源
	2. doFilter:每一次请求被拦截资源时,会执行。执行多次
	3. destroy:在服务器关闭后,Filter对象被销毁。如果服务器是正常关闭,则会执行destroy方法。只执行一次。用于释放资源
7. 过滤器配置详解
	* 拦截路径配置:
		1. 具体资源路径: /index.jsp   只有访问index.jsp资源时,过滤器才会被执行
		2. 拦截目录: /user/*	访问/user下的所有资源时,过滤器都会被执行
		3. 后缀名拦截: *.jsp		访问所有后缀名为jsp资源时,过滤器都会被执行
		4. 拦截所有资源:/*		访问所有资源时,过滤器都会被执行
	* 拦截方式配置:资源被访问的方式
		* 注解配置:
		 * 设置dispatcherTypes属性
			1. REQUEST:默认值。浏览器直接请求资源
			2. FORWARD:转发访问资源
			3. INCLUDE:包含访问资源
			4. ERROR:错误跳转资源
			5. ASYNC:异步访问资源
		* web.xml配置
			* 设置<dispatcher></dispatcher>标签即可

Listener

1. Concept:

  Listener is a special Servlet technology, it can monitor the context information, Servlet request information and Servlet session information of Web applications, namely ServletContext, ServletRequest, HttpSession. And according to different situations, the corresponding handler is called in the background. Use the listener to monitor and control the Web application to enhance the event processing capability of the Web application.
insert image description here

* ServletContextListener:监听ServletContext对象的创建和销毁
	* 方法:
		* void contextDestroyed(ServletContextEvent sce) :ServletContext对象被销毁之前会调用该方法
		* void contextInitialized(ServletContextEvent sce) :ServletContext对象创建后会调用该方法
	* 步骤:
		1. 定义一个类,实现ServletContextListener接口
		2. 复写方法
		3. 配置
			1. web.xml
					<listener>
 					 <listener-class>cn.itcast.web.listener.ContextLoaderListener</listener-class>
					* 指定初始化参数<context-param>
			2. 注解:
				* @WebListener

The difference between servlet and filter

  Filter: It can be understood that a special servlet is mainly used to preprocess user requests. It is also possible to post-process the HttpServletResponse which is a typical processing chain filtering the request and cannot generate a response to the user.
  Servlet: Mainly used to control the url before business processing, and then process it. After the processing is completed, return or redirect to a page designated by oneself, which can generate a response to the user.
  transitivity: 1. Filter is transitive. After the url is sent and checked, the original process can continue to be executed downwards and be received and processed by the next filter and servlet.
      2. Servlet is not transitive. Once processed by the servlet, it does not continue to pass down.
  Process flow: Filter preprocesses the user request; then, the request is handed over to the Servlet for processing, and a response is generated; finally, the Filter post-processes the server response.

  1. servlet 流程是短的After the url is sent, it will be processed, and then returned or redirected to a page designated by itself. It is mainly used for control before business processing.
  2. filter 流程是线性的After the url is sent and checked, the original process can be maintained to continue to be executed downward, and it will be received by the next filter, servlet, etc., and after the servlet is processed, it will not continue to be passed downward. The filter function can be used to keep the process going in the original way, or to dominate the process, while the servlet function is mainly used to dominate the process.
  filter can be used to filter character encoding, detect whether the user is logged in, prohibit page caching, etc.
insert image description here

Guess you like

Origin blog.csdn.net/S_yyuan/article/details/123344722