Java topic notes ~ Servlet programming

1. Servlet programming basics

(1) What is Servlet

Servlet is a web programming technology based on Java language. It is deployed in the web container on the server side, obtains the client's access request, and generates response information according to the request and returns it to the client.

The way to create a Servlet is

As shown in the figure below: Generally, creating a Servlet is achieved by inheriting HttpServlet, such as the HelloServlet in the figure.

(Shortcut key for class diagram: Ctrl + Alt + U)

 1. Create a Maven-based web project.

2. Create java and resources folders

3. Modify the version of web.xml

 

4. Import servlet dependencies

<!--servlet的依赖-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

 

(2) Servlet life cycle

init(): When the server starts and accesses the Servlet for the first time, the servlet is initialized

service(): During server startup, requests can be processed continuously.

destroy(): When the server stops, to destroy the Servlet.

(3) The main function of Servlet

(1) Read the explicit data (form data) sent from the client to the server

(2) Read the implicit data (request header) sent by the client to the server

(3) The server sends explicit data to the client (HTML)

(4) The server sends implicit data to the client (status code and response header)

 

2. Write the Servlet class

1. Generate static web pages through Servlet

package com.ambow.test;

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

/**
 *  作用:通过Servlet,动态生成HTML网页
 * @author foxbill
 * @date 2021/11/2 10:58
 */
@WebServlet(name = "FirstServlet")
public class FirstServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");//设置响应的字符集格式为UTF-8
        response.setContentType("text/html");//设置响应正文的MIME类型

        PrintWriter out = response.getWriter();//返回一个PrintWriter对象,Servlet使用它来输出字符串形式的正文数据
        out.println("<!doctype html>");
        out.println("<html>");
        out.println("<head><title>动态生成的HTML文档</title></head>");
        out.println("<body>");
        out.println("<table border='0' align='center'>");
        out.println("<tr><td bgcolor='skyblue' colspan=2>动态生成HTML文档</td></tr>");
        out.println("</table>");
        out.println("</body>");
        out.println("</html>");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

The relevant code of web.xml:

<servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>com.ambow.test.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/first</url-pattern>
</servlet-mapping>

 

2. Generate dynamic web pages through Servlet

package com.ambow.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalTime;

/**
 * @author foxbill
 * @date 2023/8/9 16:35
 */
@WebServlet(name = "TestServlet")
public class TestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //请求处理代码(功能:写一个动态网页)
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        LocalTime now = LocalTime.now();
        int hour = now.getHour();

        out.println("<!doctype html>");
        out.println("<html>");
        out.println("<head>");
        out.println("</head>");
        out.println("<body>");
        if (hour>0 && hour < 6){
            out.println("晚安!");
        }
        if (hour>=6 && hour <= 12){
            out.println("早安!");
        }
        if (hour>12){
            out.println("午安!");
        }
        out.println("</body>");
        out.println("</html>");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

The relevant code of web.xml:

<servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.ambow.test.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/test</url-pattern>
</servlet-mapping>

 

3. Write the web.xml configuration file

(1) Configure the virtual path

1. Servlet multiple mapping

method one:

<servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>com.ambow.test.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/first01</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/first02</url-pattern>
</servlet-mapping>

Method 2:

<servlet>
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>com.ambow.test.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
    <url-pattern>/first01</url-pattern>
    <url-pattern>/first02</url-pattern>
</servlet-mapping>

2. Wildcards are used in the mapping path, and there are two formats:

*.do: lowest priority

/*

<url-pattern>*.do</url-pattern>

<url-pattern>/*</url-pattern>

<url-pattern>/test/*</url-pattern>

3. Default Servlet: /

The default servlet is actually the servlet whose url is / in the servlet-mapping element. In the tomcat installation directory: there is such a code in web.xml under conf:

<servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

The role of the default Servlet is to process requests that cannot be matched by urls in servlet-mapping.

Accessing any resource on the web is accessing a Servlet. When accessing a static html file and picture in the tomcat service, it is actually accessing the default servlet.

If the web.xml under the web application does not have the url-pattern corresponding to 1.html, that is, there is no corresponding servlet, the server will run the default servlet, and the org.apache.catalina.servlets.DefaultServlet class corresponding to the servlet Read the data of the 1.html static page and display it on the page.

Comment out the above code, restart the tomcat server, enter http://localhost:8080 , and you will find that the pictures on the page will not be displayed, which is because of this reason.

Guess you like

Origin blog.csdn.net/qq_53142796/article/details/132194145