First, servlet introduction

1. What is a servlet

(1) Servlet (Server Applet), full name of Java Servlet. It is a server-side program written in Java. Its main function is to browse and modify data interactively and generate dynamic Web content.

  • Narrowly defined, a Servlet is an interface implemented by the Java language;
  • A Servlet broadly refers to any class that implements the interface of this Servlet, which is generally understood as the latter.

(2) Servlets run in Java-enabled application servers. Implementatively, servlets can respond to any type of request, but most of the time servlets are only used to extend HTTP-based Web servers.

(3) Servlet working mode:

  • ① The client sends a request to the server
  • ② The server starts and invokes the Servlet, which generates the response content according to the client request and sends it to the server
  • ③ The server returns a response to the client

2, the Servlet API

3. The first servlet program

Create the web.testServlet class in the SRC folder

2, create a lib folder in the Web folder and introduce the jar package javaee-apI-7.0.jar that defines servlets and Httpservlets

3. Introduce the JAR package into the program

4. Override doGet and doPost methods in testServlet

5. Associate front-end pages with servlets

6, run

The console displays the request type when a link or button is clicked

Note: If you have run the project, you can jump to the normal page, but when you type FirstHTML. HTML, 404 appears, and when you visit localhost:8080, 404 also appears. You can refer to @hupixiong here [IDEA deployment project to Tomcat run successfully but page 404 two reasons]

The reason is that the access address of Tomcat is inconsistent with the defined Application Context

Added: ak47 schematic item and loot added

Second, servlet details

1. Working principle

(1) The Servlet interface defines the contract between the Servlet and the Servlet container:

  • The Servlet container loads the Servlet class into memory and generates Servlet instances and calls its specific methods.
  • Note, however, that there can only be one instance of each Servlet type in an application. (Singleton mode)

(2) The user request causes the Servlet container to invoke the Servlet’s Service () method

  • Pass in a ServletRequest object and a ServletResponse object. The ServletRequest object and the ServletResponse object are passed in
  • Both are packaged by Servlet containers (such as TomCat) and do not require the programmer to implement them. The programmer can use both objects directly.

(3) The ServletRequest encapsulates the current Http request

  • Developers do not have to parse and manipulate raw Http data.
  • A ServletResponse represents the Http response of the current user, and the programmer can easily send the response back to the user by manipulating the ServletResponse object directly.

(4) For each application, the Servlet container also creates a ServletContext object.

  • This object encapsulates the environment details of the context (application). There is only one ServletContext per application.
  • Each Servlet object also has a ServletConfig object that encapsulates the Servlet configuration.

2. Life cycle

When the client sends the first request for the first time, the container (Web server (Tomcat)) will parse the request, find the corresponding servlet according to the request, and determine whether the object of this class exists. If not, create a servlet instance and call init() method for initialization. After initialization, the service() method is called. The service() method determines the request mode of the client. If it is GET, doGet() is executed, and if it is POST, doPost() is executed. After the processing method is complete, send the corresponding result to the client.

When the user sends a request after the second time, the object is determined to exist, but instead of init(), the service method is executed directly, calling the doGet()/doPost() method.

Call the destroy() method when the server is down.

Four processes:

  • (1) Instantiation — create servlet instances first
  • (2) Initialize –init()
  • (3) Request processing –service()
  • (4) Termination of service — Destory ()

3, add

@姠 unchanging heart growing Notes – How Servlets work and Process

Servlet

  • Servlets are a JavaEE specification designed to extend Java’s capabilities as a Web service.
  • To make it easier for third parties to comply with the specification, Sun (now Oracle) provided a set of related interfaces known as the Servlet API.

The Servlet application

  • Java programs that directly or indirectly implement the Servlet interface and need to run in a Servlet container are mainly used to generate dynamic Web pages.
  • Servlet applications cannot run independently and must be deployed to a Servlet container.

The Servlet container

  • A Servlet container (Servlet engine) is a part of a Web server or application server that provides Web services on top of sent requests and responses, decodes MIME-based requests, and formats MIME-based responses. That is, a Servlet container is used to receive client requests, process protocols, request content, and so on. Initializes the Servlet instance (only the first time) and invokes the corresponding method of the Servlet application, which then returns the processing result, which is returned to the user client by the Servlet container.

The Tomcat container

  • The Tomcat container, also known as the application server, is also called the Servlet container. In essence, the Tomcat container has the function of a Servlet container and is an open source implementation of the Servlet container, but it is not just a Servlet container.

4. Request common methods

HttpServletRequest represents a Servlet request in an Http environment. It is extended from javax.mail. Servlet. ServletRequest interface

No matter what type of data the foreground passes, the background receives it as a String, okay

1. Common methods

1.1 the String getParameter (String name)

Gets the submission data based on the form component name, and returns a String

Note: The server receives data using strings

Write an HTML page that tests GET/POST parameters

Create the UsersServlet class

package com.xrh; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class UsersServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uage = req.getParameter("uage"); String upass = req.getParameter("upass"); System.out.println("[GET] uage: " + uage + ",upass: " + upass); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); System.out.println("[POST] username: " + username); }}Copy the code

3. Configure it in web. XML

4. Running results

Click the hyperlink to trigger the GET request. Enter the content and click Submit to trigger the POST request

5. Handle POST request garbled characters

Void setCharacterEncoding(String Charset) Specifies the encoding for each request (only for POST requests).

6. Why don’t GET requests have garbled characters?

After JDK8, you do not need to manually set the encoding format yourself

1.2 String[] getParameterValues(String name)

Gets request data when a form component corresponds to multiple values

1. Modify the page to add check boxes (the value displayed may not be the same as the value passed to the back end, for example, if basketball is selected, lanQIU is passed)

2, modify UsersServlet

3, run

1.3 RequestDispatcher getRequestDispatcher (String path)

The page is displayed. Returns a RequestDispatcher object whose forward() method is used to forward the request, as shown in this example:

request.getRequestDispatcher(".. /success.jsp").forward(request,response);Copy the code

1, modify doPost

2. Add the Success page

3, run

1.4 save value request. SetAttribute (” key “, value); Values of the request. The getAttribute (” key “); // The value needs to be converted downward

2. How does the client send data to the server

Method one is submit via the get/ POST form

Method 2: Send data via tag A (GET submit)

<a href=" request name? key=value&key=value&key=value..." > Example: <a href="/login? a=10&name=abc&pass=123">Copy the code

Where key = the name of the form element’s control, value = the value of the form’s control property

Note: The first parameter is used? String name=request.getParameter(“name”);

Mode 3 Directly concatenates requests through the address bar – GET

Mode four JS submit data -get request

Location. Href =" Target request? key=value&key=value"Copy the code

Note: Two-thirds of the forms are submitted by GET. Get and POST can be used for form submission

3. Deal with the problem of request garbled characters

SetCharacterEncoding (“UTF-8”); // This works for post submissions

Method 2: String s=new String(variable name. GetBytes (“ISO-8859-1″),”UTF-8”); // Chinese characters are garbled for get submissions. Example:

String s=new String(request.getParameter("key").getBytes("ISO-8859-1"),"GBK");
Copy the code

Method 3: Modify the Tomcat configuration file :// Used for GET submission

Set the character set in the Tomcat directory structure \conf\server.xml

<Connector port="8080" protocol="HTTP/1.1" 
 connectionTimeout="20000"
 redirectPort="8443" URIEncoding="UTF-8" />
Copy the code

Note: manual setting of this property is not required after tomcat8.0

4. the difference between GET and POST

1, GET request, the requested data will be appended to the URL, as? Split URL and transfer data, multiple parameters with & join. The URL encoding format uses ASCII encoding instead of UNIClDE, meaning that all non-ASCII characters are encoded before transmission.

POST request, which places the requested data in the body of the HTTP request package. The item=bandsaw above is the actual transmission data.

Therefore, the data for a GET request is exposed in the address bar, whereas the data for a POST request is not

2. The size of the transmitted data

In the HTTP specification, there are no restrictions on the length of the URL or the size of the data transferred. In real development, however, specific browsers and servers limit the length of urls for GET. Therefore, when using GET requests, the data transferred is limited by the length of the URL.

For POST, because it is not a URL, it is theoretically not restricted. However, in fact, each server sets a limit on the size of data submitted by POST. Apache and IIS have their own configurations.

3. Security

POST is more secure than GET. Security here means real security, unlike the security method mentioned in GET above, which simply does not modify the server’s data. For example, during the login operation, the user name and password will be exposed in the URL through the GET request. Because the login page may be cached by the browser and other people may view the browser history, the user name and password can be easily obtained by others.

In addition, data submitted by GET requests can cause cross-site request Frogery attacks

5, Response common methods

In the Service API, an HttpServletResponse interface is defined, which inherits from the ServletResponse interface and is specifically used to encapsulate HTTP response messages.

The HttpServletResponse interface defines methods for sending a response status code, response header, and response body to the client.

Common methods:

  • void addCookie(Cookie var1); // Add a cookie to the response
  • void sendRedirect(String var1) ; // Send a response code to redirect the browser to the specified location (redirect)
  • PrintWriter getWriter() gets the String stream. The String can be set into the response buffer through the write(String s) method of the String stream. Tomcat then assembles the contents of the response buffer into an Http response and sends it back to the browser.
  • SetContentType () sets the type of the response content

Sixth, forward and redirection

For a more detailed and clear introduction, please refer to here, <( ̄)  ̄)↗[GO! @Zzzer! [Difference and Application of Redirection and Forwarding]

1, introduction,

At present, there are two ways to jump to the page, one is through forwarding req. GetRequestDispatcher of request, the other is through redirecting resp. SendRedirect of response.

Redirect: response. SendRedirect ()

Forwarding: request. GetRequestDispatcher (“.. /success.jsp”).forward(request,response);

2,

Similarities:

  • Are used to jump to the page

Difference:

  • A. During redirection, the address bar will change and the data stored in the request will be lost. When forwarding, the address bar displays the address of the request page, and the request data can be saved.
  • B. Forwarding belongs to one request and one response, and redirection belongs to two requests (the address bar is changed twice) and two responses.
  • Add: Use the out object to output JS or HTML or CSS to the page. Using JS to jump to a page also loses data in the request.

3. Run the example

3.1 Forwarding Mode

1, modify UsersServlet

2. When the program is running, type FirstHTML page

3, click Submit (the address bar does not change, but returns the required page content)

3.2 Redirection Mode

1, modify UsersServlet

2. When the program is running, type FirstHTML page

3. Click Submit

3.3 Drawing summary

Session

1,

Request values can only be saved in a single request and cannot be saved across pages. In case of redirection, request values will be lost.

However, when you visit a large website, such as Xoba, your account information is always there and never lost, no matter which page you go to.

This is where session objects are introduced:

  • Session data can be shared across multiple pages, and data is not lost even if the page is redirected
  • A session can contain n requests.

The concept of a session is as follows: A session is called when you visit the server from opening the browser to closing the browser. A session can contain n requests

2. Common methods

1, void setAttribute(String key,Object value)

The object value is stored in the form of key/value and the data is stored on the server

2, Object getAttribute(String key)

Get the object value by key

3, the void invalidate ()

Invalidating the session object

4, the String getId ()

Obtain the sessionID. After the first login is successful, the session generates a unique ID. If the browser finds that the ID value is the same as the previous ONE, the current session belongs to the same session

5, void setMaxInactiveInterval(int interval)

Set the session inactive time

Example:

Method 1: session. SetMaxInactiveInterval (10 * 60); // Set the validity period to 10 minutes

Method 2: Modify web.xml

<session-config> <session-timeout>10</session-timeout>// unit: minute </session-config>Copy the code

6, int getMaxInactiveInterval ()

Gets the valid inactive time (in seconds) of the session. The default valid time is 30 minutes

7, void removeAttribute(String key)

Deletes the object corresponding to the specified key from the session

8. Summary: Ways to invalidate sessions

  • invalidate()
  • removeAttribute(“key”)
  • Close the browser.

3. Code examples

8. Initialization parameter acquisition

request.setCharacterEncoding(“utf-8”); The coupling degree of the code is too high for later maintenance modification. This can be done by initializing parameters

1. Local initialization parameters

1. First define initialization parameters in web.xml

<servlet>
    <servlet-name></servlet-name>
    <servlet-class></servlet-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</servlet>
Copy the code

2. Get the initialization parameters in the servlet and override init()

public void init(ServletConfig config) throws ServletException {
     encoding= config.getInitParameter("encoding");
}
Copy the code

Note: Initialization parameters in this manner are limited to the current servlet.

2. Global initialization parameters

1. Define that context-param is at the same level as servlet tags

<context-param>
     <param-name>bianma</param-name>
     <param-value>utf-8</param-value>
</context-param>
Copy the code

2. Get the data

@ Override / / request - > init () - > service () - > doget/dopost - > destory (); public void init(ServletConfig config) throws ServletException { bianhao=config.getServletContext().getInitParameter("bianma"); }Copy the code

3. Code examples

1. Modify web.xml. Add UsersServlet local initialization parameters, and global initialization parameters

2. Modify UsersServlet and TestServlet

public class UsersServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException Println (" usersservlet-init ->myparam"+ config.getinitParameter ("myparam")); Println (" usersservlet-init -> allParam "+config.getServletContext().getinitParameter ("encoding")); }}Copy the code

public class TestServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException Println (" testservlet-init ->myparam"+ config.getinitParameter ("myparam")); Println (" testservlet-init ->allparam"+config.getServletContext().getinitParameter ("encoding")); }}Copy the code

3. Run tests

Service 3.0 notes

If you keep inserting tags into web.xml, the file will become very verbose. Hence the introduction of annotations:

  • Comments (information provided to the program to read) – Comments (information provided to the programmer to read)
  • Annotation format :@ beginning with: @override
  • The @webServlet annotation configures the Servlet

Starting with Servlet3.0, configuring servlets supports annotations, but retains the configuration of web.xml. There are two ways to use servlets:

  • The @webServlet annotation is configured on the Servlet class
  • In the web. XML file

1. Common attributes of @webServlet

2. Code examples

1. Create StudentServlet

package web; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; 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(urlPatterns = "/stu/test", name = "myName ", initParams = { @WebInitParam(name="init-stu",value = "myinitparam"), @WebInitParam(name="pwd",value = "123456") }, loadOnStartup = 1 ) public class StudentServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { System.out.println("StudentServlet-init"+config.getInitParameter("init-stu")); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("do-get-StudentServlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); }}Copy the code

2. Enter the address in the address bar

You can see that the program executed correctly

3, note

3.1 loadOnStartup properties

Flags whether the container loads the Servlet when the application is started.

  • If the default value is not configured or the value is negative, the Servlet is loaded when the client requests it for the first time.
  • The value 0 or positive indicates that the application is loaded upon startup. In the positive case, the smaller the value is, the higher the priority of loading the Servlet is.

Example: // The slash must

@WebServlet(value="/test1",loadOnStartup=1)
Copy the code

3.2 name attribute

Can be specified is not specified, through getServletName () can get to, if not specified, the full class name of the Servlet, such as: cn.edu.njit.servlet.UserServlet

3.3 urlPatterns/the value attribute

Type String[]. Multiple mappings can be configured, such as urlPatterns={“/user/test”,”/user/example”}

// The slash must

@WebServlet(loadOnStartup=1,urlPatterns= {"/test1","/test2"})
Copy the code

3.4 When using annotations, note the following:

The attribute metadata-complete=”true” cannot be configured in the root element, otherwise the Servlet cannot be loaded.

  • The metadata-complete attribute tells the Web container whether or not to find an annotation. By default, it does not write or sets false. The container scans the annotation to build valid metadata for the Web application.
  • Metadata-complete =”true”, which does not scan annotations at startup. Configuration with annotations, such as @webservlet, will not take effect without scanning annotations

(5). Common rules of urlPatterns:

  • /* or / : Intercept all
  • *.do: intercepts the specified suffix
  • /user/test: interception path
  • /user/. Do, /. Do, and test*. Do are all invalid, and an error will be reported when starting

The chapter summary is here (the better we understand you guys, the better we understand you guys).

Students who are interested in learning Java are welcome to join QQ Learning exchange group: 1126298731

Have a question welcome to ask, everyone together in learning Java on the road to play strange upgrade! (O ゜ – ゜▽゜)