30000 word express Servlet

Posted by qbox on Thu, 10 Feb 2022 04:56:48 +0100

catalogue

1, What is a Servlet

Manually implement Servlet program

2, Common configuration errors

3, How to locate the Servlet URL to the Servlet program for access

4, Servlet lifecycle

Servlet lifecycle summary

5, Distribution processing of Servlet request

Vi. realize Servlet program by inheriting HttpServlet

VII. Create Servlet program with idea

8, Inheritance system of Servlet

doGet and dopost source code

servlet method part of the source code

9, ServletConfig class

Three functions of ServletConfig class

10, ServletContext class

What is ServletContext?

What is a domain object?

Comparison table:

Four functions of ServletContext class

1. Get web The context parameters of the configuration in XML,

Error prone points:

Get current project path

Get the absolute path on the server hard disk after deployment

Access data like map

11, What is an agreement?

12, HTTP protocol format of the request

GET request

Illustration:

POST request

13, Common request header description

14, What are the of GET and POST requests

GET request:

POST request:

15, HTTP protocol format of response

Common response description

MIME type description

16, HttpServletRequest class

Common methods of HttpServletRequest class

Method demonstration:

After operation:

17, Servlet gets the parameters in the web form

get request:

post request:

XVIII. Forwarding of requests

Characteristics of request forwarding

19, base tag

The demo program cannot jump back

Operation results:

In place analysis:

20, Relative path and absolute path in Web

Relative path:

Absolute path:

21, Different meanings of / diagonal bar in web

22, HttpServletResponse class

Role of HttpServletResponse class

Description of two output streams

23, Return data to client

Chinese garbled code problem

The first way:

The second way:

The third way:

24, Request redirection

The first way to request redirection

Characteristics of request redirection

The second method of requesting redirection

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 Listenter listener.

3. servlet is a java applet running on the server. It can accept the request sent by the customer service side and respond to the data to the customer service side.

Manually implement Servlet program

Steps:

1. Write a class to implement the Servlet interface

2. Implement the service method, process the request and the corresponding data

3. To the web Configure the access address of Servlet program in XML

Create a servlet module similar to tomcat before the step

Create a class under src to implement the Servlet interface, press Alt+insert to select the implementation method, and press enter

The newly created class is as follows:

package com.servlet;

import javax.servlet.*;
import java.io.IOException;

public class HelloServlet implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    /**
     * service Methods are designed to handle requests and responses (accessed as long as the class is executed)
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("hello servlet Visited");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}

 3. To the web XML configuration, write the following in the web app tag

<!--servlet Label to Tomcat to configure Servlet program-->
    <servlet>
        <!-- servlet-name to Servlet The program has an alias(The general alias is called the class name)-->
        <servlet-name>HelloServlet</servlet-name>
        <!--servlet-class yes Servlet Full class name of the program -->
        <servlet-class>com.servlet.HelloServlet</servlet-class>
    </servlet>

    <!--servlet-mapping The label is for Servlet Program configuration access address    -->
    <servlet-mapping>
        <!-- servlet-name Is to tell the server which address I currently configure is for Servlet Program use-->
        <servlet-name>HelloServlet</servlet-name>
        <!--url-pattern Configure access address
           /  The slash indicates that the address is: http://ip:port / Project path < br / >
           /hello  Indicates that the address is: http://ip:port / Project path / Hello < br / >
        -->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

4. We're at index JSP, and then start

Results:

As mentioned earlier in Tomcat, only the project name is written, there is no resource name, and the index is accessed by default. The contents under the index directory will be presented to the browser

We previously configured the path to hello, and we will access the servlet program after adding it

2, Common configuration errors

① The path names are randomly selected without any relevance. Although there is no problem, it is difficult to distinguish

② , the path does not start with a diagonal bar, such as:

  <url-pattern>hello</url-pattern>

This will cause an error

Therefore, the name should be preceded by /, and the correct writing method is:

  <url-pattern>hello</url-pattern>

③ different names

There can also be prompts in idea. Some editors will not give prompts after running

When configuring the access address in servlet mapping, it should be consistent with the previous alias

④ . the full class name of the label is misspelled or omitted

The full class name is to write the location of the class that implements the Servlet interface. Errors will be reported if it is written incorrectly or less,

The circle should be consistent

3, How to locate the Servlet URL to the Servlet program for access

Among them, one port number can only be given to one project, and one project can occupy multiple port numbers (the project is the folder, and the resource is the directory in the folder)

4, Servlet lifecycle

Previous classes

package com.servlet;

import javax.servlet.*;
import java.io.IOException;

public class HelloServlet implements Servlet {
    public HelloServlet() {
        System.out.println("1 constructor ");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2 init Initialization method");
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    /**
     * service Methods are designed to handle requests and responses (accessed as long as the class is executed)
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("3 Servlet==hello servlet Visited");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("4 destroy Destruction method");
    }
}

When we start, visit http://localhost : 8080/01_servlet/hello

1, 2, 3 appear at the beginning, 3 appear after refreshing all the time, and 4 appear after exiting the program

Servlet lifecycle summary

1. Execute setvlet constructor method

2. Execute init initialization method

The first and second steps are to create a servlet at the first access, which will be called by the program,

3. Execute servlet method

Step 3: every access will call

4. Implement the destroy destruction method

Step 4: call when the web project stops

5, Distribution processing of Servlet request

When we use form submission, there are two submission methods: get (non encrypted) and post (encrypted)

Create a form a.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8080/02_servlet/hello" method="post">
    <input type="submit">
</form>
</body>
</html>

Override the method in the Servlet class

   @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("3 Servlet==hello servlet Visited");
        //Type conversion because HttpServletRequest has a getMethod method
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        //getMethod identifies whether the current submission method is GET or POST, and returns "GET" and "POST" respectively
         String method=httpServletRequest.getMethod();

         if("GET".equals(method)){
             //In order to prevent redundancy and better maintenance, define the method
            // System.out.println("get request");
             doGet();
         }else if ("POST".equals(method)){
             // System.out.println("post request");
             doPost();
         }
    }
        public void doGet(){
            System.out.println("get request");
        }
        public void doPost(){
            System.out.println("post request");
        }

Start the server, as shown in the figure

After running in the browser, each submission will access the service method and print out the corresponding method

Vi. realize Servlet program by inheriting HttpServlet

In actual development, the method of inheriting HttpServlet class is generally used to implement Servlet program.

Steps:

1. Write a class to inherit the HttpServlet class

2. Override doGet or doPost methods according to business needs

3. To the web Configuring Servlet program in XML

1. Write a class, Alt+insert shortcut key to override some required methods in

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 HelloServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // super.doGet(req, resp);
        System.out.println("HelloServlet2 of get request");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //  super.doPost(req, resp);
        System.out.println("HelloServlet2 of post request");
    }
}

To the web Configure access path in XML file

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

Change the access address hello in the form to Hello 2

After submission:

VII. Create Servlet program with idea

Select the package to be implemented → Servlet program

Configuration information

Check the annotation configuration of 3.0

Just on the web Just add a path to the XML (others have been generated automatically)

    <servlet>
        <servlet-name>HelloServlet2</servlet-name>
        <servlet-class>com.servlet.HelloServlet3</servlet-class>
    </servlet>
<!--The above is automatically generated. Just write the following -->   
 <servlet-mapping>
        <servlet-name>HelloServlet3</servlet-name>
        <url-pattern>/hello3</url-pattern>
    </servlet-mapping>

8, Inheritance system of Servlet

doGet and dopost source code

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = lStrings.getString("http.method_get_not_supported");
        this.sendMethodNotAllowed(req, resp, msg);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = lStrings.getString("http.method_post_not_supported");
        this.sendMethodNotAllowed(req, resp, msg);
    }

servlet method part of the source code

 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
                    ifModifiedSince = -1L;
                }

                if (ifModifiedSince < lastModified / 1000L * 1000L) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        }

9, ServletConfig class

  • ServletConfig is the configuration information class of the Servlet program.
  • Both Servlet program and ServletConfig object are created by Tomcat and used by us.
  • By default, Servlet programs are created during one access. ServletConfig is to create a corresponding ServletConfig object when each Servlet program is created

Three functions of ServletConfig class

1. You can get the alias of the Servlet program (the value of Servlet name)

2. Get initialization parameter init param

3. Get ServletContent object

Location init method

1. Get servlet alias

  public void init(ServletConfig servletConfig) throws ServletException {
         System.out.println("HelloServlet My alias is"+servletConfig.getServletName()); 
  }

2. Get the initialization parameter init param. Others have been written before

Now web XML file with < init param >

<!--servlet Label to Tomcat to configure Servlet program-->
    <servlet>
        <!-- servlet-name to Servlet The program has an alias(The general alias is called the class name)-->
        <servlet-name>HelloServlet</servlet-name>
        <!--servlet-class yes Servlet Full class name of the program -->
        <servlet-class>com.servlet.HelloServlet</servlet-class>

        <!--init-param When initializing parameters, this is a key value pair, and many pairs can be written -->
        <init-param>
            <!-- Parameter name-->
            <param-name>username</param-name>
            <!--Is the value of the parameter -->
            <param-value>root</param-value>
        </init-param>
        <init-param>
        <!-- Parameter name-->
        <param-name>url</param-name>
        <!--Is the value of the parameter -->
        <param-value>jdbc:mysql://localhost:3306/text</param-value>
        </init-param>
    </servlet>

Under init() in the class that implements the Servlet interface

  // 2. Get initialization parameter init param
        System.out.println("Initialization parameters username The value of is"+servletConfig.getInitParameter("username"));
        System.out.println("Initialization parameters url The value of is"+servletConfig.getInitParameter("url"));

3. Get ServlertContent object

 // 3. Get ServletContent object
        System.out.println("servletcontent Object is"+servletConfig.getServletContext());

The above operation results:

Each ServletConfig program is independent on the web The information in each class in XML is not shared,

When overriding the init method, add super Init (config), you have to access the init initialization method of the parent class, otherwise an error will be reported

The inheritance system can know that ServletConfig is in the GenericServlet class, and the init definition in this class:

    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

So if you override the init method, you must add super Init (config), otherwise the init method of the parent class will not be executed (the save operation in the parent class cannot be executed)

10, ServletContext class

What is ServletContext?

1. ServletContent is an interface that represents a Servlet context object

2. A web project has only one ServletContext object instance.

3. The ServletContent object is a domain object.

4. It is created after the web project is started and destroyed after the web project is completed

What is a domain object?

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

The domain here refers to the operation range of accessing data.

Comparison table:

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

Four functions of ServletContext class

1. Get web The configured context parameter context param in XML

2. Get the current project path, format: / Project path

3. Get the absolute path on the server hard disk after deployment

4. Access data like Map

Create a class ContextServlet with a shortcut in the web Configure the path in XML (the rest have been generated automatically)

    <servlet>
        <servlet-name>ContextServlet</servlet-name>
        <servlet-class>com.servlet.ContextServlet</servlet-class>
    </servlet>
<!-- It is automatically generated above, and the following path should be written by yourself-->
    <servlet-mapping>
        <servlet-name>ContextServlet</servlet-name>
        <url-pattern>/contextServlet</url-pattern>
    </servlet-mapping>

1. Get web The context parameters of the configuration in XML,

First, you have to go to the web Configure context param in XML (usually written on other servlet s)

<!--context-param Is a context parameter (it belongs to the whole web Engineering)-->
    <context-param>
        <!--Parameter name -->
        <param-name>username</param-name>
        <!--Parameter value-->
        <param-value>context</param-value>
    </context-param>
<!--Multiple pairs of context parameters can be written-->
    <context-param>
        <param-name>password</param-name>
        <param-value>root</param-value>
    </context-param>

In the doGet() method of the ContextServlet class

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Get web The configured context parameter context param in XML
        //Get object
        ServletContext context = getServletConfig().getServletContext();
        String username = context.getInitParameter("username");
        String password = context.getInitParameter("password");
        System.out.println("context-param parameter username The value of is"+username);
        System.out.println("context-param parameter password The value of is"+password);
    }
}

After running, the result is:

Error prone points:

① : configuring web Don't forget the / diagonal bar in the address in the XML file, otherwise it will report that the address is invalid

 <url-pattern>/contextServlet</url-pattern>

② : the parameters obtained in the class should be written in the doGet() method, otherwise the access address will not display the corresponding information after running

Get current project path

     System.out.println("Current project path:"+context.getContextPath());

Get the absolute path on the server hard disk after deployment

System.out.println("Get the path of project deployment"+context.getRealPath("/"));

This diagonal bar / represents the path to the current project

Access data like map

Create a Servlet class in web Configure the path in the XML file

   <servlet>
        <servlet-name>ContextServlet1</servlet-name>
        <servlet-class>com.servlet.ContextServlet1</servlet-class>
    </servlet>
<!-- The above are automatically configured-->
  <servlet-mapping>
        <servlet-name>ContextServlet1</servlet-name>
        <url-pattern>/contextServlet1</url-pattern>
    </servlet-mapping>

In class:

public class ContextServlet1 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //Get ServletContext object
        ServletContext context = getServletContext();
        System.out.println("Before saving Context obtain key1 The values are:"+context.getAttribute("key1"));
        context.setAttribute("key1","value1");
        System.out.println("context get data key1 The value of is:"+context.getAttribute("key1"));
    }
}

We can directly use getservletcontext () to get the object, which is simpler than getservletconfig () getServletContext();

We can see from the source code of ctrl+b:

    public ServletContext getServletContext() {
        return this.getServletConfig().getServletContext();
    }

The source code has done that step, so we can go back directly.

Let's continue to define a class called ContextServlet2

public class ContextServlet2 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = getServletContext();
        System.out.println("ContextServlet2 in context get data key1 The value of is:"+context.getAttribute("key1"));
    }
}

The deployment is omitted. After running

It is not difficult to find that when there is data stored in ContextServlet1, the data can be found in ContextServlet2. Alternatively, the data under the context is shared data

 

The ContextServlet object is created after the web project is started, destroyed and shared after the web project is completed

Both restart and redeployment will lead to the destruction of the web project

The addresses of ContextServlet1 and 2 are the same

11, What is an agreement?

An agreement refers to the rules that both parties or multiple parties agree on and everyone needs to abide by. It is called an agreement

The HTTP protocol refers to the rules to be followed when sending data during the communication between the client and the server, which is called HTTP protocol

Data in HTTP message.

12, HTTP protocol format of the request

The data sent by the customer service side to the server is called a request.

The server sends back data to the customer service terminal for response.

Requests are divided into GET and POST requests

GET request

1. Request line

(1) Method of request: GET

(2) Requested resource path [+? + request parameters]

(3) The version number of the requested protocol is HTTP/1.1

2. Request header

Key: value  different key value pairs represent different meanings.

Start server:

Illustration:

POST request

1. Request line

(1) request method: POST

(2) requested resource path [+? + request parameters]

(3) requested protocol number: HTTP/1.1

2. Request header

1) key: value = different request headers have different meanings

Empty line

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

Main contents in the form:

<from action="http://localhost:8080/06_servlet/hello3" method="post">
    <input type="hidden" name="action" value="login"/>
    <input type="hidden" name="username" value="root"/>
    <input type="submit">
</from>

Illustration:

13, Common request header description

Accept: indicates the data type acceptable to the customer service end

Accpet language: indicates the language type acceptable to the client

User agent: represents the information of the client browser

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

14, What are the of GET and POST requests

GET request:

1. form tag method=get

2. a label

3. link tag is introduced into css

4. Import Script tag into js file

5. img label introduction picture

6. ifram introduces html page

7. Enter the address in the browser address bar and press enter

POST request:

1. from tag method=post

15, HTTP protocol format of response

1. Line response

(1) response protocol and version number

(2) response status code 1

(3) response state descriptor

2. Response header

(1) key: value , different response headers have different meanings

Empty line

3. Response body - > > > is the data returned to the client

Common response description

200 indicates that the request is successful

302 indicates request redirection

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

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

MIME type description

MiME is the data type in HTTP protocol.

The full English name of mime is "Multipurpose Internet Mail Extensions" multifunctional Internet Mail extension service. The format of MIME type is "large type / small type" and corresponds to the extension of a certain file.

Such as gif type; The large type is a picture, and the small type is gif, which is expressed as image/gif

Common MIME types:

16, HttpServletRequest class

effect:

Every time a Request enters the Tomcat server, the Tomcat server parses and encapsulates the requested HTTp protocol information into the Request object, and then passes it to the service method (doGet and doPost are for us to use, and we can get all the requested information through the HttpServletRequest object)

Common methods of HttpServletRequest class

getRequestURI() gets the resource path of the request

getRequestURL() gets the uniform resource locator (absolute path) of the request

getRemoteHost: get the ip address of the client

getHeader() get request header

getParameter: get request parameters

getParameterValues() gets the parameters of the request pair (multiple values are used at the same time)

getMethod() gets the method of the request, GET or POST

setAttribute(key,value) sets the field data

getAttribute(key) get domain data

getRequestDispatcher: get request forwarding object

Method demonstration:

Create a web project 03_servlet, on the web Configuration in XML

    <servlet>
        <servlet-name>RequestAPIServlet</servlet-name>
        <servlet-class>com.servlet.RequestAPIServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RequestAPIServlet</servlet-name>
        <url-pattern>/requestAPIServlet</url-pattern>
    </servlet-mapping>

Create a class RequestAPIServlet under src to inherit HttpServlet

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 RequestAPIServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //        getRequestURI() gets the resource path of the request
        System.out.println("URI->"+req.getRequestURI());
        //        getRequestURL() gets the uniform resource locator (absolute path) of the request
        System.out.println("URL->"+req.getRequestURL());
        //        getRemoteHost: get the ip address of the client
        System.out.println("client ip Address:"+req.getRemoteHost());
        //        getHeader() get request header
        System.out.println("Request header User-Agent->"+req.getHeader("User-Agent"));
        //        getMethod() gets the method of the request, GET or POST
        System.out.println("Method of request:"+req.getMethod());
    }
}

Modify the information in the edit configuration to 03_ Servlets or something.

After operation:

 URI->/03_servlet/requestAPIServlet
URL->http://localhost:8080/03_servlet/requestAPIServlet
Client ip address: 0:0:0:0:0:0:0:1
Request header user agent - > Mozilla / 5.0 (Windows NT 10.0; win64; x64) applewebkit / 537.36 (KHTML, like gecko) Chrome / 97.0.4692.99 Safari / 537.36
Request method: GET

We can also find that the URI is only the resource path to the project name, while the URL is the full path and can be accessed directly.

17, Servlet gets the parameters in the web form

get request:

Create a parameter class under src. ParameterServlet inherits the HttpServlet class

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
public class ParameterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get request parameters
     String username=req.getParameter("username");
     String password=req.getParameter("password");
     String[] hobby=req.getParameterValues("hobby");
        System.out.println("account number:"+username);
        System.out.println("password:"+password);
        //Arrays.asList() returns an array
        System.out.println("Hobbies:"+ Arrays.asList(hobby));
    }

}

On the web Configure parameters in XML

 <servlet>
        <servlet-name>ParameterServlet</servlet-name>
        <servlet-class>com.servlet.ParameterServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ParameterServlet</servlet-name>
        <url-pattern>/parameterServlet</url-pattern>
    </servlet-mapping>

Write html file in web Directory

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="http://localhost:8080/03_servlet/parameterServlet" method="get">
 account number:<input type="text" name="username"><br>
 password:<input type="password" name="password"><br>
    <input type="checkbox" name="hobby" value="HTML">HTML
    <input type="checkbox" name="hobby" value="Java">Java
    <input type="checkbox" name="hobby" value="JavaScript">JavaScript
    <input type="checkbox" name="hobby" value="Spring Family bucket">Spring Family bucket
    <input type="checkbox" name="hobby" value="Servlet">Servlet<br>
    <input type="submit">
</form>
</body>
</html>

Start operation:

Fill in several groups of information and submit:

post request:

In class:

 @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get request parameters
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String[] hobby=req.getParameterValues("hobby");
        System.out.println("account number:"+username);
        System.out.println("password:"+password);
        //Arrays.asList() returns an array
        System.out.println("Hobbies:"+ Arrays.asList(hobby));
    }

Put method="post", in the request of post, once there is Chinese, there will be garbled code,

At this time, the set character set should be added to the doPost method body:

  req.setCharacterEncoding("UTF-8");

Note: the set character set must be above the obtained parameters, otherwise garbled code will appear.

 @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   //Set character set
        req.setCharacterEncoding("UTF-8");
        //Get request parameters
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String[] hobby=req.getParameterValues("hobby");
        System.out.println("account number:"+username);
        System.out.println("password:"+password);
        //Arrays.asList() returns an array
        System.out.println("Hobbies:"+ Arrays.asList(hobby));
    }

Run again:

XVIII. Forwarding of requests

Request forwarding refers to the operation of jumping from one resource to another, which is called request forwarding

Create two classes servlet1 and servlet2 to inherit HttpServlet

Under Servlet1 class:

import javax.servlet.RequestDispatcher;
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 Servlet1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get the requested parameters (materials for work) view
        String username=request.getParameter("username");
        System.out.println("stay Servlet1(Counter 1) view parameters (materials)"+username);
        //Set the domain data (stamp the material and transfer it to Servlet2 (counter 2) for viewing)
        request.setAttribute("key1", "Seal of counter 1");
        //Ask the way: how to get to Servlet2
        /**
         * Request forwarding must start with a diagonal bar /, which indicates that the address is http://ip:port/ The project name / mapping to the idea is the web directory
         */
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/servlet2");

        //Go to servlet2 (counter 2)
        requestDispatcher.forward(request, response);

    }
}

Under servlet2:

import javax.servlet.RequestDispatcher;
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 Servlet2 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get the requested parameters (materials for work) view
        String username=request.getParameter("username");
        System.out.println("stay Servlet2(Counter 2) view parameters (materials)"+username);
        //Check whether counter 1 is stamped
        Object key1 = request.getAttribute("key1");
        System.out.println("Does counter 1 have a seal:"+key1);
        //Handle your own business
        System.out.println("Servlet2 Handle your own business");
    }
}

Run access http://localhost:8080/03_servlet/servlet1

Operation results:

Add parameters in the access bar? Parameters are followed

Enter:

Characteristics of request forwarding

1. The browser address bar has not changed (always the project name / servlet1)

2. They are a request

3. Data in the Request domain can be shared (domain data can be accessed in the whole project)

4. It can be forwarded to the WEB-INF directory (WEB-INF is protected by the server and cannot be accessed directly through the client (browser), but indirectly through the resources in the server)

5. Resources other than the project cannot be accessed (because they are found under the project, and those not under the project cannot be accessed)

In class Servlet1:

Address access:

   RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/form.html");

19, base tag

The demo program cannot jump back

Create a class ForwardC to inherit the HttpServlet class

public class ForwardC extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Yes Forward program");
        req.getRequestDispatcher("/a/b/c.html").forward(req, resp);
    }
}

On the web Configuration in XML

  <servlet>
        <servlet-name>ForwardC</servlet-name>
        <servlet-class>com.servlet.ForwardC</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ForwardC</servlet-name>
        <url-pattern>/forwardC</url-pattern>
    </servlet-mapping>

Create in the web directory, as shown in the figure

Write in c Directory

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>This is a c page</title>
  
</head>
<body>
<a href="../../index.html">Return to home page</a>
</body>
</html>

In index HTML write down

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
This is web Lower index.html<br>
<a href="a/b/c.html">a/b/c.html</a><br>
<a href="http://localhost:8080/03_ Servlet / forwardc "> request forwarding: A / B / c.html</a>
</body>
</html>

After operation:

As we mentioned earlier, only the project name is written, and the index page is accessed by default

We found that clicking both up and down can successfully jump

Although they all successfully jump, the address is obviously different, because we write.. / under c.html/ index.html,

Operation results:

In place analysis:

The former (the first), localhost:8080/03_servlet/a/b/c.html, after.. // You can jump to the web project. There is index under the web HTML, so it will jump successfully.

The latter (second), localhost:8080/03_servlet/forwardC, after.. // The jump will jump to the src directory, and there is obviously no index in the src directory HTML page, so it will fail. (structure: src/com/servlet/Forward)

Illustration:

When we add the base tag, the browser will take the base tag as the final address.

The base tag is usually added under the title

  <base href="http://localhost:8080/03_servlet/a/b/c.html">
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>This is a c page</title>
   <base href="http://localhost:8080/03_servlet/a/b/c.html">
</head>
<body>
<a href="../../index.html">Return to home page</a>
</body>
</html>

This solves the problem that the latter cannot be transferred to the home page.  

20, Relative path and absolute path in Web

In javaWeb, paths are divided into relative paths and absolute paths:

Relative path:

. indicates the current directory

.. Indicates the upper level directory

Resource name indicates the current directory / resource name

Absolute path:

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

21, Different meanings of / diagonal bar in web

In the web / diagonal bar is an absolute path.

/If the diagonal bar is parsed by the browser, the address obtained is: http://ip:port/

The significance of < a href = "/" > diagonal bar</a>

/If the diagonal bar is parsed by the server, the address obtained is: http://ip:port/ Engineering path

           1,<url-pattern>/servlet1<url-pattern>

           2,servletContext.getRealPath("/");

           3,request.getRequestDispatcher("/")

Special case: response sendRediect("/"); Send the inclined bar to the browser for analysis and get http://ip:port/

22, HttpServletResponse class

Role of HttpServletResponse class

The HttpServletResponse class is the same as the HttpServRequest class. Every time a request comes in, the Tomcat server will create a Response object and pass it to the Servlet program for use. HttpServletRequest represents the information received, and HttpServletResponse represents the information of all responses. If we need to set the information returned to the client, we can set it through the HttpServletResponse object

Description of two output streams

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

Character stream: getWriter(); Often used to return string (common)

Only one of two streams can be used at the same time. Otherwise, an error is reported

23, Return data to client

Create a class ResponIOServlet:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResponseIOServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer=response.getWriter();
        writer.write("AiQingShuiXingL");
    }
}

web.xml configuration, after running:

Chinese garbled code problem

Set response setCharacterEncoding("GBK"); It can solve the problem of Chinese displaying garbled code in the browser

The first way:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ResponseIOServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(response.getCharacterEncoding());//The default character set is ISO-8859-1 and Chinese is not supported
      //Set character set to GBK
       response.setCharacterEncoding("GBK");
        PrintWriter writer=response.getWriter();
        writer.write("Waking Love Up ");
    }

The second way:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ResponseIOServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(response.getCharacterEncoding());//The default character set is ISO-8859-1 and Chinese is not supported
     
       //Set the character set to UTF-8
        response.setCharacterEncoding("UTF-8");
        //Just tell the browser to set UTF-8
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        PrintWriter writer=response.getWriter();
        writer.write("Waking Love Up ");
    }
}

The third way:

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ResponseIOServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(response.getCharacterEncoding());//The default character set is ISO-8859-1 and Chinese is not supported
//It must be used before obtaining the stream object, otherwise it is invalid
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer=response.getWriter();
        writer.write("Waking Love Up ");
    }
}

24, Request redirection

The first way to request redirection

Create two classes response1 and response2

response1

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 Response1 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Set the response status code 302 to indicate redirection (moved to a new location)
        resp.setStatus(302);
        //Set the response header to indicate where the new address is
        resp.setHeader("Location","http://localhost:8080/03_servlet/response2");
    }
}

response2

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 Response2 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       resp.getWriter().write("hello response2");
    }
}

web. Configure access path in XML configuration

    <servlet>
        <servlet-name>Response1</servlet-name>
        <servlet-class>com.servlet.Response1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Response1</servlet-name>
        <url-pattern>/response1</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>Response2</servlet-name>
        <servlet-class>com.servlet.Response2</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Response2</servlet-name>
        <url-pattern>/response2</url-pattern>
    </servlet-mapping>

Operation results:

Characteristics of request redirection

1. The browser address bar changes

2. Two requests (the first is the old address and the second is to relocate to the new address)

3. The data in the Request field cannot be shared (because Tomcat will seal each Request into one object, and two requests are different objects)

4. Unable to access resources under WEB-INF (because it is also a request sent by the browser, the browser cannot directly access WEB-INF)

5. You can access resources outside the project, such as www.baidu.com com

The second method of requesting redirection

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 Response1 extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //The second method (set the new access address directly in parentheses)
        resp.sendRedirect("http://www.baidu.com");
    }
}

Topics: Java servlet Network Protocol http