JavaWeb (Super invincible, serious and easy to use, 4D collection!!!!)

1. JavaWeb

​ JavaWeb development is a combination, combining all the content of the previous learning. There are not many new contents of JavaWeb,
but the idea of ​​​​JavaWeb development should be formed at this stage. In the current development, JavaWeb-related technologies are not directly used, and even some The technology is no longer in use, but the mode and idea of ​​Web development require us to form
all the content in the early stage, which cannot be called software. The view and the underlying processing are not really combined. Starting with JavaWeb, we can see the view (interface) + server-side processing + database interact to form a complete project.

1.1 Development mode

​( 1) C/S:Client/Server (client/server)

Refers to installing a dedicated client on your own computer and using this client to interact with the server

​Similar to: QQ/WeChat/large-scale online games/multimedia teaching software
​ Advantages:
1. Easy to save (can effectively use bandwidth, only need to transmit changed data in network transmission, improve the retention rate of software)
2. Easy to use large software
​ Disadvantages:
1. High development cost
2. High maintenance cost

(2) B/S: Blag/Server (browser/server)

The B/S structure means that users can directly access through the browser, which is currently the most widely used method

​ Advantages:

  1. low development cost
  2. low maintenance cost
  3. Easy to develop directly
    Disadvantages:
    1. Not easy to save (users need to remember the URL) [for internal use]
    2. Currently not suitable for large data transmission

1.1.1 Related technologies of B/S structure

(1) Server: JavaSE\Database\Setvlet/JavaEE framework technology
(2) Client: HTML\avaScript\JQuery\Ajax\Other front-end frameworks

1.1.2 B/S operation mode

insert image description here

  • An IP address is the address of each computer on the network
  • The IP address we are using is dynamic

In web applications, all use the request-response mode;
in the B/S structure, there is no request to directly push data from the server to the client;

1.2 Server in JavaWeb – tomcat

1.2.1 Server

​ (1) Hardware server: a computer, cloud server
​ (2) Software server: A software server is also called an application server. It is a software running on a computer
on which other applications can be deployed and run. At this time, the software Let's call it a server.

1.2.2 tomcat server

Tomcat is a JavaEE application server. After the web application we write is published to the tomcat server, the server can be accessed by users (direct access through browsers and URLs) after the web application we write is used for compiling,
parsing, and publishing our programs.

1.2.3 Tomcat installation

Click to enter the official website to download

insert image description here
insert image description here

  1. Tomcat directory structure

insert image description here

  1. Configure environment variables
  • Add system variables:CATALINA_HOME

insert image description here

  • Add %CATALINA_HOME%inand%CATALINA_HOME%lib

insert image description here

  1. test run

​ Open cmd as an administrator, then enter the bin directory of tomcat, enterservice.bat install

​ Open the bin directory and double-click the startup.bat file.

insert image description here

Enter in the browser: http://localhost:8080/If it is successfully opened, it means that the download and configuration are successful

1.2.4 IDEA creates a javaweb project

​ Refer to this article: https://zhuanlan.zhihu.com/p/100092323

1.3 JSP

1.3.1 Introduction to Jsp

​ JSP full name: Java Server Page (Java Server Page)
JSP is to embed Java code in HTML files. In the page, Java code can be used to execute dynamic content, and HTML code can be used to execute static content.
Java code is responsible for function processing and dynamically generates results , HTML to beautify and display the results generated by the page and Java
Common encoding:
ISO-8859-1: Western encoding does not support Chinese
GB 2312: Support Chinese, only Simplified Chinese
GBK: Support Chinese, support Simplified Chinese and Traditional Chinese
​ UTF-8: supports languages ​​of all countries in the world

1.3.2 JSP page content composition

1. Static content: HTML/CSS/JavaScript

​ 2. Command <%@ command name %>: command name is generally used to set the page

3. Small script <%java code%>: used to write java code, in addition to not being able to define methods and properties, you can write any java code

​ 4. Expression <%=expression%>: used to output java content to the page

5. Declaration <%! Declaration content %>: used to declare methods in the page

6. Comments <%–JSP–%>: JSP comments

7. Standard action < jsp: action name />: used to execute a function in a JSP page

1.3.3 Execution process of JSP

.ispescape>.javacompile>.classimplement>The JVM
JSP page is inefficient when it is executed for the first time; because the first execution needs to be escaped before compiling and executing,
and from the second time, it will no longer be escaped and compiled to directly execute
the execution of the JSP page of the class file Two parts:
1. First, the server executes the Java code, and after execution, the execution result is responded to the client in the form of html.
2. The client interprets and executes the HTML code in response.

1.3.4 Use request and response objects to realize user registration and login functions [simple user management project]

The source code is here, you need to get it yourself

  1. JSP processing flow

insert image description here

  1. request object

    Request object, the client sends the request object to the server

    request.getParameter("paramName"): Obtain the corresponding parameter value (form) according to the parameter name submitted by the client
    request.setCharacterEncoding("UTF-8"): Set the encoding set of the request object
    request.setAttribute( "key", "value"): An attribute is stored in the scope of the request object (multiple attributes can be stored)
    request.getAttribute("key"): Get the attribute value stored in the request object according to the attribute name
    request.getRequestDispatcher(url). forward(request, response): request forwarding

  2. response object
    Response object, the response object sent by the server to the client is called
    response.sendRedirect("ur1"): redirection, used to realize page jump (similar to hyperlink, but redirection does not need to click to automatically jump)
    Redirection can be used to achieve page jumps, but the "request object" cannot be passed to the target page

  3. What is the difference between request forwarding and redirection? (Interview must ask questions)
    Common point: Both can realize page jumping
    Differences:
    (1) The browser displays different addresses in the address bar

    • The address displayed in the address bar of the browser is the target address when the redirection is realized

    • The address displayed in the browser address bar is the source address (forwarding source) when request forwarding is implemented

    (2) Transfer data is different

    • Redirection can use the form of "url parameter transfer" to transfer data in the form of project address when realizing jump
    • Request forwarding can use the form of "url parameter transfer" to transfer data in the form of project address when implementing jump, and can also transfer "request object" to the target address

    (3) Different processor mechanisms

    • Redirection is equivalent to sending another request to the server when redirecting
    • Request forwarding to realize the jump belongs to the internal jump of the server, and the jump processing is performed directly inside the server, and the request will not be sent again. Therefore, when using request forwarding, the original request object can be forwarded to the target location, and the effect of request extension has been achieved.
  4. The choice of request forwarding and redirection?
    Generally, if you want to jump to the page and do not need to pass the request data, we use redirection at this time.
    If it is a jump between handlers inside the server or to the If the request object is passed to the page, it is recommended to use request forwarding at this time

1.4 JSP built-in objects

1.4.1 What are built-in objects

Built-in objects are not created by developers, but by "application server (tomcat)", and these objects can be used directly in JSP pages

1.4.2 JSP nine built-in objects (implicit objects)

  • request: (request object)

    He is a scope object, representing a request sent by the client to the server

    • The life cycle of request: only one request, when the client sends a request to the server, the server will discard the request directly when it runs out
      • By default, the life cycle of the request object is limited to one request, and the life is relatively short
      • Extend the life cycle of the request object, and pass the request object to other JSP pages or Servlets by means of "request forwarding", so that the request object can be extended
    • Data in the request object:
      • When sending a request, the client will send the related data of the client "in the form of bytecode" to the server, and the server will decode the bytecode of these requests and encapsulate them into the request object

      • Data sent by client:

        • Client host information
        • Client browser information
        • Request header additional information
        • Request parameters (form data/url data)
  • The request object can also store attributes. These attributes are not passed in by the client, but the data that the server actively stores in the request for "passing data".

    • Scope objects in JavaWeb can add properties through which data can be passed
      • The request internally uses the Map collection to store attributes, the key is of String type, and the Value is of Object type
    • request.setAttribute("key", "value"): Store an attribute in the scope of the request object
      request.getAttribute("key"): Obtain the attribute value stored in the request object according to the attribute name
    • remove.getAttribute
  • Common methods:

    (1) request.setCharacterEncoding("utf-8"):设置request对象的编码集
    (2) request.getParameter("paramName"):根据参数名获得对应的参数值
    (3) request.getParameterValues("paramName"):根据参数名获得一组同名的参数值,返回字符串数组
    (4) request.setAttribute(attrName,attrValue):向request作用域中设置一个属性
    (5) request.getAttribute(attrName);从request作用域中获取一个属性的值,默认为Object类型
    (6) request.getRequestDispatch(url).forward(request,response);请求转发
    
  • response: Response object, the server's response to the client

    • The server can also pass data to the client in response, and what is passed is a string

      • There are three ways for the response object to transfer data to the client:

        • pass parameters through url

        • pass through cookies

          //创建Cookie对象
       Cookie cookie = new Cookie("phone","110");
         //将cookie对象添加到response对象中
         response.addCookie(cookie);
         response.sendRedirect("demo2.jsp");
      
      • Pass through I/O stream (commonly used after front-end and back-end separation)
         PrintWriter writer = response.getWrite();
                         out.println("hello");
      
    • Common methods of response objects:

         response.sendRedirect(url) //重定向,用于实现页面跳转
         response.setContentType("text/html;charset=utf-8") //设置响应的内容类型及编码集
         response.addCookie(cookie)  //向请求对象中添加Cookie对象,此时response对象就会将cookie发送到客户端由浏览器保存cookie
         response.getWrite();获得一个输出流,通过该输出流可以向客户端直接输出内容,如果需要输出中文则需要设置"内容类型"
      
  • session: session object

    Indicates a session, what is a session?

    • A session refers to a collection of request responses
    • Session refers to the first time the client sends a request to the server, until the client browser is closed or the server is closed or timed out or manually destroyed and terminated
    • All "requests and responses" during a session are in the same session

    Why does JavaWeb have the concept of session?

    • Understand the Http protocol: The Http protocol is a stateless protocol. Stateless means that the connection state between the client and the server will not be maintained under this protocol.
    • Since we use the Http protocol, the server cannot determine whether the request has been made before, but the state of the current client and server can be maintained through the session
    • In web development, sessions can be used to maintain the relationship between the client and the server

    How to use session to maintain the relationship between client and server in web applications?

    • Maintained by sessionId
      insert image description here

      1. When the client accesses the server for the first time, whether there is a corresponding sessionId on the server, if not, it is the first visit

      2. The server creates a session object to generate a unique sessionId, saves the sessionId to the server and responds to the client

      3. When the client browser receives the sessionId, it will automatically save the sessionId (temporary storage)

      4. The sessionId is automatically sent to the server every time the client sends a request to the server

      5. The server receives the sessionId to check whether the sessionId is valid, and can obtain data from the session object at the same time

    • Session depends on the browser, and different browsers generate different sessionIds

      session start and destroy conditions

      • Start: The client accesses the server for the first time
    • Destruction can be done in the following ways:

      1. close browser

      2. The server is manually destroyed, using session.invalidate(); to destroy

      3. Timeout, when the client does not send any request to the server within a certain period of time, the server will consider the session invalid and automatically destroy it (tomcat's default timeout is 30 minutes)

      4. server shutdown or restart

      • Session is also a scope object, and its scope is from the first request to the end of session destruction, and the data in the scope is shared with the same session
    • Session common methods

      session.getId():获得sessionId
      session.invalidate():销毁session
      session.setAttribute(attrName,attrValue):向session作用域中存放一个属性
      session.getAttribute(attrName):从session中获取一个属性值
      
  • application: application server object

    • This object represents the current application server

    • This object is also a scope object, which can store data, but this object is scoped to the entire server, and this object can be obtained by anyone at any location

      Therefore, the data stored in the application object is the shared data of the entire server, and the data about the user is not allowed to be stored in the object

  • out: output object (output content object to the page, this object is not in use)

  • page: Indicates the current object (current page object, equivalent to this keyword)

  • pageContext: page context object (current page context object, this object is not used)

  • config: configuration object (configuration object, configuration information can be obtained in the page, not used)

  • exception: exception object (handle JSP page exception, no longer used)

1.5 Servelt (key)

1.5.1 Basic use of Servlet

  1. What is servlet ? (interview question)

Answer: The servlet class is a Java class running on the server side. This class has respect (request object), response (access object), and access address

  1. The role of servlet

Used to obtain client requests and respond to clients

  • Mainly responsible for requests and responses, without specific function processing, calling classes and methods for underlying function processing
  1. Use of Servlet
  • (1) Create a class that inherits the HttpServlet class. When a class inherits the HttpServlet class, this class is the Servlet class.

  • (2) Rewrite the doGet and doPost methods of the HttpServlet class (rewrite one or both of them)

    doGet method: used to process the get request submitted by the client

    doPost method: used to process the Post request submitted by the client

    The difference between Get and Post requests (interview focus)

    1. The get request is generally to get the data (in fact, it can also be submitted, but the common way is to get the data); the
      post request is generally to submit the data.

    2. Because the parameters of get will be placed in the url, the privacy and security are poor. The length of the requested data is limited.
      Different browsers and servers are different. Generally, the limit is between 2~8K, and the more common one is within 1K. ;
      There is no length limit for post requests, and the request data is placed in the body;

    3. The get request refreshes the server or rollback has no effect, and the data request will be resubmitted when the post request rolls back.

    4. Get requests can be cached, post requests will not be cached.

    5. Get requests will be saved in the browser history, post will not.
      Get requests can be bookmarked because the parameters are in the url, but post cannot. Its parameters are not in the url.

    6. Get requests can only be url encoded (application-x-www-form-urlencoded),
      post requests support multiple types (multipart/form-data), etc.

  • (3) Configure the Servlet. There are two ways to configure the Servlet:

    The instance of the Servlet class is not created by the developer itself, but by the application server itself.
    Once the Servlet class is successfully created, it is stored in the memory of the server.

    Once the Servlet is created, it is stored in the memory of the server, and the Servlet object can be accessed through the "mapping address" of the Servlet object

    Servlet access flow :

    ​ (1) The client directly accesses the url-pattern, and the server will search for the servlet object corresponding to the current mapping path according to the url-pattern

    (2) Find the object name corresponding to the current object according to the servlet object name

    (3) Execute the corresponding method in the object according to the request type

    • (1) Configure in the web.xml file
    <!--  servlet配置
               servlet-name:指定对象的对象名
               servlet-class:
    -->
      <servlet>
        <servlet-name>demoServlet</servlet-name>
        <servlet-class>com.jiazhong.registeAndLogin.servlet.ServletDemo</servlet-class>
      </servlet>
      <!--servlet映射配置
            servlet-name:Servlet对象名,与servlet配置的对象名一致
            url-pattern:配置当前Servlet映射地址,地址名可以任意
      -->
      <servlet-mapping>
        <servlet-name>demoServlet</servlet-name>
        <url-pattern>/demo.do</url-pattern>
      </servlet-mapping>
    
    • (2) Configure with annotations

      • Use the @WebServlet (current Servlet access path) annotation on the Servlet class to configure

        • By default, the name of the Servlet object is lowercase with the first letter of the class name
        • Complete configuration @WebServlet (name="name specifies the object name" urlPatterns="specifies the path name" the current Servlet access path)

1.5.2 Servlet modification registration and login function [simple user management project]

The source code is here, you need to get it yourself

1.5.3 Servlet lifecycle management

Servlet life cycle

The process of Servlet from creation to demise

  • The first request and Servlet: first execute the parameterless construction method to create the Servlet object, then execute the init method, execute the doGet method

  • From the second request, instead of creating a Servlet object, directly access the doGet method (service method)

    (1) The life cycle of Servlet includes the following stages:

    • Instantiation: Call the no-argument constructor to create a Servlet object (created by the Web server)
      When the Servlet is requested for the first time, the Web server will instantiate the Servlet and create a Servlet class object
      Created at the first visit, the object is created It is resident in memory, and the object is obtained from the memory every time it is accessed and used directly
    • Initialization: When a Servlet object is created, it will automatically call the initialization method to perform initialization operations. This method will only be called once​
    • Service: Service refers to doGet|doPost|doDelect|doPut|Servcie... These are all service methods
      ​ Every time a Servlet is requested, a certain service method will be executed, and the service method executed according to the type of request is different
    • Destroy: When the server is closed, the destroy method will be called automatically to clean up the resources occupied by the current Servlet

    Servlet creation timing :
    1. By default, when the user accesses the Servlet for the first time, the server will create a Servlet object (lazy loading mechanism)
    2. We can 注解add "loadOnStartup=0"or web.xmladd <servlet>tags <lodad-on-startup>to modify the creation priority of Servlet creation, When the value is 0, it means that the Servlet object will be created automatically when the server starts

1.5.4 Servlet class structure and execution process

  • Custom Servlet inherits HttpServlet
  • HttpServlet inherits GenericServlet
  • GenericServlet implements the Servlet interface
  • Our current project is a web project, and all web projects are based on the Http protocol. HttpServlet is a Servlet based on the Http protocol.
  • The client request is sent to the doGet or doPost request in the Servlet
  • The client sends a request directly to the service method (service method) in the HttpServlet class, and then the method of judging the request in the service method is delegated to doGet or doPost or other methods for execution according to different request methods
  • Our implementation rewrites the service method in the custom Servlet, processes the function directly in the service method, and does not delegate the request to the doGet or doPost method...

1.5.5 Use request forwarding and redirection to implement functions [simple user management project]

The source code is here, you need to get it yourself

  • Administrator login function
    • The client enters the administrator account and password, defines a loginServlet to obtain data from the client, passes it to the underlying adminLogin method, and obtains a respnse response
      • Get data using request
      • Pass the acquired data into the underlying function implementation
      • Response redirects to success page and request forwards to failure page
  • User query function
    • To retrieve user information from the database
    • Define a queryuserServlet to obtain user data from the server and display it in the JSP page
    • Pass the data from the server to the JSP page, and the page displays
  • User delete function
    • Pass the user ID to the server
    • The server obtains the user number, sends a delete SQL statement to the database and deletes the specified data
    • Jump to the user list after successful deletion
  • User modification function
    • Send the request to the Servlet that gets the user information based on the user ID
    • Call the underlying function implementation
    • Bottom layer returns query results
    • Submit user information to the modification page display
    • Submit the modification to "Modify Servlet", and the Servlet will call the underlying function
    • Return modified data to "Modify Servlet"
    • Jump from "Modify Servlet" to the user list page display

1.6 JSP tag library and EL expressions

There will be a lot of JAVA code in the JSP page

  • There is a problem:
    1. JSP pages are messy
    2. Not suitable for front-end staff to develop front-end code
  • If we also use JSP pages in development, we need to implement scriptless pages
  • Use JSTL and EL expressions in development to implement scriptless pages
  • JSTL and EL can be used alone, generally used together

1.6.1 Basic use of JSTL

  1. What is a JSTL page

    The full name of JSTL is JSP Standard Tag Library. By using JSTL, some tags can be used to implement logical processing capabilities on JSP pages.

    Although JSTL is a page tag, there is a Java class inheritance behind each tag

  2. JSTL contains the following tags

    1. Core tag: This tag is mainly used to process page logic programs such as: if|for...
    2. Formatting tag: This tag is mainly used to deal with time and number formats
    3. SQL tag: This tag allows JSP pages to use SQL statements, which is not allowed for development (not used)
    4. XML tag: This tag allows parsing and processing of XML files in JSP pages (not applicable)
    5. I18N tag: (internationalization): internationalization tag, mainly used to deal with multilingual systems
    6. fn function: The fn function provides some methods for processing, such as the common method of obtaining the size of the collection and string
  3. Use of JSTL

    ①Introduce JSTL dependency package in Maven

    <dependency>
              <groupId>org.apache.taglibs</groupId>
              <artifactId>taglibs-standard-compat</artifactId>
              <version>1.2.5</version>
          </dependency>
    

    ② JSP page imports JSTL core tag library

    <%--
        taglib:引入JSTL标签库
        prefix:设置标签的前缀,核心标签一般为c
        url:指定标签库位置
    --%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    

    ③Used in the page

  4. Common tags of JSTL core tags

    ①out tag: <c:out>, the out tag is mainly used to output content to the page

    <c:out value="${name}" default="自定义内容" escapeXml="false"/>
    <!--
        value:表示输出的值,如果输出的值为EL表达式,则表示为某个作用域的值
        default:默认值,若value没有值则输出 dafault的值
        escapexml:是否对xml/html解释执行
    --!>
    

    ②set tag: <c:set>, used to set attributes to a certain scope, used to replace setAttribute();

    <c:set value="20" var="age" scope="request"></c:set>
    <!--
        向requst作用域设置一个age=20的属性	
    -->
    

    ③remove tag: <c:remove>, mainly used to remove an attribute from a scope

    <c:remove var="age" scope="request"></c:remove>
    <!--
       删除request中属性名为age的属性
    -->
    

    ④if label: <c:if>single branch statement label

    <c:if test="${判断语句}">
        输出内容
    </c:if>
    <!--
    判断test属性的值,如果为true则执行标签体内容,如果为false则不执行
    *JSTL中只有if标签没有else标签,JSTL没有if-else标签,JSTL可以使用choose标签来替代
    -->
    

    ⑤choose tag: <c:choose>equivalent to the Switch statement in java, this tag cannot be used alone, it must be used with the when tag and the otherwise tag

    <c:choose>
        <c:when test="判断语句">输出内容</c:when>
        <c:when test="判断语句">输出内容</c:when>
        <c:otherwise>其他内容</c:otherwise>
    </c:choose>
    <!--
       判断 第一个when标签的test属性,若true则执行,反正向后继续执行,
       若when标签test属性都为false
        则返回 otherwise标签  
    -->
    

    ⑥forEach tag: <c:forEach>equivalent to the for loop in java

    <%
        List<String> strList =new ArrayList<>();
        strList.add("1");
        strList.add("2");
        strList.add("3");
        request.setAttribute("strList",strList);
    %>
    <c:set var="str" value="${strList}" scope="request"></c:set>
    <c:forEach var="str1" items="${str}" varStatus="status">
           ${str1}--->${status.index}---->${status.count}<br>
    </c:forEach>
    
    <!--
        items:用于执行遍历的集合
        str:每次遍历的值会赋给该遍历
        varStatus:循环的状态
              循环下标:status.index 循环次数:status.count
    -->
    
    <c:forEach begin="1" end="9" step="1" varStatus="status">
        ${status.index}-------->你好《=<br>
    </c:forEach>
    <!--
           begin:从某值开始循环,起始大小
           end:表示结束大小
           step:表示步长,相当于 i++,i+2....
    --!>
    
  5. Use of formatting tags

    • Introducing formatting tags

      <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
      
    • format time:

      <fmt:formatDate value="${nowTime}" pattern="yyyy年MM月dd日 HH:mm:ss"/>
      
    • format number

      <fmt:formatNumber value="1234567895.646" pattern="###,###,###.##"></fmt:formatNumber>
      

1.6.2 Use of EL expressions

Used to replace <%=Java code%> in JSP

Introduction to EL expression syntax, powerful functions, a large number of EL expressions will be used in JSP pages instead of traditional scripts

EL expressions are mainly used to get the value of the attribute from the scope and output it to the page

  1. Basic functions of EL expressions

    The computer outputs content to the page

    --------------------------Separator---------------------- -----------------

    EL expression is currently disabled by default, and it needs to be configured to use it. Setting it on the JSP page isELIgnored="false" means turning off EL expressions, or configuring it in the Web.xml file. The web.xml file generated by creating a project is not a standard configuration file. can be deleted

    • The web.xml file in the config folder in the server is shared with our project, and the EL expression is configured in it and can be used normally
    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    
    • Calculate and output the content

      ${
              
              "hello,word"} 
      ${
              
              2+2}
      
    • get object from scope

      JSP scope objects include request, session, and application, all of which can store attributes, and the values ​​of attributes can be easily obtained from these three scopes through EL expressions

      <c:set value="1" var="sex" scope="request"/>${sex==1?"男":"女"}
      <!--传统方式-->
      <br><hr>
      <%
          Integer i=Integer.valueOf((String) request.getAttribute("sex"));
      %>
      <%=i+10%>
      <!--使用EL表达式-->
      ${sex+11}
      
      • The Object type needs to be converted in the traditional way, but it is automatically converted using EL expressions

      The values ​​obtained by EL expressions from the scope are ordered by default: according to the scope range from small to large

      • page---->request------->session------>application

      Since EL expressions look up data from the scope object with the smallest scope by default, unless the attribute is in the page scope, it will look for other scopes, which is not efficient

      Generally we will avoid the automatic search of EL expressions from the scope, we search from the specified scope

            <c:set var="name" value="sessionName" scope="session"/>
            <c:set var="name" value="application" scope="application"/>
            <c:set var="name" value="requestName" scope="request"/>
      ${sessionScope.name}------->session作用域取值<br>
      ${requestScope.name}-------->request作用域取值<br/>
      ${applicationScope.name}------->application取值<br/>
      
    • Get the property value in the object

      • The name used by the EL expression to obtain the value of the attribute from the entity object has nothing to do with the attribute name ${requestScope.student.stuName}

      • The EL expression internally converts the first letter of the string "stuName" to uppercase and splices the "get" string in front to form the method name string of the get method

      • Then use reflection technology to obtain the method object of the get method according to the method name of the get method and call the method

      • Simply understand that EL is based on the acquisition of entity object attribute values ​​​​based on the get method

1.6.3 Use JSTL and EL expressions to modify [Simple User Management Project]

The source code is here, you need to get it yourself

1.7 Filter Filter

1.7.1 What is a filter?

  • Used to intercept requests and responses sent to the system (requests intercepted by different filters are determined by different configurations)
  • Filters are special Servlets, which do not need to be called after the filter configures the path. When the current path of these configurations is requested, the filter is automatically called
  • When a request is made to access the system, the filter first receives the request and processes it. After processing, the request is passed to the next filter or Servlet

1.7.2 Using filters

  • Create a class that implements package javax.servlet.Filterthe interface

  • Implement the doFilter method of the interface (this method is used to implement the filtering logic)

    • There must be result processing in doFilter (release the request or transfer it to other places), otherwise the request will stay in the filter

      filterChain.doFilter(servletRequest,servletResponse);//Allow to continue to visit the location

      • The code is preceded by the request period code, followed by the response period code
  • configure filter

    • Configuration based on Web.xml configuration file
       <!--
             配置过滤器对象,配置后tomcat会自动创建过滤器对象
              <filter-name>:指定过滤器对象名
              <filter-class>:指定要配置过滤器的类
       -->
        <filter>
            <filter-name>demoFilter</filter-name>
            <filter-class>com.jiazhong.filters.demoFilter</filter-class>
        </filter>
        <!--
           配置过滤器映射,配置后当浏览器访问该映射路径时对应过滤器会自动执行
           <filter-name>:要执行的过滤器对象
           <url-pattern>: 过滤器映射路经,配置后,只要访问该路径下资源过滤器自动执行
        -->
        <filter-mapping>
            <filter-name>demoFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    • Annotation- based @WebFilter()configuration

1.7.3 What is the lifecycle of a filter?

① When the server starts, the Filter object is created and the init method is automatically executed

② Execute the doFilter method in Filter to implement the filtering function every time the web resource intercepted by the filter is accessed

③ When the server is closed, execute the destroy method of Filter to destroy related resources

1.7.4 What is a filter chain

  • An execution chain is composed of multiple filters, which is the filter chain
  • When the system accesses multiple filters, request access selects which filters to execute based on the interception path configuration of each filter

1.7.5 Filter Execution Order

  • When configuring based on annotations, the comparator in the string will be used to sort according to the alphabetical order of the class name
  • If it is based on xml configuration, it will be executed in sequence according to the configuration mapping path

1.7.6 Use filters to complete simple filtering functions and improve [Easy User Management Project]

The source code is here, you need to get it yourself


  • Learning comes from Xi'an Jiazhong training

Guess you like

Origin blog.csdn.net/woschengxuyuan/article/details/126957659