Java Web (5) – servlet details (Part I)

1、 Servlet

1. What is a servlet

2. Manually implement the servlet program

First, create a corresponding module in the idea. See the previous one for details. The results are as follows

1. First, create a java file under SRC, implement the servlet interface and rewrite the method

Now let's look at servlet (), and omit others

package com.md.servlet;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author MD
 * @create 2020-07-24 14:44
 */
public class HelloServlet implements Servlet {

    /**
     * service方法专门用来处理请求和响应的
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest,ServletResponse servletResponse) throws ServletException,IOException {
        System.out.println("Service方法");
    }
}

2. web. XML. The specific parameters are as follows:

<?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标签给Tomcat配置Servlet程序-->
    <servlet>
        <!--给servlet程序起一个别名,通常是类名-->
        <servlet-name>HelloServlet</servlet-name>
        <!--servlet程序全类名-->
        <servlet-class>com.md.servlet.HelloServlet</servlet-class>
    </servlet>


    <!--servlet-mapping标签给servlet程序配置访问地址-->
    <servlet-mapping>
        <!--servlet-name 作用是告诉服务器,当前配置的地址给那个Servlet程序使用-->
        <servlet-name>HelloServlet</servlet-name>
        <!-- 配置访问的地址 http://ip:port/hello , 可以自定义-->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
</web-app>

When accessing address http://localhost:8080/hello You can see the output statement

3. URL address to servlet program

4. Servlet declaration cycle

The first and second steps are to create a servlet during the first access, and the program will call

package com.md.servlet;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author MD
 * @create 2020-07-24 14:44
 */
public class HelloServlet implements Servlet {

    public HelloServlet() {
        System.out.println("1 构造器方法");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2 init初始化方法");
    }

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

    /**
     * service方法专门用来处理请求和响应的
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest,IOException {
        System.out.println("3. service方法");
    }


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

    @Override
    public void destroy() {
        System.out.println("4 destroy销毁方法");
    }
}

// 结果如下:
//1 构造器方法
//2 init初始化方法     只有第一次访问执行
//3. service方法
//3. service方法      每次刷新都会执行这个方法
//4 destroy销毁方法    关闭Tomcat会执行这个方法

4. Distribution and processing of get and post requests

At this time, the service () method will be executed no matter whether the get or post request is executed. This is inconvenient, so the following improvements are made,

Other methods are omitted, mainly focusing on service ()

public class HelloServlet implements Servlet {

    @Override
    public void service(ServletRequest servletRequest,IOException {
        System.out.println("3. service方法");

        // 1. 类型转换
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        // 2. 获取请求的方式
        String method = httpServletRequest.getmethod();

        // 3. 处理不同的请求
        if ("GET".equals(method)){
            doGet();
        }else if ("POST".equals(method)){
            doPost();
        }

    }

    /**
     * 做get请求的操作
     */
    public void doGet(){
        System.out.println("get请求正在操作");
    }

    /**
     * 做post请求的操作
     */
   public void doPost(){
       System.out.println("post请求正在操作");
   }
}

5. Implement servlet program by inheriting httpservlet

Generally, in the actual project development, the servlet program is implemented by inheriting the httpservlet class

Code in the servlet class

package com.md.servlet;

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

/**
 * @author MD
 * @create 2020-07-24 15:25
 */
public class HelloServlet2 extends HttpServlet {

    /**
     * get请求时调用
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
        System.out.println("HelloServlet2 --- get");
    }

    /**
     * post请求时调用
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req,IOException {
        System.out.println("HelloServlet2 --- post");
    }
}

On the web Configuration in XML

<servlet>
        <servlet-name>HelloServlet2</servlet-name>
        <servlet-class>com.md.servlet.HelloServlet2</servlet-class>
 </servlet>


    <servlet-mapping>
        <servlet-name>HelloServlet2</servlet-name>
        <url-pattern>/hello2</url-pattern>
    </servlet-mapping>

6. Create a servlet program using idea

Convenient and fast

Configure servlet information

Finally, on the web Just add information to XML

<servlet>
        <servlet-name>HelloServlet3</servlet-name>
        <servlet-class>com.md.servlet.HelloServlet3</servlet-class>
 </servlet>
    
    <servlet-mapping>
        <servlet-name>HelloServlet3</servlet-name>
        <url-pattern>/hello3</url-pattern>
    </servlet-mapping>

7. Inheritance system of servlet class

2、 ServletConfig class

ServletConfig is the configuration information class of the servlet program

Both the servlet program and the ServletConfig object are created by Tomcat and used by us

By default, servlet programs are created during the first access. ServletConfig is a corresponding ServletConfig object created when each servlet program is created

1. Three functions of ServletConfig class

The first is on the web XML

  <!--servlet标签给Tomcat配置Servlet程序-->
    <servlet>
        <!--给servlet程序起一个别名,通常是类名-->
        <servlet-name>HelloServlet</servlet-name>
        <!--servlet程序全类名-->
        <servlet-class>com.md.servlet.HelloServlet</servlet-class>

        <!--初始化参数-->
        <init-param>
            <!--参数名-->
            <param-name>url</param-name>
            <!--参数值-->
            <param-value>jdbc:MysqL://localhost:3306/test</param-value>
        </init-param>
        <!--可以配置多个-->
        <init-param>
            <!--参数名-->
            <param-name>username</param-name>
            <!--参数值-->
            <param-value>root</param-value>
        </init-param>
    </servlet>
  <!--servlet-mapping标签给servlet程序配置访问地址-->
    <servlet-mapping>
        <!--servlet-name 作用是告诉服务器,当前配置的地址给那个Servlet程序使用-->
        <servlet-name>HelloServlet</servlet-name>
        <!-- 配置访问的地址 http://ip:port/hello , 可以自定义-->
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    

Code in servlet:

Other methods are omitted. Just look at this. After starting tomcat, enter the address in the address bar http://localhost:8080/hello You can see the output statement,

@Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2 init初始化方法");

        // 1. 可以获取Servlet程序的别名servlet-name的值
        System.out.println("HelloServlet的别名是:"+servletConfig.getServletName());
        //HelloServlet的别名是:HelloServlet

        // 2. 获取初始化参数init-param
        System.out.println("初始化参数url:"+servletConfig.getInitParameter("url"));
        //初始化参数url:jdbc:MysqL://localhost:3306/test
        System.out.println("初始化参数username:"+servletConfig.getInitParameter("username"));
        //初始化参数username:root

        // 3. 获取ServletContext对象
         System.out.println(servletConfig.getServletContext());
        //org.apache.catalina.core.ApplicationContextFacade@521f9e31

    }

be careful:

When overriding the init method, you must call the init (config) operation of the parent class

@Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        System.out.println("重写的init方法");
    }

3、 ServletContext class

1. What is ServletContext?

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, the whole web project

2. Four functions of ServletContext class

In the contextservlet class,

package com.md.servlet;

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

/**
 * @author MD
 * @create 2020-07-24 16:17
 */
public class ContextServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {

    }

    protected void doGet(HttpServletRequest request,IOException {

        // 1. 获取web.xml中配置的上下文参数
        ServletContext context = getServletConfig().getServletContext();
        String username = context.getInitParameter("username");
        System.out.println("context-param中参数username的值为:"+username);
        System.out.println("context-param中参数pwd的值为:"+context.getInitParameter("pwd"));


        // 2. 获取当前工程的路径
        System.out.println("当前工程的路径:"+context.getContextPath());



        // 3. 获取工程部署后在服务器磁盘上的绝对路径,映射到IDEA代码的web目录,
        // 相当于直接到了web目录那,如果使用web目录下的其他文件,直接/目录名就可以

        System.out.println("工程部署路径:"+context.getRealPath("/"));
        // 工程的绝对路径:E:\Java\code\JavaWeb\out\artifacts\03_web_war_exploded\


        // 比如web下有css目录和imgs目录
        System.out.println(context.getRealPath("/css"));
        System.out.println(context.getRealPath("/imgs/1.jpg"));

    }
}

Corresponding configuration file web xml

This is directly under the < web app tag, not under a < servlet tag,

  <!--context-param 是上下文参数,属于整个的Web工程-->
    <context-param>
        <param-name>username</param-name>
        <param-value>context</param-value>
    </context-param>

    <context-param>
        <param-name>pwd</param-name>
        <param-value>123456</param-value>
    </context-param>

  <servlet>
        <servlet-name>ContextServlet</servlet-name>
        <servlet-class>com.md.servlet.ContextServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ContextServlet</servlet-name>
        <url-pattern>/context</url-pattern>
    </servlet-mapping>

ServletContext accesses data like a map. You can do this directly

In contextservlet1, the corresponding web XML is omitted

package com.md.servlet;

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

/**
 * @author MD
 * @create 2020-07-24 16:40
 */
public class ContextServlet1 extends HttpServlet {
    protected void doPost(HttpServletRequest request,IOException {

        // 1. 通过getServletContext()直接获取ServletContext对象
        ServletContext context = getServletContext();


        System.out.println("保存前:"+context.getAttribute("key1")); // null
        // 2. 设置值
        context.setAttribute("key1","value1");

        // 3. 获取值
        System.out.println("保存后:"+context.getAttribute("key1")); //value1

        // 

    }
}

It can also be obtained in different services because it is a domain object

This value can be obtained by the whole web, and it can also be obtained through contextservlet2

public class ContextServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request,IOException {
    }

    protected void doGet(HttpServletRequest request,IOException {

    // 由于context是域对象,整个web只有一个,所以这个获取的和ContextServlet1里的是同一个
        ServletContext context = getServletContext();
        // 只要ContextServlet1运行过,设置过这个值,那么这个就可以获取到值
        System.out.println(context.getAttribute("key1")); //value1
    }
}

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>