Introduction of the Servlet

Servlets are Java classes in essence. Writing servlets requires following the basic Syntax of Java. However, unlike ordinary Java classes, servlets are Java classes that can only run on the server side and must follow special specifications. These features are unique to servlets and have their own life cycle during runtime. In addition, Servlet is closely related to HTTP protocol, so it can handle almost all aspects of HTTP protocol, which is the biggest reason why Servlet is favored by developers.

How servlets work

Servlets need to run in a specific container. The container here refers to the runtime environment required by the Servlet. Generally, the common Java Web Server in the market can support servlets. For example, Tomcat, Resin, Weblogic, WebSphere, etc., Tomcat is used as the container of Servlet in this book, and Tomcat provides the basic running environment for Servlet.

The Servlet container environment implements an abstraction layer between HTTP communication and the Web server platform. The Servlet container is responsible for passing the request to the Servlet and returning the result to the client. The container environment also provides a simple way to configure Servlet applications and also provides a way to configure servlets using XML files. When the Servlet container receives a request from the user to the Servlet, the Servlet engine determines whether the Servlet has been accessed for the first time. If so, the Servlet engine initializes the Servlet. That is, the init () method in the Servlet is called to do the necessary initialization. When a subsequent client requests the Servlet service, the init () method is not called, but the service () method is directly called. In other words, each Servlet is initialized only once. The subsequent request simply creates a new thread and calls the service () method in the Servlet.

In the process of using Servlet, the problem of concurrent access is handled by the Servlet container. When multiple users request the same Servlet, the Servlet container is responsible for starting a thread for each user, and the operation and destruction of these threads are responsible for the Servlet container. In traditional CGI programs, which start a process for each user, servlets are much more efficient than CGI programs.

Servlet life cycle

Servlet is a program running on the server side, so the running state of Servlet is completely maintained by the Servlet container, and the life cycle of a Servlet generally has three processes.

1. Initialize the

When a Servlet is first requested, the Servlet engine initializes the Servlet, in this case by calling the init () method to do the necessary initialization. Moreover, this object is consistently active in memory, and the Servlet creates a new thread for subsequent customer requests by directly calling the service () method in the Servlet without initializing the Servlet.

2. To provide services

Once the Servlet object is created, the concrete service () method can be invoked to serve the user.

3. The destruction

After the Servlet is initialized, it is kept in memory for subsequent access without initialization. When the server encounters a problem and needs to be restarted, these objects need to be destroyed. The Servlet engine calls the Servlet destroy () method to destroy the Servlet object in memory.

Servlet complete example

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/helloServlet") // Request path, this is annotation development, so that you don't need to write the servlet-mapping in web.xml
public class HelloServlet extends HttpServlet {
    @Override
    public void init(a) throws ServletException {
        System.out.println("HelloServlet initialization");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet doGet handles GET requests");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet doPost Handles POST requests");
    }
    @Override
    public void destroy(a) {
        System.out.println("HelloServlet destroyed"); }}Copy the code

Difference between doGet and doPost

Common way

Get: Enter the URL or hyperlink in the URL address bar. If method in the form is SET to GET or method in the form is empty, get is submitted by default. Post: The method attribute in the form is POST.

Data transmission mode

Get: Form data is stored after the URL address. There is no body in HTTP for all GET submissions. Post: Form data is stored in the HTTP message body and sent to the server as an entity.

How the server obtains data

GET: The server uses Request.QueryString to obtain the value of a variable. POST: The server uses request.Form to obtain data.

The amount of data transferred

GET: the length of the data is limited, usually not more than 2kb. Because it is passed as a parameter and is in the address bar, the amount of data is limited. POST mode: Suitable for large-scale data transmission. Because it’s delivered physically.

security

GET mode: Poor security. Because the data is displayed directly in the address bar, the browser has a buffer to record user information. So the security is low. POST mode: High security. Because the HTTP POST mechanism is used to submit data through POST, the fields and values in the form are placed in the HTTP HEADER and sent together to the URL indicated by the ACTION, which is invisible to the user.

When the user refreshes

In GET mode, no prompt is displayed. In POST mode, a prompt box is displayed asking the user whether to resubmit the file

Servlet sends requests

The most common operation with servlets is that the page passes values to the background, the background receives and processes the background, and returns the execution results to the front end. The method of receiving the value requested by the front end is req.getParameter(” The name of the input box name “); Example: Let’s pass the username and password from the front end to the back end, verify that they are correct, and output the result to the console. The front-end input corresponding values, you can test the results.

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get the user name
        String userName = req.getParameter("userName");
        // Get the password
        String userPassword = req.getParameter("userPassword");
        if (userName.equals("admin") && userPassword.equals("123456")) {
            System.out.println("Verified");
        } else {
            System.out.println("Verification failed"); }}}Copy the code
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>
<body>
<form action="/login" method="post"> User name: <input type="text" name="userName"/><br> Password: <input type="password" name="userPassword" /><br>
    <input type="submit" value="Submit" />
</form>
</body>
</html>
Copy the code

Servlet response data

We modify the previous example by telling the front-end user the result of the response, usually through req.setAttribute(” message name, “” message content”); The page then uses ${message name} to get the value.

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get the user name
        String userName = req.getParameter("userName");
        // Get the password
        String userPassword = req.getParameter("userPassword");
        if (userName.equals("admin") && userPassword.equals("123456")) {
            // Save the result to the request
            req.setAttribute("message"."Verified");
        } else {
            // Save the result to the request
            req.setAttribute("message"."Verification failed");
        }
        / / to
        req.getRequestDispatcher("index.jsp").forward(req, resp); }}Copy the code
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>
<body>
${message}
<form action="/login" method="post"> User name: <input type="text" name="userName"/><br> Password: <input type="password" name="userPassword" /><br>
    <input type="submit" value="Submit" />
</form>
</body>
</html>
Copy the code

I entered the user name admin and password 123456. The test result is as follows:

Servlet redirection and forwarding

In servlets, there are two ways to jump to a page, redirection and forwarding.

The difference between a

When redirected, the url on the browser changes. Forwarding is the same url on the browser

The difference between the two

A redirection actually generates two requests and forwards only one request

The difference between the three

The redirected url can be any url. The redirected URL must be the url of this site

redirect

Send a request – > The server runs – > Responds to the request and returns a new address and response code to the browser. – > The browser determines that the response is redirected based on the response code and automatically sends a new request to the server. – > The server runs – > Responds to the request

Forwarding:

Send a request – > Run the server – > reconfigure the request, for example, using request.setAttribute(name,value) – > Obtain the web page based on the forwarded address – > respond to the request to the browser

Break down

Redirect: All variables stored in the previous request are invalidated and a new request scope is entered. Forwarding: Variables stored in previous requests are not invalidated, like putting two pages together.

Write the difference between

req.getRequestDispatcher("index.jsp").forward(req, resp); / / forwarding
resp.sendRedirect("index.jsp"); / / redirection
Copy the code

Servlet annotation development

Traditional configuration of servlets

In JavaWeb development, each time you write a Servlet, you need to configure it in a web.xml file, as follows:

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.sponge.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>
Copy the code

Servlet3.0 provides annotations that eliminate the need to describe Servlet deployment in a web.xml file. Simplify the development process.

Annotation-based configuration of servlets

The same effect can be achieved by writing the following annotation directly above the servlet class name:

@WebServlet("/login")
Copy the code
package com.sponge.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doGet");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("doPost");
    }
Copy the code

}