ServletContext接口详解

发布时间:2023-05-23 09:33:44

1.什么是Servletcontext?14

*Servletcontext是Servlet规范的接口之一。

2.谁实现了Servletcontext?14

*实现Servletcontext接口的Tomcat服务器(WEB服务器)。

*publicclassorg.apache.catalina.core.ApplicationContextFacadeimplementsServletContext{}

3.谁创建了Servletcontext对象?什么时候创建?14

*WEB服务器启动时创建Servletcontext对象。

*WEB服务器创建了Servletcontext对象。

*Servletcontext对象只有一个webapp。

*服务器关闭时,Servletcontext对象被销毁。

4.如何理解Servletcontext?14

*context是什么意思?

*Servlet对象的环境对象。(Servlet对象的上下文对象。)

*Servletcontext对象实际上对应于整个web.xml文件。

*50个学生,每个学生都是Servlet,这50个学生都在同一个教室。那么这个教室就相当于Servletcontext的对象。

*所有Servlet必须共享ServletContext对象中的数据。

*比如教室里的空调是所有学生共享的,教室里的语文老师是所有学生共享的。

*Tomcat是一个容器,多个webapp可以放在一个容器中,一个webapp对应一个servletcontext对象。

4.1Servlet小总结15

Servlet对应Servletconfig。100个Servlet对象对应100个Servletconfig对象。

-只要在同一个webapp中,只要在同一个应用中,所有Servlet对象都共享同一个Servletcontext对象。

-在服务器启动阶段创建Servletcontext对象,在服务器关闭时销毁。这就是Servletcontext对象的生命周期。Servletcontext对象是应用级对象。

-Tomcat服务器中有一个webaps,可以存储webapp和多个webapp。假设有100个webapp,那么就有100个servletcontext对象。然而,简而言之,一个应用程序,一个webapp必须只有一个servletcontext对象。

-Servletcontext被称为Servlet的上下文对象。(Servlet对象周围的环境对象。)

-Servletcontext对象通常对应于web.xml文件。

4.2Servletcontext显示了生活中的哪些例子?15

-一个教室里有很多学生,所以每个学生都是同一个教室里的Servlet,所以我们可以称这个教室为Servletcontext对象。也就是说,Servletcontext对象(环境)中的数据在同一个教室中共享。例如,教室里有一台空调,所有的学生都可以操作。可见,空调是共享的。因为教室里有空调。教室是Servletcontext的对象。

-servletcontext是一个接口,tomcat服务器实现了servletcontext接口。

-Tomcat服务器也完成了Servletcontext对象的创建。创建webapp时。

5.Servletcontext接口中常用的方法有哪些?155.1getInitParameter(Stringname)和getinitparameternames()

publicStringgetInitParameter(Stringname);///通过初始参数的name获得value

getInitParameterNames();////name获取所有初始化参数

   <context-param>        <param-name>pageSize</param-name>        <param-value>10</param-value>    </context-param>    <context-param>        <param-name>startIndex</param-name>        <param-value>0</param-value>    </context-param>
5.2getContextPath()获取应用的根路径15

获取应用程序的根路径(非常重要),因为java源代码中有一些地方可能需要应用程序的根路径,该方法可以动态获取应用程序的根路径

在java源码中,不要写下应用程序的根路径,因为当最终部署时,您永远不知道该应用程序的名称。

publicStringgetContextPath();

StringcontextPath=application.getContextPath();

5.3getRealPath(Stringpath)获取文件的绝对路径15

获取文件的绝对路径(真实路径)

publicStringgetRealPath(Stringpath);

5.4log()记录日志15

也可以通过Servletcontext对象记录日志

publicvoidlog(Stringmessage);

publicvoidlog(Stringmessage,Throwablet);

这些日志信息记录在哪里?

localhost.2021-11-05.log

tomcat服务器logs目录下有哪些日志文件?

catalina.2021-11-05.Java程序在log服务器端运行的控制台信息。

localhost.2021-11-05.logServletcontext对象log方法记录的日志信息存储在本文件中。

localhost_access_log.2021-11-05.txt访问日志

5.5servletcontext对象还有另一个名称:应用域16

Servletcontext对象还有另一个名称:应用域(后面还有其他域,比如请求域和会话域)

如果所有用户共享一个数据,而且这个数据很少修改,而且这个数据很少,那么这些数据可以放在Servletcontext应用域中

为什么所有用户共享数据?不共享是没有意义的。因为Servletcontext只有一个对象。只有放入共享数据才有意义。

为什么数据量很小?因为如果数据量相对较大,则过于占用堆内存,而且对象的生命周期相对较长。当服务器关闭时,对象将被销毁。大数据量会影响服务器的性能。可以考虑放置占用内存较小的数据量。

为什么这些共享数据很少修改,或者几乎没有修改?

如果所有用户共享的数据都涉及到修改操作,线程并发带来的安全问题是不可避免的。因此,ServletContext对象中的数据通常只被阅读。

数据量小,所有用户共享,不修改。将此类数据放入Servletcontext应用域将大大提高效率。由于应用域相当于缓存中的数据,因此下次使用时无需从数据库中再次获取,大大提高了执行效率。

//存储(如何将数据存储到Servletcontext应用域)

publicvoidsetAttribute(Stringname,Objectvalue);//map.put(k,v)

//取(如何从Servlecontex应用域取数据)span>

publicObjectgetAttribute(Stringname);//Objectv=map.get(k)

//删除(如何删除Servletcontext应用域的数据)

publicvoidremoveAttribute(Stringname);//map.remove(k)

com中的代码.bjpowernode.javaweb.servletAServlet
package com.bjpowernode.javaweb.servlet;import jakarta.servlet.*;import java.io.IOException;import java.io.PrintWriter;import java.util.Enumeration;//Servletcontext接口详细说明   14-15publiclic class AServlet extends GenericServlet {    @Override    public void service(ServletRequest request, ServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();        ///获得Servletcontext对象        ServletContext application = this.getServletContext();        ///输出结果        ///Servletcontext对象为:org.apache.catalina.core.ApplicationContextFacade@59363a65        out.print(Servletcontext对象为:"+application);        out.print("");        ///获取上下文的初始参数   15        Enumeration initParameterNames = application.getInitParameterNames();        //遍历        while(initParameterNames.hasMoreElements(){///判断是否有更多的元素            String name = initParameterNames.nextElement();//取元素            String value = application.getInitParameter(name);            out.print(name+" = "+value+"");        }        //获得contextet path(获取应用的上下文根)   15        String contextPath = application.getContextPath();        out.print(contextPath+"");//   /servlet04        //获取index.html文件的绝对路径  15        // 后面的路径,加一个“/”,这个“/”代表web的根        //String realPath = application.getRealPath("/index.html");//可以        String realPath = application.getRealPath("index.html");//不加“/”也可以        //E:\java学习javaWeb\course\course8out\artifacts\course8_war_exploded\index.html        out.print(realPath);        out.print("");        ///common目录下的common.html文件的绝对路径  15        String realPath1 = application.getRealPath("/common/common.html");        //E:\java学习javaWeb\course\course8out\artifacts\course8_war_exploded\common\common.html        out.print(realPath1+”;        //记录日志log()   15        // 这个日志会自动记录在哪里?        // CATALINA_HOME/logs目录下。        // CATALINA_HOME/logs目录下。        //application.log(大家好,我是动力节点杜老师,欢迎大家和我一起学习Servlet规范!");        application.log(“你好中国”);        //log还可以记录异常日志        int age = 17; // 17岁        // 当年龄小于18岁时,表示非法,记录日志        if(age < 18) {            application.log(对不起,您未成年,请绕行!"                    , new RuntimeException(小屁孩,快走开,不适合你!"));        }        ///Servletcontext对象还有另一个名称:应用域   16        //如果所有用户共享一个数据,而且这个数据很少修改,        // 而且这个数据量很少,这些数据可以放在Servletcontext的应用域中        //准备数据        User user = new User("jack","123");        ///存储数据(存储USER对象)到Servletcontext应用域        application.setAttribute("userObj",user);        //取出来        Object userObj = application.getAttribute("userObj");        //打印到浏览器        out.print(userObj+"");//User{name='jack', password='123'}    }}
BServlet
package com.bjpowernode.javaweb.servlet;import jakarta.servlet.*;import java.io.IOException;import java.io.PrintWriter;//Servletcontext接口详细说明   14public class BServlet extends GenericServlet {    @Override    public void service(ServletRequest request, ServletResponse response)            throws ServletException, IOException {        response.setContentType("text/html");        PrintWriter out = response.getWriter();        ///获得Servletcontext对象        ServletContext application = this.getServletContext();        ///输出结果        ///Servletcontext对象为:org.apache.catalina.core.ApplicationContextFacade@59363a65        out.print(Servletcontext对象为:"+application);        out.print("");        ///Servletcontext对象还有另一个名称:应用域   16        ///取出AServlet存储的USer对象共享资源    16        Object userObj = application.getAttribute("userObj");        //打印到浏览器        out.print(userObj+"");//User{name='jack', password='123'}    }}
User类,验证应用域
package com.bjpowernode.javaweb.servlet;public class User {    private String name;    private String password;    public User() {    }    public User(String name, String password) {        this.name = name;        this.password = password;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    @Override    public String toString() {        return "User{" +                "name='" + name + '\'' +                ", password='" + password + '\'' +                '}';    }}
web配置文件.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"         xmlns:xsi="https://www.tulingxueyuan.cn/d/file/p/20230523/q0zqiwyv2u4"         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"         version="4.0"><!--    上下文的初始参数,以及这些配置信息,Servletcontext对象可以获得-->    <context-param>        <param-name>pagesize</param-name>        <param-value>10</param-value>    </context-param>    <context-param>        <param-name>startIndex</param-name>        <param-value>0</param-value>    </context-param><!--    这是AServletweb配置信息-->    <servlet>        <servlet-name>aservelt</servlet-name>        <servlet-class>com.bjpowernode.javaweb.servlet.AServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>aservelt</servlet-name>        <url-pattern>/a</url-pattern>    </servlet-mapping><!--    这是BServletweb配置信息-->    <servlet>        <servlet-name>bservelt</servlet-name>        <servlet-class>com.bjpowernode.javaweb.servlet.BServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>bservelt</servlet-name>        <url-pattern>/b</url-pattern>    </servlet-mapping></web-app>
index.html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>common html</title></head><body><h1>common data</h1></body></html>
common.html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>common html</title></head><body><h1>common data</h1></body></html>
6.重点16

注:以后写Servlet的时候,其实不会直接继承GenericServlet,因为我们是B/S结构的系统,是基于HTTP超文本传输协议的。在Servlet规范中,提供了一个叫做HTTPServlet的类别,是专门为HTTP协议准备的Servlet类别。我们编写的Servlet类别将继承HttpServlet。(HTTPServlet是HTTP协议专用的。)HTTTP协议更方便使用HTTPServlet处理。但是你需要直到它的继承结构:

jakarta.servlet.Servlet(接口)【爷爷】

jakarta.servlet.GenericServletimplementsServlet(抽象)[儿子]

jakarta.servlet.http.HttpServletextendsGenericServlet(抽象)[孙子]

将来我们编写的Servlet将继承HttpServlet。

上一篇 使用接口进行衔接
下一篇 TCP网络通信编程+netstat

文章素材均来源于网络,如有侵权,请联系管理员删除。

标签: Java教程Java基础Java编程技巧面试题Java面试题