ServletContext对象

Java知识点总结:想看的可以从这里进入

3.5、ServletContext

ServletContex是 servlet上下文,是一个代表了整个项目的对象,全局唯一,项目内部所有servlet都能共享这个对象中保存的数据所以 ServletContext 又叫全局应用程序共享对象。
在这里插入图片描述
ServletContext对象在服务器启动的时候创建,服务器关闭的时候销毁。它共用四种获取方式

//第一种。 通过 GenericServlet 提供的 getServletContext() 方法
ServletContext servletContext = this.getServletContext();
//第二种。通过 ServletConfig 提供的 getServletContext() 方法
ServletContext servletContext = this.getServletConfig().getServletContext();
//第三种。通过 HttpSession 提供的 getServletContext() 方法
ServletContext servletContext = req.getSession().getServletContext();
//第四种。通过 HttpServletRequest的 getServletContext() 方法
ServletContext servletContext = req.getServletContext();

ServletContext的作用:

  1. 在各个 servlet 间实现全局数据共享

  2. 获取web.xml配置的上下文参数context-param

  3. 获取项目路径,读取 Web 应用下的资源文件

3.5.1 数据共享

因为ServletContext的全局性,所以可以在Servlet之间共享数据

方 法说 明
Object getAttribute(String attributeName)获取 attributeName(属性名称)对应的 object
void setAttribute(String attributeName, Object object)将object保存到ServletContext中
Enumeration getAttributeNames()返回 application 对象中所有的 attributeName
void removeAttribute(String objectName)删除 application 对象中指定 attributeName 的属性
String getServerInfo()获取当前 Servlet 的版本信息
public class Test1Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Userinfo userinfo = new Userinfo("张三","123456");
        //获取context将对象userinfo保存进去
        ServletContext context = request.getServletContext();
        context.setAttribute("userinfo",userinfo);
    }
}

public class Test2Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext context = request.getServletContext();
        //从context对象中获取userinfo
        Userinfo userinfo = (Userinfo) context.getAttribute("userinfo");
        System.out.println("username:"+userinfo.getUsername());
        //获取所有的attributeName
        Enumeration<String> attributeNames = context.getAttributeNames();
        while (attributeNames.hasMoreElements()){
            System.out.println(attributeNames.nextElement());
        }
        //移除userinfo对象
        context.removeAttribute("userinfo");
        Userinfo userinfo1 = (Userinfo) context.getAttribute("userinfo");
        if(userinfo1 == null){
            System.out.println("移除成功");
        }
    }
}

在这里插入图片描述

3.5.2 上下文参数

获取在XML文件中上下文初始化的参数

方 法说 明
Enumeration getInitParameterNames()获取所有的param-name
String getInitParameter(paramName)根据param-name获取相应值
<?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">
  <!--初始化参数设置-->
  <context-param>
    <param-name>name</param-name>
    <param-value>yu</param-value>
  </context-param>
  <context-param>
    <param-name>gender</param-name>
    <param-value></param-value>
  </context-param>
</web-app>
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();

    //获取ServletContext对象
    ServletContext servletContext = this.getServletContext();
    //获取全局param-name
    Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
    while (initParameterNames.hasMoreElements()){
        String paramName = initParameterNames.nextElement();
        String paramValue = servletContext.getInitParameter(paramName);
        out.write("param-name:"+paramName+".paramValue:"+paramValue+"<br/>");
    }
    out.close();
}

在这里插入图片描述

3.5.3 页面转发

访问Test1Servlet时会将页面转发到指定的转发路径,访问路径不会改变,但是会显示转发后的页面

public class Test1Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       response.setContentType("text/html;charset=utf-8");
       request.setCharacterEncoding("utf-8");
		//获取ServletContext对象
        ServletContext context = this.getServletContext();
        //设置需要转发的路径
        RequestDispatcher requestDispatcher = context.getRequestDispatcher("/Test2Servlet");
        //开始转发
        requestDispatcher.forward(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
3.5.4、项目路径

因为是使用的Tomcat部署项目,我们的项目随然显示在idea 的路径中,但实际上还是部署到了Tomcat的webapps中了,如果直接在代码中写相对、绝对路径,很可能会导致找不到文件,而直接写磁盘路径的话,在更换服务器后一样会出现找不到资源的情况,所以ServletContext提供了getRealPath()获取项目路径,这样不管再怎么更换服务器都能获取到正确的路径。

  • 根据项目内文件的相对路径获取绝对路径:context.getRealPath(“文件相对路径”);
  • 返回webapp目录下的类目录列表,指示子目录路径的路径以/结尾。:getResourcePaths(String path)
  • 返回映射到资源文件的 URL 对象(该路径必须以/开头):getResource(String path)
  • 根据相对路径获取服务器上资源的输入字节流:getResourceAsStream(path)
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");

    PrintWriter out = response.getWriter();
    //获取ServletContext对象
    ServletContext servletContext = this.getServletContext();
    String realPath = servletContext.getRealPath("index.xml");
    out.write("获取的路径:"+realPath+"</br>");
    Set<String> servlet = servletContext.getResourcePaths("/");
    out.write("获取的web资源:");
    servlet.forEach(s -> out.write(s+","));
    out.write("</br>");
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
ServletContextJava Web中的一个重要对象,表示整个Web应用程序的上下文环境。它是一个接口,提供了许多方法,用于获取Web应用程序的相关信息,例如应用程序的名称、版本、servlet上下文参数、初始化参数等。 以下是ServletContext对象的一些常用方法和用法: 1. 获取应用程序的名称和版本: String appName = context.getServletContextName(); //获取应用程序名称 String appVersion = context.getMajorVersion() + "." + context.getMinorVersion(); //获取应用程序版本号 2. 获取servlet上下文参数: String paramValue = context.getInitParameter("paramName"); //获取指定参数的值 Enumeration<String> paramNames = context.getInitParameterNames(); //获取所有参数名称 3. 获取应用程序的真实路径: String realPath = context.getRealPath("/"); //获取应用程序的根目录真实路径 4. 获取应用程序的资源: InputStream input = context.getResourceAsStream("/path/to/resource"); //获取指定资源的输入流 URL resourceUrl = context.getResource("/path/to/resource"); //获取指定资源的URL 5. 获取应用程序的Servlet信息: ServletInfo info = context.getServletInfo(); //获取Servlet的信息 6. 获取应用程序的Session管理器: HttpSessionManager sessionMgr = context.getSessionManager(); //获取Session管理器 7. 获取应用程序的Mime类型: String mimeType = context.getMimeType("fileName"); //获取指定文件的Mime类型 8. 获取应用程序的Servlet上下文: ServletContext servletContext = context.getContext("/path/to/servlet"); //获取指定Servlet的上下文 总之,ServletContext对象提供了一种方便的方式来获取Web应用程序的各种信息和资源,使得开发人员可以更方便地开发和管理Web应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辰 羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值