The Servlet,

1. Servlets run in Java-enabled application servers to interactively browse and modify data and generate dynamic Web content.

  • We are going to customize a Servlet and we have to implement the Servlet interface broadly
  • The Servlet interface has two implementation classes, and HttpServlet in turn inherits the GenericServlet class, both of which are abstract classes
    • GenericServlet
    • HttpServlet
  • We typically create JavaWeb projects based on the Http protocol, so creating servlets inherits httpservlets

2. Servlet working mode

  • The client sends the request to the server
  • The server starts and accepts the request sent by the client, invokes the corresponding Servlet to process the request, and generates the response content and passes it to the server
  • The server returns the response content to the client

3. Servlet lifecycle


public interface Servlet {
    void init(ServletConfig var1) throws ServletException;
 
    void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
 
    void destroy(a);
Copy the code
  • When a Servlet is first requested, the server calls the init() method to initialize a Servlet object, but this method is not called again in subsequent requests, only once. When this method is called, the Servlet container passes in a ServletConfig object to initialize the Servlet object.
  • Each time a client requests this Servlet, the Servlet container calls the service() method to handle the request; On subsequent requests, the Servlet container will only call this method.
  • When the server shuts down or stops, the Servlet container calls Destroy () to destroy the Servlet.
  • Each Servlet has only one Servlet object in the container, which is a singleton

4. ServletContext object

When the Web container is started, it creates a unique ServletContext object for each Web application, which represents the current Web application

Shared data

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Use ServletContext to share data
        ServletContext servletContext = this.getServletContext();
        servletContext.setAttribute("username"."Vecal");
    }

Copy the code
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Get shared data
        ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");

        resp.setContentType("text/html; charset=utf-8");
        resp.setCharacterEncoding("utf-8");

        resp.getWriter().print("Name:" + username);
    }
Copy the code
<! -- Configure Servlet mapping -->
<servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.vecal.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>get</servlet-name>
        <servlet-class>com.vecal.servlet.GetServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>get</servlet-name>
        <url-pattern>/get</url-pattern>
    </servlet-mapping>
Copy the code

Gets initialization parameters

<! -- Custom initialization parameters -->
<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
Copy the code
@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        String url = context.getInitParameter("url");
        resp.getWriter().print(url);
    }
Copy the code

Forward requests

// Request forwarding
ServletContext context = this.getServletContext();
context.getRequestDispatcher("/initParam").forward(req,resp);
Copy the code

Reading resource files

  • Create a new resource file in the Java directory

  • Create a new resource file under the Resources directory

All are packaged into the same directory: classes, collectively known as classpath: path

If you find that the resource files in the Java directory are not packaged in the classes directory, you need to do the following configuration in pom.xml

<build>
      <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>**/*.properties</exclude>
                <exclude>**/*.xml</exclude>
             </excludes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
Copy the code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Read the configuration file
        ServletContext context = this.getServletContext();
        InputStream in = context.getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties prop = new Properties();
        prop.load(in);

        String username = prop.getProperty("username");
        String password = prop.getProperty("password");

        resp.getWriter().print(username + ":" + password);
    }
Copy the code

5, HttpServletResponse

When the Web server receives the HTTP request from the client, it creates an HttpServletRequest object representing the request and an HttpServletResponse object representing the response

  • To get some of the data parameters of a client request, use HttpServletRequest
  • To respond with some data to the client, use HttpServletResponse

1. Send data to the browser

ServletOutputStream getOutputStream(a) throws IOException;

PrintWriter getWriter(a) throws IOException;
Copy the code

2. Set the response header

void setCharacterEncoding(String var1);

void setContentLength(int var1);

void setContentLengthLong(long var1);

void setContentType(String var1);
Copy the code

3. Response status code

int SC_OK = 200;
int SC_FOUND = 302;
int SC_BAD_REQUEST = 400;
int SC_INTERNAL_SERVER_ERROR = 500;
Copy the code

4. Download the file

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. Obtain the image path
        String realPath = "D:\\How2JTest\\project\\ Javaweb-02 -servlet\\ Response \\target\\ Response \ web-INF \classes\\;
        // 2. Obtain the file name
        String fileName = realPath.substring(realPath.lastIndexOf("/") + 1);
        System.out.println("File download path:" + realPath);
        // 3. Set the response header,URLEncoder. Encode () to handle the filename Chinese garble problem
        response.setHeader("Content-Disposition"."attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
        // 4. Get the file stream
        FileInputStream in = new FileInputStream(realPath);
        // 5. Set the buffer
        int len = 0;
        byte[] buffer = new byte[1024];

        // 6. Write the file
        ServletOutputStream os = response.getOutputStream();
        while((len = in.read(buffer)) ! = -1){
            os.write(buffer, 0, len);
        }

        os.close();
        in.close();
    }
Copy the code

5. Implement redirection

  • The URL address bar will change
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
    // The request is redirected and the URL bar is changed
    response.sendRedirect("/r/down");
}
Copy the code

6, it

HttpServletRequest represents a client request. The user accesses the server through THE HTTP protocol, and the HTTP server encapsulates all the request information into this object.

1. Obtain parameters passed by the front-end

// Gets an argument with the specified name
String getParameter(String var1);
// Get multiple arguments with the specified name
String[] getParameterValues(String var1);
Copy the code

7. The difference between request and forward

Interview question: Can you talk about the difference between forwarding and redirecting?

Similarities:

  • The page jumps

Difference:

  • The URL address bar does not change when a request is forwarded
  • The URL address bar changes when the request is redirected