Servlet common class analysis

content

Implementing Servlet Programs by Inheriting HttpServlet

 Use idea to create servlet program

Servlet inheritance system

 doGet and dopost source code

 servlet method part of the source code

ServletConfig class

Three functions of the ServletConfig class

ServletContext class

What is ServletContext?

What is a domain object?

Comparison chart:

Four functions of the ServletContext class

1. Get the context parameters of the configuration in web.xml,

 Error prone:

Get the current project path

Get the absolute path on the server's hard drive after deployment

Access data like a map


Implementing Servlet Programs by Inheriting HttpServlet

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

step:

1. Write a class to inherit the HttpServlet class

2. Rewrite the doGet or doPost method according to business needs

3. Configure the servlet program in web.xml

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

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的 get请求");
    }

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

Configure the access path in the web.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 hello2

After running submit:

 Use idea to create servlet program

Select the package to be implemented → Servlet program

 configuration information

Check the annotation configuration of 3.0 

 Just add the path to web.xml (others have been automatically generated)

    <servlet-mapping>
        <servlet-name>HelloServlet3</servlet-name>
        <url-pattern>/hello3</url-pattern>
    </servlet-mapping>

Servlet inheritance system

 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);
                }
            }
        }

ServletConfig class

  • ServletConfig is the configuration information class of servlet program.
  • Servlet programs and ServletConfig objects are created by Tomcat, and we are responsible for using them.
  • Servlet programs are created by default when they are accessed once. ServletConfig is created when each servlet program is created, and a corresponding ServletConfig object is created.

Three functions of the ServletConfig class

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

2. Get the initialization parameter init-param

3. Get the ServletContent object

Location init method

1. Get the servlet alias

  public void init(ServletConfig servletConfig) throws ServletException {
         System.out.println("HelloServlet 的别名是"+servletConfig.getServletName()); 
  }

2. Get the initialization parameter init-param, thank you for the others

Now configure <init-param> in the web.xml file

<!--servlet标签给Tomcat配置Servlet程序-->
    <servlet>
        <!-- servlet-name给Servlet程序起一个别名(一般别名起为类名)-->
        <servlet-name>HelloServlet</servlet-name>
        <!--servlet-class是Servlet程序的全类名 -->
        <servlet-class>com.servlet.HelloServlet</servlet-class>

        <!--init-param时初始化参数,这是个键值对可以写很多对 -->
        <init-param>
            <!-- 参数名-->
            <param-name>username</param-name>
            <!--是参数的值 -->
            <param-value>root</param-value>
        </init-param>
        <init-param>
        <!-- 参数名-->
        <param-name>url</param-name>
        <!--是参数的值 -->
        <param-value>jdbc:mysql://localhost:3306/text</param-value>
        </init-param>
    </servlet>

Under init() in the class implementing the Servlet interface

  // 2、获取初始化参数init-param
        System.out.println("初始化参数username的值是"+servletConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是"+servletConfig.getInitParameter("url"));

3. Get the ServletContent object

 // 3、获取ServletContent对象
        System.out.println("servletcontent对象是"+servletConfig.getServletContext());

The result of the above operation:

Each ServletConfig program is independent, and the information in each class in web.xml is not shared,

When overriding the init method, super.init(config) must be added, and the init initialization method of the parent class must be accessed, 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 rewrite 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)

ServletContext class

What is ServletContext?

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

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

3. The ServletContent object is a domain object.

4. Created after the web project starts, and destroyed after the web project ends

What is a domain object?

Domain objects are objects that can access data like a Map, and are called domain objects.

The domain here refers to the scope of operations for accessing data.

Comparison chart:

save data fetch data delete data
Map put() get() remove()
domain object setAttribute() getAttribute() removeAttribute()

Four functions of the ServletContext class

1. Get the context parameter context-param of the configuration in web.xml

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

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

4. Access data like a Map

Create a class ContextServlet with a shortcut, configure the path in web.xml (the rest is auto-generated)

    <servlet>
        <servlet-name>ContextServlet</servlet-name>
        <servlet-class>com.servlet.ContextServlet</servlet-class>
    </servlet>
<!-- 上面自动生成了,下面要自己书写的路径-->
    <servlet-mapping>
        <servlet-name>ContextServlet</servlet-name>
        <url-pattern>/contextServlet</url-pattern>
    </servlet-mapping>

1. Get the context parameters of the configuration in web.xml,

First, you have to configure context-param in web.xml (usually written on top of other servlets)

<!--context-param是上下文参数(他属于整个web工程)-->
    <context-param>
        <!--参数名 -->
        <param-name>username</param-name>
        <!--参数值-->
        <param-value>context</param-value>
    </context-param>
<!--可以写多对上下文参数-->
    <context-param>
        <param-name>password</param-name>
        <param-value>root</param-value>
    </context-param>

In the doGet() method in the ContextServlet class

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1、获取web.xml中的配置的上下文参数context-param
        //获取对象
        ServletContext context = getServletConfig().getServletContext();
        String username = context.getInitParameter("username");
        String password = context.getInitParameter("password");
        System.out.println("context-param参数username的值是"+username);
        System.out.println("context-param参数password的值是"+password);
    }
}

The result after running is: 

 Error prone:

①: Do not forget the / slash in the address in the configuration web.xml file, otherwise the address will be reported invalid

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

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

Get the current project path

     System.out.println("当前工程路径:"+context.getContextPath());

Get the absolute path on the server's hard drive after deployment


System.out.println("获取工程部署的路径"+context.getRealPath("/"));

 This slash / indicates the path to the current project

Access data like a map

Create a Servlet class and configure the path in the web.xml file

   <servlet>
        <servlet-name>ContextServlet1</servlet-name>
        <servlet-class>com.servlet.ContextServlet1</servlet-class>
    </servlet>
<!-- 以上自动配好-->
  <servlet-mapping>
        <servlet-name>ContextServlet1</servlet-name>
        <url-pattern>/contextServlet1</url-pattern>
    </servlet-mapping>

In the class:

public class ContextServlet1 extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //获取ServletContext对象
        ServletContext context = getServletContext();
        System.out.println("保存之前Context获取key1的值是:"+context.getAttribute("key1"));
        context.setAttribute("key1","value1");
        System.out.println("context获取数据key1的值为:"+context.getAttribute("key1"));
    }
}

We can get the object directly with getServletContext(), which is simpler, instead of getServletConfig().getServletContext();

We can see the source code with ctrl+b:

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

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

We 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中 context获取数据key1的值为:"+context.getAttribute("key1"));
    }
}

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. The data under the context can also be shared data

 

 The ContextServlet object is created after the web project starts, destroyed after the web project ends, and shared

Restarting and redeploying will result in the destruction of the web project

 The addresses of ContextServlet1 and 2 are also the same

Guess you like

Origin blog.csdn.net/weixin_60719453/article/details/122733989