Servlet of Java Web Technology (Java Web core)

1, Introduction

1. What is a Servlet?

  1. Servlet is one of the Java EE specifications. A specification is an interface.
  2. Servlet is one of the three major components of Java Web. The three components are: servlet program, Filter filter and Listener listener.
  3. Servlet is a java applet running on the server. It can receive requests from the client and respond to data to the client.

2. Manually implement the Servlet program

  1. Write a class to implement the Servlet interface
  2. Implement the service method, process the request and respond to the data
  3. To the web XML to configure the access address of the servlet program

Servlet program code example:

public class HelloServlet implements Servlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { 
        System.out.println("Hello Servlet Was interviewed"); 
    }
}

web. Configuration in XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>hello.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
</web-app>

3.Servlet life cycle

  1. Execute Servlet constructor method

  2. Execute init initialization method

    The first and second steps are to create a Servlet during the first access, and the program will call.

  3. Execute the service method

    The third step is to call every access.

  4. Execute destroy destroy method

    Called when the web project stops.

4.GET and POST requests

public class HelloServlet implements Servlet {
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("Hello Servlet Was interviewed");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String method = httpServletRequest.getMethod();
        
        if("GET".equals(method)){
            doGet();
        }else if("POST".queals(method)){
            doPost();
        }
    }
    
    public void doGet(){
        System.out.println("get request");
    }
    public void doPost(){
        System.out.println("post request");
    }
}

5. Implement Servlet program by inheriting HttpServlet

Generally, in the actual project development, the Servlet program is implemented by inheriting the HttpServlet class.

  1. Write a class to inherit the HttpServlet program
  2. Override doGet or doPost methods according to business needs
  3. To the web XML to configure the access address of the Servlet program

Code of Servlet class:

public class HelloServlet2 extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet2 of doGet method");
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet2 of doPost method");
    }
}

web. Configuration in XML:

    <servlet>
        <servlet-name>HelloServlet2</servlet-name>
        <servlet-class>hello.HelloServlet2</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet2</servlet-name>
        <url-pattern>/hello2</url-pattern>
    </servlet-mapping>

6. Create a Servlet program using IDEA

  1. Menu: New - > Servlet

  2. Configure servlet

If not, file - > projectstructure - > face - > sourceroots, and check the file with src at the end.

7. Inheritance system of servlet class

2, ServletConfig class

From the perspective of class name, ServletConfig class is the configuration information class of Servlet program.

Three functions

  1. You can get the value of the alias servlet name of the servlet program
  2. Get initialization parameter init param
  3. Get ServletContext object

web. Configuration in XML

<servlet>
    <!--alias-->
    <servlet-name>HelloServlet</servlet-name>
    <!--init-param Is an initialization parameter-->
    <servlet-class>hello.HelloServlet</servlet-class>
    
    <init-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </init-param>
</servlet>

Code in Servlet:

public void init(ServletConfig servletConfig) throws ServletException {
    //1. You can get the value of the alias Servlet name of the Servlet program
    System.out.println("HelloServlet The alias of the program is:" + servletConfig.getServletName());
    //2. Get the initialization parameter init param
    System.out.println("Initialization parameters username The value of is;" + servletConfig.getInitParameter("username"));
    //3. Get ServletContext object
    System.out.println(servletConfig.getServletContext());
}

3, ServletContext class

a) What is ServletContext?

  1. ServletContext is an interface that represents a Servlet context object.
  2. A web project has only one ServletContext object instance.
  3. The ServletContext object is a domain object.
  4. ServletContext is created when the web project deployment starts. Destroy when the web project stops.

b) What is a domain object

A domain object is an object that can store data like a Map. It is called a domain object

The domain here refers to the operation range of accessing data, the whole web project

Save dataFetch dataDelete data
Mapput()get()remove()
Domain objectsetAttribute()getAttribute()removeAttribute()

c) Four functions of ServletContext class

  1. Get web The context parameter content param configured in XML
  2. Get the current project path, format: / Project path
  3. Get the absolute path on the hard disk of the project deployment background server
  4. Store data like Map
public class ContextServlet1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        System.out.println("Before saving: Context1 obtain key1 The value of is:"+ context.getAttribute("key1"));
        context.setAttribute("key1", "value1");
        System.out.println("Context1 Get domain data from key1 The value of is:"+ context.getAttribute("key1"));
    }
}

4, Http request

1.http protocol

What is an agreement?

Agreement refers to the rules agreed by both parties or multiple parties and everyone needs to abide by, which is called agreement.

What is the http protocol?

The so-called HTTP protocol refers to the rules that need to be followed for the data sent during the communication between the client and the server, which is called HTTP protocol.

The data in http protocol is also called message.

Format of request http protocol

The client sends a data call request to the server.

The server sends back data to the client for response.

2.GET request

  1. Request line

    1. The method of the request is GET
    2. Requested resource path (+? + request parameters)
    3. Requested protocol version number HTTP/1.1
  2. Request header

    key:value forms different key value pairs, indicating different meanings.

3.POST request

  1. Request line

    1. Request mode POST
    2. Requested resource path (+? + request parameters)
    3. Requested protocol version number HTTP/1.1
  2. Request header

    key:value forms different key value pairs, indicating different meanings.

    Blank line

  3. The request body > > > > is the data sent to the server

4. Description of common request headers

Accept: indicates the data type that the client can accept

Accept language: indicates the language type that the client can accept

User agent: represents the information of the client browser

Host: indicates the server ip and port number at the time of the request

5. Which are get requests and which are POST requests

GET request:

  1. form tag method=get
  2. a label
  3. link tag introduces css
  4. Script tag import js file
  5. img tag import picture
  6. iframe introduces html pages
  7. Enter the address in the browser address bar and press enter

POST request:

  1. form label method=post

6. HTTP protocol format of response

  1. Response line

    1. The protocol and version number of the response
    2. Response status code
    3. Response state descriptor
  2. Response header

    1. key:value different response headers have different meanings

      Blank line

  3. The response body ----- > > > is the data returned to the client

Description of common response codes

200: indicates that the request was successful

302: indicates request redirection

404: indicates that the request server has received it, but the data you want does not exist (the request address is wrong)

500: indicates that the server has received the request, but the server has an internal error (code error)

5, HttpServletRequest class (* *)

1. Role of HttpServletRequest class

Get the request information to enter the Tomcat server.

2. Common methods of HttpServletRequest class

getRequestURI()Gets the requested resource path
getRequestURL()Gets the requested uniform resource locator (absolute path)
getRemoteHost()Get the ip address of the client
getHeader()Get request header
getParameter()Get requested parameters
getParameterValues()Get the requested parameter (used when multiple values are used)
getMethod()GET or POST the request
setAttributerValues(key, value)Set domain data
getAttribute(key)Get domain data
getRequestDispatcher()Get request forwarding object

3. How to obtain request parameters

getParameter()Get requested parameters
getParameterValues()Get the requested parameter (used when multiple values are used)

Form

<body>    <form action="http://localhost:8080/07_ Servlet / servlet "method =" get "> User Name: < input type =" text "name =" username "> < br / > password: < input type =" password "name =" password "> < br / > hobbies: < input type =" checkbox "name =" hobby "value =" CPP "> C + + < input type =" checkbox "name =" hobby "value =" Java "> java < input type =" checkbox "name =" hobby "value =" JS ">JavaScript<br/>        <input type="submit">    </form></body>

Java code:

public class ParameterServlet extends HttpServlet { @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {         // Get request parameter string username = req getParameter("username");         String password = req. getParameter("password");         String[] hobby = req. getParameterValues("hobby");         System. out. Println ("user name:" + username); System. out. Println ("password:" + password); System. out. Println ("hobbies:" + Arrays.asList(hobby));}}

Chinese garbled code solution of doGET request

String username = req.getParameter("username");//1 encode with iso8859-1 / / 2 decode with utf-8 username = new String(username.getBytes("iso-8859-1"), "UTF-8");

Chinese garbled code solution for POST request

req.setCharacterEncoding("UTF-8");

4. Forwarding of requests

What is request forwarding?

Request forwarding refers to the operation that the server jumps from one resource to another after receiving the request, which is called request forwarding.

Servlet1 Code:

public class Servlet1 extends HttpServlet {    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        // Get the requested parameters (materials for work) and view string username = req.getparameter ("username"); System. out. Println ("view parameter (material) in Servlet1 (counter 1):" + username)// Stamp a chapter on the material and pass it to Servlet2 (counter 2) to view req.setAttribute("key1", "chapter of counter 1")// How to get to Servlet2 (counter 2): RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servlet2")// Go to Sevlet2 (counter 2) requestDispatcher.forward(req,resp);}}

Servlet2 Code:

public class Servlet2 extends HttpServlet {    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        // Get the requested parameters (materials for work) and view string username = req.getparameter ("username"); System. out. Println ("view parameters (materials) in Servlet2 (counter 2):" + username)// Check whether counter 1 has a seal object key1 = req getAttribute("key1");         System. out. Println ("does counter 1 have a seal:" + key1)// Handle your own business system out. Println ("Servlet2 handles its own business");}

5. Function of base label

The base tab sets the address referenced when the relative path of the page works

The href attribute is the address value of the parameter

<!DOCTYPE html><html lang="zh_CN">    <head>        <meta charset="UTF-8">         <title>Title</title>         <!--base The address referenced when the relative path of the label setting page works href Property is the address value of the parameter -->         <base href="http://localhost:8080/07_ Servlet / A / b / "> < / head > < body > this is the c.html page under a and b < br / > < a href =".. // index. HTML "> jump back to the home page < / a > < br / ></body></html>

6. Path in Web

Relative and absolute paths in the Web

Relative path:

. Represents the current directory

... indicates the upper level directory

The resource name represents the current directory / resource name

Absolute path

http://ip:port/ Project path / resource path

In open instances, absolute paths are used instead of relative paths.

  1. Absolute path
  2. base + relative

Different meanings of / slash in web

/If the slash is parsed by the browser, the resulting address is: http://ip:port/

<a herf="/">Slash</a>

/If the slash is parsed by the server, the resulting address is: http://ip:port/ Engineering path

1. <url-pattern>/servlet</url-pattern>2. servletContext.getRealPath("/");3. request.getRequestDispatcher("/");

exceptional case:

> response.sendRediect("/");   Send the slash to the browser for parsing. obtain http://ip:port/

6, HttpServletResponse class (* *)

1. Role of httpservletresponse class

HttpServletResponse is the same as the HttpServletRequest class. Every time a request comes in, the Tomcat server will create a Respnose object and pass it to the Servlet program for use. HttpServletRequest represents the requested information, which is set by the HttpServletResponse object

2. Description of two output streams

Byte stream getOutputStream(); Commonly used for downloading (passing binary data)

Character stream getWriter(); Commonly used to return string (commonly used)

Note: two streams can only be one at the same time. When byte stream is used, character stream can no longer be used. Vice versa, otherwise an error will be reported.

3. How to return data to the client

public class ResponseIOServlet extends HttpServlet {    @Override     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        PrintWriter writer = resp.getWriter();        writer.write("response's content!!!");    }}

4. Response garbled code resolution

Solution 1: (not recommended)

// Set the server character set to UTF-8 resp setCharacterEncoding("UTF-8"); //  Through the response header, set the browser to also use the UTF-8 character set resp setHeader("Content-Type", "text/html; charset=UTF-8");

Solution 2: (recommended)

// It will set up both the server and the client to use the UTF-8 character set, and set the response header / / this method must be called before the stream object is valid resp.. setContentType("text/html; charset=UTF-8");

5. Request redirection

Request redirection means that the client sends a request to the server, and then the server tells the client. I'll give you some addresses. You visit the new address. Call request redirection (because the previous address may have been discarded).

The first method to request redefinition (not recommended)

//Set the corresponding status, indicating redirection (relocated) resp.setStatus(302)// Set the response header to indicate where the new address is resp setHeader("Location", " http://localhost:8080 ");

The second solution to request redirection (recommended)

resp.sendRedirect("http://localhost:8080");

Keywords: Java servlet

Added by KevinCB on Wed, 22 Dec 2021 17:26:05 +0200