servlet learning notes

Posted by synchro_irl on Mon, 07 Mar 2022 16:11:51 +0100

1. servlet Basics

1.1. What is a servlet? (what)

Servlet is a Java program running on the server. It can receive requests from the client and respond to data to the client.
Servlet is one of the three major components of Java Web. The three major components are servlet program, Filter filter and Listener listener

1.2. Why use servlet s? (why)

We are one of the components of the web container. Since we study the web, the three components are essential. The jsp we learned before is essentially a java class.
For example: demo JSP, and the demo is generated after compilation Java and demo Class file, and these two files will import packages about servlets, so learning servlets is essential.

1.3. How to use servlet? (how)

We can inherit the HttpServlet class or implement the servlet class to servlet this class.

1.4 servlet knowledge points

  1. servlet lifecycle
  1. Construction method of executing Servlet program
  2. Execute init method
  3. Execute service method
  4. Execute destroy method
    Note: among them, 1 and 2 will be executed when accessing and creating the Servlet program for the first time (only once when starting the service), each refresh (access) in step 3 will be executed, and once when clicking stop in step 4
  1. Inheritance relationship of servlet:

  2. servletConfig interface:

  1. From the name, we can see that the configuration information of Servlet program is in this interface:
    (1) Both servlet programs and ServletConfig objects are created by Tomcat and used by programmers
    (2) By default, the Servlet program is created during the first access. When each Servlet program is created, the corresponding ServletConfig object is created. The two correspond to each other. A Servlet program can only obtain its corresponding ServletConfig object, but cannot obtain the ServletConfig object of other Servlet programs
  1. Three functions of ServletConfig interface:
    (1) You can get the alias of the Servlet program (that is, the content of web.xml)
    (2) You can get the web Value of initialization parameter of XML
    (3) Can get ServletContext object
  1. servletContext interface:
  1. The ServletContext interface represents a Servlet context object
  2. A web project has only one ServletContext object instance
  3. ServletContext is created when the web project starts and destroyed when the web project stops
  4. The ServletContext object is a domain object
  1. Common response codes

200 indicates that the request was successful
302 indicates request redirection
404 indicates that the server receives the request, but the requested data does not exist (wrong request address)
500 indicates that the server received the request, but the server has an internal error (code error)

  1. HttpServletRequest class:

Every time a Request enters the Tomcat server, the Tomcat server parses and encapsulates the HTTP protocol information sent by the Request into the Request object, and then passes it to the service method (calling doGet or doPost method) for programmers to use. Programmers can obtain all the information of the Request through the HttpServletRequest object

Common methods of HttpServletRequest class:
getRequestURI(): get the resource path of the request
getRequestURL(): get the absolute path of the request
getRemoteHost(): get the ip address of the client
getHeader(): get request header
getParameter(): get the parameters of the request
getParameterValues(): get the requested parameters (used when there are multiple values)
Method of GET or post request
setAttribute(key, value): set the field data
getAttribute(key): get domain data
getRequestDispatcher(): get the request forwarding object

  1. HttpServletResponse class

Every time a request enters the Tomcat server, the Tomcat server will create a Response object and pass it to the Servlet program. HttpServletResponse indicates the information of all responses (HttpServletRequest indicates the information sent by the request), and the information returned to the client can be set through the HttpServletResponse object

Description of the two output streams:
Byte stream getOutputStream(); Commonly used to download (transfer) binary data
Character stream getWriter(); Commonly used to return string
Return string data from the server to the client (browser)

  1. Request forwarding

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

  1. redirect

Request redirection refers to that the client sends a request to the server, and then the server notifies the client to access its new address (the previous address may be discarded), which is called request redirection

  1. The meaning of "/":

"/" if parsed by the browser, the resulting address is: http://ip:port/
(1) /
"/" if parsed by the server, the resulting address is: http://ip:port/ Engineering path
(1) /servlet1
(2) servletContext.getRealPath("/");
(3) request.getRequestDispatcher("/");

2. servlet Programming

2.1. We write a simple servlet

  1. Create a web project.

  2. Create a servlet class named WebDemo1

package com.controller;

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 WebDemo1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("This is get Method 1");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("This is post Method 1");
    }
}

  1. Configure web XML file.
<?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>webDemo1</servlet-name>
            <servlet-class>com.controller.WebDemo1</servlet-class>
        </servlet>
      
    <servlet-mapping>
        <servlet-name>webDemo1</servlet-name>
        <url-pattern>/web1</url-pattern>
    </servlet-mapping>

</web-app>
  1. It can be seen that the project is launched and the results can be accessed.

2.2. We continue to create a more difficult project

First create a jsp page with a button. Click this button to display a line of words "you succeeded" on the console.

  1. Create a servlet class, name it WebDemo1, and write out the content.
package com.controller;

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 WebDemo1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("This is get Method 1");
        System.out.println("You did it");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("This is post Method 1");
    }
}

  1. Modify web XML file
<?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>webDemo1</servlet-name>
            <servlet-class>com.controller.WebDemo1</servlet-class>
        </servlet>
      
    <servlet-mapping>
        <servlet-name>webDemo1</servlet-name>
        <url-pattern>/web1</url-pattern>
    </servlet-mapping>

</web-app>
  1. Create a new jsp page named index1 jsp page.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/web1" >
    <input type="submit" value="Submit">
</form>
</body>
</html>

  1. Access and view results

2.3. Let's continue to upgrade

We enter some information on a page and print it on the console.

  1. Create an index JSP page.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
        <form action="${pageContext.request.contextPath}/web1" method="post">
            full name:<input type="text" name="userName"><br>
            password:<input type="password" name="password"><br>
            Gender:<input type="radio" value="male" name="sex">male <input type="radio" value="female" name="sex">female<br>
            address:<select name="address">
                <option value="Beijing">Beijing</option>
                <option value="Nanjing">Nanjing</option>
        </select><br>
            Hobbies:<input type="checkbox" name="hobby" value="Basketball">Basketball
            <input type="checkbox" name="hobby" value="Football">Football
            <input type="checkbox" name="hobby" value="badminton">badminton<br>
            <input type="submit" value="Submit"/>
        </form>



  </body>
</html>
  1. Create a servlet class
package com.controller;

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 WebDemo2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get2");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("post2");
        //Solve Chinese garbled code
        resp.setContentType("text/html;charset=utf-8");
        //Request to resolve garbled code
        req.setCharacterEncoding("utf-8");
        //Response to resolve garbled code
        resp.setCharacterEncoding("utf-8");


        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String address = req.getParameter("address");
        String sex = req.getParameter("sex");
        String[] hobbies = req.getParameterValues("hobby");


        System.out.println("full name:"+ userName);
        System.out.println("password:"+ password);
        System.out.println("Gender:"+ sex);
        System.out.println("Hobbies:"+ Arrays.toString(hobbies));
        System.out.println("Address:"+ address);


        req.getRequestDispatcher("/result/result1.jsp").forward(req, resp);
    }
}

  1. Modify web XML file
<?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>webDemo1</servlet-name>
            <servlet-class>com.controller.WebDemo1</servlet-class>
        </servlet>

        <servlet>
              <servlet-name>webDemo2</servlet-name>
               <servlet-class>com.controller.WebDemo2</servlet-class>
         </servlet>

         <servlet-mapping>
             <servlet-name>webDemo2</servlet-name>
              <url-pattern>/web2</url-pattern>
          </servlet-mapping>

    <servlet-mapping>
        <servlet-name>webDemo1</servlet-name>
        <url-pattern>/web1</url-pattern>
    </servlet-mapping>

</web-app>
  1. Run and view the results.

2.4. Let's continue to upgrade

Information obtained from one page is forwarded to another page for display

  1. Write index JSP page (2.3)
  2. Modify web XML file (2.3)
  3. Modify servlet class
package com.controller;

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 WebDemo2 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get2");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("post2");
        //Solve Chinese garbled code
        resp.setContentType("text/html;charset=utf-8");
        //Request to resolve garbled code
        req.setCharacterEncoding("utf-8");
        //Response to resolve garbled code
        resp.setCharacterEncoding("utf-8");


        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        String address = req.getParameter("address");
        String sex = req.getParameter("sex");
        String[] hobbies = req.getParameterValues("hobby");


        System.out.println("full name:"+ userName);
        System.out.println("password:"+ password);
        System.out.println("Gender:"+ sex);
        System.out.println("Hobbies:"+ Arrays.toString(hobbies));
        System.out.println("Address:"+ address);

        req.setAttribute("userName", userName);
        req.setAttribute("password", password);
        req.setAttribute("sex", sex);
        req.setAttribute("hobbies", Arrays.toString(hobbies));
        req.setAttribute("address", address);

        req.getRequestDispatcher("/result/result1.jsp").forward(req, resp);
    }
}

Here we use a request forwarding.

  1. Create a new result jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    full name: ${userName}
    Gender: ${sex}
    password: ${password}
    Hobbies: ${hobbies}
    Address: ${address}
</body>
</html>

Here we use the el expression to fetch the data.

  1. Run and view results

Part of the content here is borrowed from our blog. The author expresses his heartfelt thanks here.

Topics: SSM