Loading

[JavaWeb学习笔记]——Servlet

Servlet学习笔记

Servlet其实就一个运行在web服务器上的小的Java程序,用于处理从web客户端发送的请求,并且对请求作出响应。

使用

Servlet接口作为入门使用:

  1. 实现Servlet接口
  2. 在web.xml中配置实现类

实际编程中一般使用HttpServlet类:

学习参考:https://www.cnblogs.com/libingbin/p/5960456.html

​ SUN设计之初,是有野心,以后的互联网不仅仅只使用http协议,可以通过GenericSrvlet实现。HttpServlet是一个与协议相关的Servlet,是专门用来处理HTTP协议的请求。通常编写一个Servlet 一般都会让这个Servlet 继承Httpervlet 重写service方法。
​ 在service方法内部根据请求方式不同执行不同的doXXX的方法(get 请求执行doGet方法,如果是post请求就会执行doPost方法)。
​ 所以往往继承了HttpServlet 之后不需要重写service 方法,只需要重写doGet和doPost方法即可。往往请求要处理的内容的代码都是一致的,所以需要让doGet和doPost相互调用可以简化编程。

学习参考:https://www.cnblogs.com/isme-zjh/p/11820298.html

生命周期

英文文档介绍:

This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:

  1. The servlet is constructed, then initialized with the init method.
  2. Any calls from clients to the service method are handled.
  3. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.

ServletConfig对象

用来获得Servlet的相关的配置的对象

代码演示:

web.xml配置

<servlet>
    <servlet-name>ServletConfig</servlet-name>
    <servlet-class>servlet.demo.ServletConfig</servlet-class>
    
    <init-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>ServletConfig</servlet-name>
    <url-pattern>/config</url-pattern>
</servlet-mapping>

继承HTTPServlet的类:

public class ServletConfig extends HttpServlet {

    @Override
    public void init(jakarta.servlet.ServletConfig config) throws ServletException {
        super.init(config);
        System.out.println("初始化");
        System.out.println("程序别名:"+config.getServletName());
        System.out.println("初始化参数username的值:"+config.getInitParameter("username"));
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}

或者直接这样写

@WebServlet(name = "Servlet", urlPatterns = "/config",
        initParams = {
                @WebInitParam(name = "username", value = "root")
        }
)

public class ServletConfig extends HttpServlet {

    @Override
    public void init(jakarta.servlet.ServletConfig config) throws ServletException {
        super.init(config);
        System.out.println("初始化");
        System.out.println("程序别名:"+config.getServletName());
        System.out.println("初始化参数username的值:"+config.getInitParameter("username"));
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }
}

ServletContext对象

获取web项目信息

SeryletContext: Servlet 的上下文对象。ServletContext 对象对Servlet之前和之后的内容
都知道。这个对象-个web项目只有一一个。 在服务器启动的时候为每个web项目创建一-个
单独的ServletContext对象。

public class ServletContextDemo extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取文件的MIME的类型
        ServletContext servletContext = this.getServletContext();
        String mimeType = servletContext.getMimeType("aa.txt");
        System.out.println(mimeType);
        //获得请求路径的工程名
        String path = servletContext.getContextPath();
        System.out.println(path);
        //获取全局初始化参数
        String username = servletContext.getInitParameter("username");
        String password = servletContext.getInitParameter("password");
        System.out.println(username+"  "+password);

        Enumeration<String> names = servletContext.getInitParameterNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = servletContext.getInitParameter(name);
            System.out.println(name + "  " + value);
        }
    }

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

web.xml配置

注意<context>标签写在<servlet>外面

    <context-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </context-param>
    <context-param>
        <param-name>password</param-name>
        <param-value>123123</param-value>
    </context-param>

    <servlet>
        <servlet-name>ServletContext</servlet-name>
        <servlet-class>servlet.demo.ServletContextDemo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletContext</servlet-name>
        <url-pattern>/context</url-pattern>
    </servlet-mapping>

读取web项目下的文件

之前使用I0流就可以读取文件(java项目中)。现在是-个web项目, web项目需要发布到tomcat下才能访问的。获取web项目下的文件如果使用传统的10就会出现问题(原因:路径中使用的是相对路径,相对的是JRE环境)。

@WebServlet(name = "Servlet", urlPatterns = "/context")
public class ServletDemo extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Properties properties = new Properties();

        //创建一个文件的输入流
        InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/servlet/demo/db.properties");

//        String path = this.getServletContext().getRealPath("/WEB-INF/classes/servlet/demo/db.properties");
//        System.out.println(path);
//        InputStream is = new FileInputStream(path);

        properties.load(is);

        //获取数据
        String driverClassName = properties.getProperty("driverClassName");
        String url = properties.getProperty("url");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");

        System.out.println(driverClassName);
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
    }

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

域对象:

域对象:指的是将数据存入到域对象中,这个数据就会有一定的作用范围。域指的是一定的作用范围。

​ ServletContext是在服务器启动的时候为每个web项目单独创建一个ServletContext对象。当web项目从服务器中移除,或者是关闭服务器的时候ServletContext 对象会被销毁。向ServletContext中保存的数据一直存在 (当服务器关闭的时候SenvletContext对象被销毁,然后里面数据才会失效)。范围:整个web应用。

posted @ 2021-11-24 20:14  Masahiko  阅读(55)  评论(0)    收藏  举报