Java web core knowledge

Introduction to Java Web

  • Web: global wide area network, also known as the world wide web (www), a website that can be accessed through a browser.

  • JavaWeb: use Java technology to solve the technology stack in the field of web and Internet.

  • B/S architecture: Browser/Server architecture mode. Its feature is that the client only needs a browser, and the logic and data of the application are stored in the server. The browser only needs to request the server to obtain the Web resources, and the server can send the Web resources to the browser.

    • Benefits: easy to maintain and upgrade. After the server is upgraded, the client can use the latest version without any deployment
    • Static resources: HTML, css, JavaScript, pictures, etc. Responsible for page display
    • Dynamic resources: servlets, JSPS, etc. Responsible for logic processing
    • Database: responsible for data storage
    • HTTP protocol: define communication rules
    • Web server: responsible for parsing HTTP protocol, parsing request data and sending response data

HTTP

concept

HyperText Transfer Protocol specifies the rules of data transmission between browser and server.

characteristic
  • Based on TCP protocol: connection oriented, providing reliable data transmission
  • Based on request response model: one request corresponds to one response
  • http protocol is a stateless protocol: it has no memory ability for transaction processing, and each request response is independent
    • Disadvantages: data cannot be shared between multiple requests. Use Java session technology to solve this problem
    • Advantages: high speed
Request data format

The request data is divided into three parts:

  • Request line: the first line of requested data. Where GET indicates the request mode, / indicates the request resource path, and HTTP/1.1 indicates the protocol version
  • Request header: starting from the second line, in the form of key: value
  • Request body: the POST request method is unique. In the last part of the request data, note that there should be a blank line between the request body and the request header to store the request parameters

Common HTTP request headers:

  • Host: indicates the host name of the request
  • User agent: browser version. For example, the logo of Chrome browser is similar to Mozilla/5.0 Chrome/79
  • Accept: indicates the type of resources that the browser can receive, such as text / *, image / * or * / * indicates all;
  • Accept language: indicates the browser's preferred language, and the server can return web pages in different languages accordingly;
  • Accept encoding: indicates the compression type that the browser can support, such as gzip, deflate, etc.

The difference between GET request and POST request:

  1. The GET request parameter is in the request line and there is no request body. The POST request parameter is in the request body
  2. GET request parameters have size restrictions, but POST does not
Response data format

The response data is divided into three parts:

  • Response line: the first line of response data. Where HTTP/1.1 represents the protocol version, 200 represents the response status code, and OK represents the status code description
  • Response header: starting from the second line, in the form of key: value
  • Response body: the last part stores the response data

Common HTTP response headers:

  • Content type: indicates the type of the response content, such as text/html, image/jpeg;
  • Content length: indicates the length of the response content (number of bytes);
  • Content encoding: indicates the response compression algorithm, such as gzip;
  • Cache control: indicates how the client should cache. For example, Max age = 300 indicates that it can cache for up to 300 seconds.
Status code category
Status code classificationexplain
1xxIn response - temporary status code, indicating that the request has been accepted, telling the client that it should continue the request or ignore it if it has been completed
2xxSuccess - indicates that the request has been successfully received and the processing has been completed
3xxRedirect -- redirect elsewhere: he asks the client to make another request to complete the whole process
4xxClient error - the responsibility for processing errors lies with the client, such as the client's request for a nonexistent resource, the client is not authorized, access is prohibited, etc
5xxServer side error - the server is responsible for handling errors, such as throwing exceptions on the server side, routing errors, http version not supported, etc

Common response status codes

Status codeEnglish descriptionexplain
200OKIf the client request is successful, the processing is successful. This is the status code we most want to see
302FoundIndicates that the requested resource has been moved to the URL given by the location response header, and the browser will automatically revisit this page
304Not ModifiedTell the client that the server has not changed the requested resources since the last acquisition. You can directly use your local cache. Implicit redirection
400Bad RequestThe client request has syntax error and cannot be understood by the server
403ForbiddenThe server receives the request but refuses to provide services. For example, it does not have permission to access relevant resources
404Not FoundThe requested resource does not exist. Generally, the URL is entered incorrectly, or the website resource is deleted
428Precondition RequestThe server requires a conditional request and tells the client that it must carry a specific request header in order to access the resource
429Too Many RequestIf there are too many requests, you can limit the number of resources requested by the client, which can be used together with the retry after response header
431Request Header Fields Too LargeThe request header is too large and the server is unwilling to process the request because its header field is too large. The request can be resubmitted after reducing the size of the request header field
405Method Not AllowedThe request method is incorrect. For example, the resource that should use the GET request method uses POST
500Internal Server ErrorAn unexpected error occurred on the server
503Service UnavailableThe server is not ready to process requests. The server has just started and has not been initialized yet
511Network Authentication RequiredThe client needs authentication to gain network access

Servlet

  • Servlet is a dynamic web resource development technology provided by Java
  • Servlet is one of the Java EE specifications. In fact, it is an interface. In the future, we need to define a servlet class to implement the servlet interface, and run the servlet by the web server
quick get start
  1. Create a web project and import Servlet dependent coordinates

    <dependency>
    	<groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    
  2. Create: define a class, implement the Servlet interface, and rewrite all methods in the interface

    public class ServletDemo1 implements Servlet{
        public void service(){
            
        };
    }
    
  3. Configuration: use @ WebServlet annotation on the class to configure the access path of the Servlet

    @WebServlet("/demo1")
    public class ServeltDemo1 implements Servlet{
        
    }
    
  4. Access: start Tomcat and enter the URL to access the Servlet

    http://localhost:8080/web-demo/demo1
    
Servlet execution process

  1. Who created the Servlet? Who calls the Servlet method?

    The Servlet is created by the web server, and the Servlet method is called by the web server.

  2. How does the server know that there must be a service method in the servlet?

    Because our custom Servlet must implement the Servlet interface and copy its methods, and the service method is in the Servlet interface

Servlet lifecycle

Servlet runs in the servlet container (web server), and its life cycle is managed by the container, which is divided into four stages:

  1. Loading and instantiation: by default, when the Servlet is accessed for the first time, the Servlet object is created by the container

    @WebServlet(urlPatterns = "/demo", loadOnStartup = 1)
    /*
    	Set the loadOnStartup parameter to change the creation time of the Servlet object
    		- Negative integer: the Servlet object is created when it is accessed for the first time. The default value is
    		- 0 Or positive integer: the Servlet object is created when the server starts. The smaller the number, the higher the priority
    */
    
  2. Initialization: after the Servlet is instantiated, the Servlet container will call the init() method of the Servlet to initialize the object and complete some initialization work, such as loading configuration files and creating connections. This method is called only once

  3. Request processing: every time a Servlet is requested, the Servlet container will call the service() method of the Servlet to process the request

  4. Service termination: when the memory needs to be released or the container is closed, the container will call the destroy() method of the Servlet instance to release the resources. When the destroy() method is called, the container will release the Servlet instance, which will then be recycled by the Java garbage collector

Introduction to Servlet method
  • The initialization method is executed only once when the Servlet is created

    void init(ServletConfig config)
    
  • Provide a service method, which will be called every time the Servlet is accessed

    void service(ServletRequest req, ServletResponse res)
    
  • Destroy method, which is called when the Servlet is destroyed. Destroy the Servlet when memory is released or the server is shut down

    void destroy()
    
  • Get ServletConfig object

    ServletConfig getServletConfig()
    
  • Get Servlet information

    String getServletInfo()
    
Servlet architecture

We will develop web projects with B/S architecture in the future, which are all aimed at HTTP protocol, so we customize the Servlet and inherit HttpServlet.

@WebServlet("/demo")
public class ServletDemo extends HttpServlet{
    @override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        System.out.println("get...");
    }
}

	@override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        System.out.println("post...");
    }
}

General Servlet classes need to process requests separately in the service() method according to different request methods (because the parameter positions of different request methods are different).

@override
public void service(ServletRequest req, ServletResponse resp)throws ServletException, IOException(){
    // According to different request modes, processing is carried out separately
    // The ServeletRequest object needs to be forcibly converted to an HttpServletRequest object in order to obtain the request method
    HttpServletRequest request = (HttpServletRequest) req;
    
    // 1. Acquisition request method
    String method = request.getMethod();
    // 2. Judgment
    if("GET".equals(method)){
        // Request logic of get mode
        
    }else if("POST".equals(method)){
        // Request logic in post mode
    }
}

The HttpServlet class encapsulates the above code. We don't need to write code to judge the request mode. We just need to rewrite the doGet() method and doPost() method.

Servlet urlPattern configuration

If a Servlet wants to be accessed, its access path (urlParttern) must be configured

  1. Multiple urlpatterns can be configured with one Servlet

    @WebServlet(urlPatterns = {"/demo1",{"/demo2"}})
    
  2. urlPattern configuration rule

    1. Exact match

      Configuration path:@WebServlet("/user/select")
          
      Access path: localhost:8080/web-demo/user/select
      
    2. Directory matching

      Configuration path:@WebServlet("/user/*")
          
      Access path: localhost:8080/web-demo/user/aaa
      		localhost:8080/web-demo/user/bbb
      
    3. Extension matching

      Configuration path:@WebServlet("*.do")
      
      Access path: localhost:8080/web-demo/aaa.do
      		localhost:8080/web-demo/bbb.do
      
    4. Arbitrary matching

      Configuration path:@WebServlet("/")
      		@WebServlet("/*")
      
      Access path: localhost:8080/web-demo/hello
      		localhost:8080/web-demo/aaa
                  
      / and /* Differences between:
      	- When in our project Servlet Configured"/",It will be covered Tomcat Medium DefaultServlet,When others url-pattern When they don't match, they will go this way Servlet,So don't use this generally
      	- When our project is configured with"/*",Means matching any access path
      

    Priority: exact path > directory path > extension path > / * >/

Write Servlet in XML configuration mode

After servlet version 3.0, annotation @ WebServlet configuration is supported. Before version 3.0, only XML configuration file is supported

Steps:

  1. Writing Servlet classes
  2. On the web Configure the Servlet in XML
<!-- to configure Servlet Full class name: servlet-class -->
<servlet>
	<servlet-name>demo</servlet-name>
    <servlet-class>com.itheima.web.servlet.ServletDemo</servlet-class>
</servlet>
<!-- Configure access path -->
<servlet-mapping>
	<servlet-name>demo</servlet-name>
    <url-pattern>/demo</url-pattern>
</servlet-mapping>

Request & Response

  • Request: get request data
  • Response: set response parameters

Request inheritance system

  1. Tomcat needs to parse the request data, encapsulate it as a request object, and create a request object to pass to the service method
  2. Use the request object to consult the HttpServletRequest interface of the Java EE API document.
Request get request parameters

The request data is divided into three parts:

  • Request line:

    GET/request-demo/req1?username=zhangsan HTTP/1.1
    

    request object method:

    String getMethod();		// Get request method
    String getContextPath();	// Get virtual directory (project access path): request demo
    StringBuffer getRequestURL();	// Get URL (uniform resource locator): http://localhost:8080/request-demo/req1
    String getRequestURI();		// Get URL (Uniform Resource Identifier): / request demo / req1
    String getQueryString();	// GET request parameters (GET method): username = Zhangsan & password = 123
    
  • Request header

    User-Agent:Mozilla/5.0 Chrome/91.0.4472.106
    

    request object method:

    String getHander(String name);	// Get value based on request header name
    
  • Request body

    username=zhangsan&password=123
    

    request object method

    ServletInputStream getInputStream();	// Get byte input stream
    BufferReader getReader();	// Get the character input stream, and get the request parameters in post mode
    

GET and POST are common ways to obtain request parameters:

Request will encapsulate the obtained request parameters into a * * map < string, string [] > * * set

  1. Get the map collection of all parameters

    Map<String, String[]> getParameterMap();	//Get all parameter map sets
    
  2. Get the parameter value according to the key and the array

    String[] getParameterValues(String name);	// Get parameter value (array) according to key name
    
  3. Get a single parameter value according to the key

    String getParameter(String name);	// Get parameter value according to key name (single value)
    

In the actual development, this general method can be used to simplify the code and let the doPost() method directly call the doGet() method to obtain the request parameters. In fact, in the bottom layer, these general methods still choose to call getQueryString() and getReader() to complete parameter acquisition according to the specific request mode.

Solve the problem of garbled code when the request parameter is Chinese

  • post method: the getReader() method is used to obtain the character input stream when obtaining the request parameters, so we need to set the encoding of the character input stream

    request.setCharacterEncoding('UTF-8');
    
  • get method: use the getQueryString() method to directly obtain the string to obtain the request parameters. The browser URL does not support Chinese, so the Chinese browser in the request parameters will encode the URL in utf-8, and then send it to the Tomcat server for decoding. Therefore, we need to set the decoding method of Tomcat URL encoding to uft-8

    • URL encoding
      • Converts a string to binary by encoding
      • Each byte is converted to 2 hexadecimal numbers and preceded by%

    We can convert the garbled data generated by Tomcat into byte data and convert it into utf-8 format

    // Get request parameters
    String username = request.getParameter("username");
    // Convert to byte data
    byte[] bytes = username.getBytes("ISO-8859-1");
    // Convert byte data to string
    username = new String(bytes, "utf-8");
    

Note: after Tomcat 8.0, the problem of garbled get request has been solved, and the default decoding method is set to utf-8.

Request forwarding

Forward: a method of resource jump inside the server

Resource A processes part of it and then forwards it to resource B for further processing

Implementation method:

request.getRequestDispatcher("resources B route").forward(request,response);

Request to forward shared data between resources: use the request object

void setAttribute(String name, Object obj);		// Store data in the request field
Object getAttribute(String name);	// Get the value according to the key
void removeAttribute(String name);		// Delete the key value pair according to the key

Request forwarding features:

  • The browser address bar path does not change
  • It can only be forwarded to the internal resources of the current server
  • For one request, you can use request to share data among the forwarded resources
Response setting response data function introduction

The response data is divided into three parts:

  1. Response line:

    HTTP/1.2 200 OK
    
    void setStatus(int sc);		// Set response status code
    
  2. Response header:

    Content-Type:text/html
    
    void setHeader(String name, String value);	// Set response header key value pair
    
  3. Responder:

    <html><head></head><body></body></html>
    
    PrintWriter getWriter();	// Get character output stream
    ServletOutputStream getOutputStream();	// Get byte output stream
    
Response complete redirection
  • Redirect: a method of resource jump

  • Implementation method:
response.setStatus(302);
response.setHeader("location","resources B Path of");

// Or write it directly in the following way
response.sendRedirect("resources B Path of");

Redirection features:

  • Browser address bar path changes
  • Resources that can be redirected to any location (internal or external to the server)
  • For two requests, the function request cannot be used to share data in multiple resources

Resource path problem

  • Identify who uses the path?

    • Browser usage: need to load virtual directory (project access path)
    • Server use: no need to add virtual directory
  • Get virtual directory dynamically

    String contextPath = request.getContextPath();
    response.sendRedirect(contextPath+"/resp2");
    
Response response character data
  1. Get the character output stream through the Response object

    // Set the encoding of the stream to solve the problem of Chinese garbled code
    response.setContextType("text/html;charset = utf-8");
    PrintWriter writer = resp.getWriter();		// The flow does not need to be closed
    
  2. Write data

    writer.write("Hello");
    

be careful:

  • The flow does not need to be closed. With the end of the response, the response object is destroyed and the server is closed
  • Chinese data garbled: the reason is that the default code of the character output stream obtained through response is ISO-8859-1
Response response byte data
  1. Get byte output stream through Response object

    ServletOutputStream outputStream = resp.getOutputStream();
    
  2. Write data

    outputStraeam.write(Byte data);
    

Example:

// 1. Read the file
FileInputStream fis = new FileInputStream("d://a.jpg");
// 2. Obtain the request byte output stream, which does not need to be closed
ServletOutputStream os = response.getOutputStream();
// 3. Complete the copy of the stream
/* Traditional writing:
    byte[] buff = new byte[1024];
    int len = 0;
    while((len = fis.read(buff))!=-1){
        os.write(buff,0,len);
    }
*/

// Using common IO tool class
IOUtils.copy(fis,os);

fis.close
SqlSessionFactory tool class extraction
// Create SQLSessionFactory object
String resource = "mybatis-config.xml";
InputStream inputStream = Resource.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

Question:

  1. Duplicate code
  2. SQLSessionFactory factory is created only once. Do not create it repeatedly, otherwise it will waste resources

Code optimization:

// Encapsulates a SqlSessionFactoryUtils tool class
public class SqlSessionFactoryUtils{
    private static SqlSessionFactory sqlSessionFactory;

    static{
        // Static code blocks are executed automatically as the class loads, and only once
        try{
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resource.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    
    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

JSP -- Java Server Page

concept

Java Server Pages, java server page. A dynamic web page technology, which can define not only static content such as HTML, JS and CSS, but also dynamic content of Java code. Namely: JSP = HTML + Java

  • Function: simplify development and avoid directly outputting HTML tags in Servlet
JSP quick start
  1. Import JSP coordinates

    <dependency>
    	<groupId>javax.servlet.jsp</groupId>
        <artifictId>jsp-api</artifictId>
        <version>2.2</version>
        <scope>provided</scope>
    </dependency>
    
  2. Create JSP file

  3. Writing HTML tags and Java code

    <body>
        <h1>
            hello jsp~
        </h1>
        <% Stsyem.out.print("jsp hello~");%>
    </body>
    
JSP principle
  • JSP is essentially a Servlet

  • When the JSP is accessed, the JSP container (Tomcat) converts it into a Java file (Servlet), and then the JSP container (Tomcat) compiles it. In fact, the bytecode file is the final service.
JSP script
  • Used to define Java code within JSP pages
  • JSP script classification:
    • <%...% >: the content will be put directly into_ In the jspService() method
    • <% =...% >: the content will be put in out In print(), as out Parameters of print()
    • <%!..%>: The content will be put in_ In addition to the jspService() method, it is directly contained by the class and is generally used to define member variables and member methods
  • JSP disadvantages:
    • Writing is troublesome, especially complex pages
    • Reading trouble
    • High complexity: the operation needs to rely on various environments, such as JRE, JSP container, JavaEE, etc
    • Occupy memory and disk: JSP will be generated automatically java and class file occupies the disk and is running class file occupies memory
    • Debugging difficulty: after an error, you need to find the automatically generated java file for debugging
    • Not conducive to teamwork: front-end personnel can't Java, and back-end personnel can't understand HTML

EL expression

Expression Language, which is used to simplify Java code in JSP pages

  • Main function: obtain data

  • Syntax:

    <!-- Gets the information stored in the domain key by brands Data -->
    ${brands}
    
  • Four domain objects in JavaWeb:

    1. Page: the current page is valid
    2. Request: the current request is valid
    3. Session: the current session is valid
    4. Application: the current application is valid

Note: when obtaining data from EL expression, it will look for the four fields in turn until it is found

JSTL tag
  • JSP standard tag liberty uses tags to replace Java code on JSP pages.

Quick start:

  1. Import coordinates

    <dependency>
    	<groupId>jstl</groupId>
        <artifactId>jstl</artifictId>
        <version>1.2</version>
    </dependency>
    <dependency>
    	<groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>
    
  2. Introduce JSTL tag library on JSP page

    <%@ taglibs prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
  3. use

    <!-- c:if Used to complete logical judgment and replace Java Medium is-else -->
    <c:if test="true">
    	<h1>true</h1>
    </c:if>
    
    <c:if test="false">
    	<h1>false</h1>
    </c:if>
    
    <!-- example -->
    <c:if test="${status == 1}">
    	<h1>Enable</h1>
    </c:if>
    <c:if test="${status == 0}">
    	<h1>Disable</h1>
    </c:if>
    
    <!-- c:forEach amount to java Medium for loop
    		- items:Traversed container
    		- var:Temporary variables generated by each traversal
    		- varStatus:Traversing state objects, status.index Starting from 0, status.count Start with 1
    -->
    <c:forEach items="${brands}" var="brand" varStatus="status">
    	<tr align="center">
            <!-- Notice what's written here id Is the attribute name
    			EL Writing this in the expression will automatically call the corresponding function of the object get Method to get properties
    		-->
        	<!--<tb>${brand.id}</tb>-->
            <tb>${status.count}</tb>-
            <tb>${brand.brandName}</tb>
            <tb>${brand.companyName}</tb>
            <tb>${brand.description}</tb>
        </tr>
    </c:forEach>
    
    <!-- ordinary for loop -->
    <c:forEach begin="0" end="10" step="1" var="i">
    	${i}
    </c:forEach>
    
MVC mode and three-tier architecture
  • MVC mode is a layered development mode, in which
    • M: Model, business model, processing business
    • 5: V iew, View, interface display
    • C: Controller, controller, processing requests, invoking models and views

  • MVC benefits:
    • Single responsibility without mutual influence
    • Conducive to division of labor and cooperation
    • Conducive to component reuse
  • Three tier architecture
    • Data access layer: basic CRUD operations on the database
    • Business logic layer: encapsulate the business logic and combine the basic functions in the data access layer to form complex business logic functions
    • Presentation layer: receive the request, encapsulate the data, call the business logic layer and respond to the data

Session tracking technology -- cookie & session

  • Session: the user opens the browser and accesses the resources of the web server. The session is established until one party disconnects and the session ends. Multiple requests and responses can be included in a session.

  • Session tracking: a method to maintain the state of the browser. The server needs to identify whether multiple requests come from the same browser in order to share data among multiple requests in the same session

  • HTTP protocol is stateless. Every time the browser requests from the server, the server will treat the request as a new request. Therefore, we need session tracking technology to realize intra session data sharing.

  • Implementation method:

    1. Client session tracking technology: Cookie
    2. Server Session tracking technology: Session

Basic use of cookies

Cookie: client session technology, which saves data to the client and carries cookie data for access every request in the future

Basic use of cookies

  1. Create Cookie object and set data

    Cookie cookie = new Cookie("key","value");
    
  2. Send Cookie to client: use response object

    response.addCookie(cookie);
    
  3. Get all cookies carried by the client: use the request object

    Cookie[] cookies = request.getCookies();
    
  4. Traverse the array and get each Cookie object: for

  5. Get data using Cookie object method

    cookie.getName();
    cookie.getValue();
    
Cookie principle
  • The implementation of Cookie is based on http protocol
    • Response header: set cookie (send cookie)
    • Request header: Cookie (get cookie)

Cookie usage details
  • Cookie lifetime

    • By default, cookies are stored in the browser memory. When the browser is closed and the memory is released, the cookies are destroyed
    • setMaxAge(int seconds): sets the Cookie lifetime
      • Positive number: the Cookie is written into the hard disk of the computer where the browser is located, stored persistently, and automatically deleted at the time
      • Negative number: the default value is that the Cookie is in the memory of the current browser. When the browser is closed, the Cookie will be destroyed
      • Zero: delete the corresponding Cookie
  • Cookie s store Chinese

    • Cookie s cannot store Chinese by default

    • Solution: URL encoding

      URLEncoder.encode(value, "utf-8");	// code
      URLDecoder.decode(value, "utf-8");	// decode
      
Session basic usage
  • Server session tracking technology: save data to the server
  • Java EE provides HttpSession interface to realize the data sharing function between multiple requests of a session

  • use

    1. Get Session object

      HttpSession session = request.getSession();
      
    2. Session object function

      void setAttribute(String name, Object o);	// Store data in the session domain
      Object getAttribute(String name);	// Get value according to key
      void removeAttribute(String name);	// Delete the key value pair according to the key
      
Session principle
  • Session is implemented based on cookies
    • Tomcat will send the Session id to the browser as a Cookie data by default

Session usage details
  • Session passivation and activation

    • Is the data still in the Session after the server is restarted? The answer is: in
    • Passivation: after the server is shut down normally, Tomcat will automatically write the Session data to the file on the hard disk
    • Activation: after starting the server again, load data from the file into the Session
    • Note: when the browser closes once, the Session ends, and you can't get the same Session object again after restarting
  • Session destroy

    • By default, there is no operation and it will be automatically destroyed in 30 minutes

      <session-config>
      	<session-timeout>30</session-timeout>
      </session-config>
      
    • Call the invalidate() method of the Session object to destroy it manually

Comparison between Cookie and Session
  • Cookie s and sessions are used to share data between multiple requests in a Session
  • difference:
    • Storage location: a Cookie stores data on the client and a Session stores data on the server
    • Security: the Cookie is not secure, and the Session is secure
    • Data size: the maximum size of the Cookie is 3KB, and the Session has no size limit
    • Storage time: cookies can be stored for a long time. The default Session is 30 minutes
    • Server performance: cookies do not occupy server resources, and Session occupies server resources
Case: user login and registration
  • User login

    • Three tier architecture

    • Detailed code
  • Remember users

    • If the user checks "remember user", the user name and password will be automatically filled in the next visit to the login page

    • How to automatically fill in user name and password?

      1. Write the user name and password into the Cookie, and store the Cookie persistently. The next time you visit the browser, you will automatically carry the Cookie

      2. After obtaining the Cookie data on the page, set it to the user name and password box

        ${cookie.key.value}		<!-- key Means stored in cookie The name of the key in the -->
        
    • When to write cookies?

      1. Login successful
      2. Users check the remember users check box

  • User registration

    • Registration function: save user information to the database

    • Verification code function:
      • Display verification code: display the verification code picture. You can click to switch the picture
        • The verification code is a picture generated using Java code
        • Function of verification code: prevent the machine from automatically registering and attacking the server
      • Verification Code: if the verification code is not filled in correctly, the registration fails

Filter

concept
  • Filter refers to filter, which is one of the three major components of Java Web (Servlet, filter and Listener).
  • The filter can intercept requests for resources, so as to realize some special functions.
  • Filters generally complete some general operations, such as permission control, unified coding processing, sensitive character processing, etc

Filter quick start
  1. Define the class, implement the Filter interface, and override all its methods

    public class FilterDemo implements Filter{
        public void init(FilterConfig filterConfig) throw ServletException{
            
        }
        public void doFilter(ServletRequest request, ServletResponse response) throw IOException{
            
        }
        public void destroy(){
            
        }
    }
    
  2. Configure the path of Filter intercepting resources: define @ WebFilter annotation on the class

    @WebFilter("/*")
    public class FilterDemo implements Filter{
        ......
    }
    
  3. Output a sentence in the doFilter method and release it

    public void doFilter(ServletRequest request, ServletResponse response)throw IOException{
        // 1. Process the request data before release
        System.out.println("filter Before release");
        
        // 2. Release, access resources... response carries data
        chain.doFilter(request,response);
        
        // 3. Process the response data after release
        System.out.println("filter After release");
    }
    
Filter execution process

After the release, the corresponding resource is accessed. After the resource access is completed, it will return to the Filter and execute the logic after the release. That is: execute pre release logic → release → access resources → execute post release logic

Filter usage details
  • Filter intercept path configuration

    Filter can configure different interception resource paths according to requirements, using the annotation: @ WebFilter("path")

    • Intercept specific resources: / index Jsp: only access index JSP
    • Directory interception: / user / *: all resources accessed under / user will be intercepted
    • Block all: / *: access to all resources will be blocked
  • Filter chain

    • A Web application can be configured with multiple filters, which are called filter chains
    • For the Filter configured by annotation, the execution priority is naturally sorted according to the Filter class name (string)

Case: login verification
  • Requirements: when accessing server resources, you need to verify the login first. If you don't log in, you will automatically jump to the login page

Listener

concept
  • Listener refers to listener, which is one of the three major components of Java Web (Servlet, Filter and listener)

  • Listener is a functional component that automatically executes code when three objects, application, session and request, are created, destroyed or properties are added, modified or deleted

  • Listener classification: eight listeners are provided in Java Web

Listener classificationListener nameeffect
ServletContext listeningServletContextListenerUsed to listen to (create and destroy) ServletContext objects
ServletContextAttributeListenerListening to attributes in ServletContext object (adding, deleting and modifying attributes)
Session listeningHttpSessionListenerListening to the overall state of the Session object (create, destroy)
HttpSessionAttributeListenerListen to the attributes in the Session object (add, delete and modify attributes)
HttpSessionBindingListenerBinding and releasing of listening object to Session
HttpSessionActivationListenerMonitoring of passivation and activation of Session data
Request listeningServletRequestListenerListen to the Request object (create, destroy)
ServletRequestAttributeListenerListening to attributes in Request object (adding, deleting and modifying attributes)
ServletContextListener uses
  1. Define a class to implement the ServletContextListener interface

  2. Add @ WebListener annotation on class

    @WebListener
    public class ContextLoaderListener implements ServletContextListener{
        public void contextInitialized(ServeltContextEvent sce){
            // load resources
            System.out.println("ContextLoaderListener...");
        }
        
        public void contextDestroyed(ServletContextEvent sce){
            // Release resources
        }
    }
    

Ajax

concept
  • AJAX (Asynchronous JavaScript And XML): Asynchronous JavaScript And XML
effect
  1. Data exchange with the server: through Ajax, you can send requests to the server and obtain the data responded by the server

    • Using Ajax to communicate with the server, you can use HTML + Ajax to replace JSP pages

  2. Asynchronous interaction: the technology that can exchange data with the server and update some web pages without reloading the whole page, such as search Association, user name availability verification, etc

Asynchronous and synchronous

Ajax quick start
  1. Write an Ajax servlet and use response to output a string

  2. Create XMLHttpRequest object: used to exchange data with the server

    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
  3. Send request to server

    xmlhttp.open("GET","url");
    xmlhttp.send();		// Send request
    
  4. Get server response data

    /*
    	readyState Saved the status of XMLHttpRequest
    	- 0:Request not initialized
    	- 1:Server connection established
    	- 2:Request received
    	- 3:Processing request
    	- 4:Request completed and response ready
    	
    	status
    	- 200:"OK"
    	- 403:"Forbidden"
    	- 404:"Page not found"
    	
    	statusText Returns the status text (for example, "OK" or "Not Found")
    */
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            alert(xmlhttp.responseText);
        }
    }
    
Case: verify whether the user name exists
  • Requirement: when completing user registration, when the user name input box loses focus, verify whether the user name already exists in the database

Axios asynchronous framework
  • Axios encapsulates native Ajax to simplify writing

  • Official website: http://www.axios-http.cn

  • Axois quick start:

    1. Introduce the js file of axios

      <script src="js/axios-0.18.0.js"></script>
      
    2. Send the request using axios and get the response result

      axios({
          method:"get",
          url:"http://localhost:8080/ajax-demo/aJAXDemo?username=zhangsan"
      }).then(function(resp){
          alert(resp.data);
      })
      
      axios({
          method:"post",
          url:"http://localhost:8080/ajax-demo/aJAXDemo",
          data:"username=zhangsan"
      }).then(function(resp){
          alert(resp.data);
      })
      
JSON
concept
  • JavaScript Object Notation. JavaScript object representation
  • Because of its simple syntax and distinct hierarchical structure, it is now mostly used as a data carrier for data transmission in the network
JSON basic syntax

definition

var Variable name = {
    "key1":value1,
    "key2":value2,
   	...
    "name":"zhnagsan",
    "age":23,
    "addr":["Beijing","Shanghai","Xi'an"]
};

/*
	value The data types are:
		- Number (integer or floating point number)
		- String (in double quotes)
		- Logical value (true or false)
		- Array (in square brackets)
		- Object (in curly braces)
		- null
*/

Get data:

Variable name.key
JSON data and Java object conversion
  • Fastjson is a high-performance and fully functional JSON library written in Java language provided by Alibaba. It is the fastest JSON Library in Java language at present, which can realize the mutual conversion of Java objects and JSON strings.
  • Request data: convert JSON string to Java object
  • Response data: convert Java object to JSON string

  • use:

    1. Import coordinates

      <dependency>
      	<groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <versoin>1.2.62</versoin>
      </dependency>
      
    2. Java object to JSON

      String jsonStr = JSON.toJSONString(obj);
      
    3. JSON string to Java object

      User user = JSON.parseObject(jsonStr, User.class);
      

Note: request. Can't be used to get JSON data Getparameter(), but use request getReader(). Readline(), and then use parseObject(param, class name. calss) to convert the obtained JSON characters into corresponding Java objects.

Vue

  • Vue is a front-end framework that eliminates DOM operations in native JavaScript and simplifies writing
  • Based on the idea of MVVM (model view ViewModel), realize the two-way binding of data, and focus the programming on

Vue quick start
  1. Create a new HTML page and introduce Vue JS file

    <script src="js/vue.js"></script>
    
  2. In the JS code area, create Vue core objects for data binding

    new Vue({
        // el: binding Vue to element through selector
        el:"#app",
        data(){
            return{
                username:""
            }
        }
    });
    
  3. Authoring views

    <div id="app">
        <!-- v-model And the front Vue The name of the model written in it is the same -->
        <input name="username" v-model="username">
        <!-- {{Difference expression}} -->
        {{username}}
    </div>
    
Vue common instructions
  • Instructions: special attributes with v-prefix on HTML tags. Different instructions have different meanings. For example: v-if, v-for, etc

  • Common instructions

    instructionseffect
    v-bindBind attribute values for HTML tags, such as setting href, css style, etc. Simplified write only:, for example: href = ""
    v-modelCreate a two-way data binding on a form element
    v-onBind events for HTML tags, simplify writing @, such as @ click = ""
    v-if
    v-elseConditional rendering elements are rendered when they are judged to be true, otherwise they will not be rendered
    v-else-if
    v-showDisplaying an element according to conditions is different from v-if in that it switches the value of the display attribute
    v-forList rendering, traversing the elements of the container or the attributes of the object
    • v-for example

      <div v-for="addr in addrs">
          {{addr}}<br>
      </div>
      <!-- Caucasian citation -->
      <div v-for="(addr,i) in addrs">
          <!-- i Indicates the index, starting from 0 -->
          {{i+1}}--{{addr}}<br>
      </div>
      
Vue lifecycle
  • Eight stages of life cycle: each time a life cycle event is triggered, a life cycle method (hook) will be automatically executed
statePhase cycle
beforeCreateBefore creation
createdAfter creation
beforeMountBefore loading
mountedMount complete
beforeUpdateBefore update
updatedAfter update
beforeDestroyBefore destruction
destroyedAfter destruction

  • mounted: mount is completed, Vue initialization is successful, and HTML page rendering is successful.
    • Send asynchronous request and load data

Element

  • Element: is it hungry? A set of Vue based website component library provided by the front-end development team of the company is used to quickly build web pages
  • Components: components that make up a web page, such as hyperlinks, buttons, pictures, tables, etc
quick get start
  1. Introduce css, JS file and Vue. Exe of Element js

    <script src="vue.js"></script>
    <script src="element-ui/lib/index.js"></script>
    <link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
    
  2. Create Vue core object

    <script>
    	new Vue({
            el:"#app"
        })
    </script>
    
  3. Go to the official website to copy the required component code

Element layout
  • Element has two layout methods:

    • Layout: create layout quickly and easily through 24 columns of the foundation

    • Container layout container: a container component used for layout, which is convenient to quickly build the basic structure of the page

Servlet code optimization

  • There are too many servlets in the Web layer, which is not conducive to management and writing
  • Classify servlets and write the operation methods of the same entity into a Servlet. For example: BrandServlet, UserServlet

Customize the Servlet, use the request path for method distribution, and replace the HttpServlet for method distribution according to the request method.

/*
	Replace HttpServlet and distribute the method according to the last path of the request
*/
public class BaseServlet extends HttpServlet{
    // The method is distributed according to the last path of the request
    @override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //1. Get request path
        String uri = req.getRequesetURI();	// /brand-case/brand/selectAll
        //Get the last path, that is, the method name
        int index = uri.lastIndexOf('/');
        String methodName = uri.substring(index + 1);
        
        //2. Implementation method
        //2.1 get BrandServlet bytecode object Class
        //Who calls me (the method where this is located) and who I (this) represent
        Class<? extends BaseServlet> cls = this.getClass();
        //2.2 get Method object
        try{
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //2.3 execution method
            method.invoke(this, req, resp);
        }catch(NoSuchMethodException e){
            e.printStackTrace();
        }catch(IllegalAccessException e){
            e.printStackTrace();
        }catch(InvocationTargetException e){
            e.printStackTrace();
        }
    }
}

Keywords: Java servlet server

Added by running_out_of_imagination on Sun, 27 Feb 2022 10:18:05 +0200