简介

如何得到对象

有什么作用

1、获取全局配置参数

2、获取web工程中的资源

3、存取数据,servlet间共享数据 域对象

ServlerContext的生命周期

ServletContext 的作用范围


简介

每个web工程都只有一个ServletContext对象。 说白了也就是不管在哪个servlet里面,获取到的这个类的对象都是同一个。


如何得到对象

//1. 获取对象
ServletContext context = getServletContext();

有什么作用

  1. 获取全局配置参数
  2. 获取web工程中的资源
  3. 存取数据,servlet间共享数据 域对象

1、获取全局配置参数

web.xml中设置参数

 <context-param>
<param-name>name</param-name>
<param-value>朱俊伟</param-value>
</context-param>
</web-app>

创建Servlet并配置Servlet并读取相应的参数

package com.zhujunwei.servletContext;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Administrator
* 创建ServletContext读取全局变量的值
*
*/
public class ServletContext01 extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//读取全局变量的值
ServletContext context = getServletContext();
String name = context.getInitParameter("name");
System.out.println(name);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

运行结果

朱俊伟

2、获取web工程中的资源

如果在项目中存在配置文件想要读取(如config.properties),可采用如下三种方法:

config.properties文件所在目录

-WebContent
-file
-config.properties
-META-INF
-WEB-INF

config.properties文件内容

name=zhujunwei

读取的三种方法

package com.zhujunwei.servletContext;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
*
* @author Administrator
* 读取工程文件的三种方法
*
*/
public class ServletContext02 extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
getProperty1();
getProperty2();
getProperty3();
} /**
* 方法3:通过类加载器读取工程中的文件
* @throws IOException
*/
private void getProperty3() throws IOException {
// 1、创建属性对象
Properties properties = new Properties(); // 2、指定载入的数据源
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("../../file/config.properties");
properties.load(inStream); // 3、获取name属性的值
String name = properties.getProperty("name");
System.out.println("getProperty3():name=" + name);
} /**
* 方法2:通过ServletContext中的getResourceAsStream方法读取文件
* @throws IOException
*/
private void getProperty2() throws IOException {
// 获取ServletContext对象
ServletContext context = getServletContext(); // 1、创建属性对象
Properties properties = new Properties(); // 2、指定载入的数据源
InputStream inStream = context.getResourceAsStream("file/config.properties");
properties.load(inStream); // 3、获取name属性的值
String name = properties.getProperty("name");
System.out.println("getProperty2():name=" + name);
} /**
* 方法1:通过ServletContext中的getRealPath方法读取文件
* @throws FileNotFoundException
* @throws IOException
*/
private void getProperty1() throws FileNotFoundException, IOException {
// 获取ServletContext对象
ServletContext context = getServletContext();
// 获取给定的文件在服务器上面的绝对路径
String path = context.getRealPath("file/config.properties"); // 1、创建属性对象
Properties properties = new Properties(); // 2、指定载入的数据源
InputStream inStream = new FileInputStream(path);
properties.load(inStream); // 3、获取name属性的值
String name = properties.getProperty("name");
System.out.println("getProperty1():name=" + name);
} protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

配置Servlet,执行得到结果

getProperty1():name=zhujunwei
getProperty2():name=zhujunwei
getProperty3():name=zhujunwei

3、存取数据,servlet间共享数据 域对象

思路分析

Login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>请输入账号密码登录</h2>
<form action="LoginServlet" method="get">
账号:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>

LoginServlet

package com.zhujunwei.servletContext;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 从客户端取得用户输入的账号和密码,经过校验后跳转到指定的页面
* @author Administrator
*
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取客户端输入的值
String username = request.getParameter("username");
String password = request.getParameter("password"); //对值进行校验并返回客户端
if("admin".equals(username)&&"123456".equals(password))
{
//1、成功次数的累加
//获取以前存的值,然后在旧的值基础上+1
Object obj = getServletContext().getAttribute("count");
//默认就是0次
int totalCount = 0;
if(obj!=null)
{
totalCount = (int) obj;
}
//给count赋新的值
getServletContext().setAttribute("count", totalCount+1);
//2、跳转到login_success.html
//设置状态码 :重新定位状态码
response.setStatus(302);
//定位跳转的位置是哪一个页面
response.setHeader("Location", "login_success.html");
}
else
{
PrintWriter pw = response.getWriter();
pw.write("login filed...");
}
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

login_success.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>登录成功</h2>
<a href="ServletContext04">查看网页登录成功的次数。</a>
</body>
</html>

CountServlet

package com.zhujunwei.servletContext;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class CountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//取值
int count = (int) getServletContext().getAttribute("count");
//输出到界面
response.getWriter().write("Login Success Count:"+count);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
} }

运行结果

ServlerContext的生命周期

服务器启动的时候,会为托管的每一个web应用程序,创建一个ServletContext对象

从服务器移除托管,或者是关闭服务器。

ServletContext 的作用范围

只要在这个项目里面,都可以取。 只要同一个项目。 A项目存,在B项目取,是取不到的,因为ServletContext对象不同。

ServletContext相关的更多相关文章

  1. 与ServletContext相关的监听器

    概述 与ServletContext相关的监听器有ServletContextListener与ServletContextAttributeListener. ServletContextListe ...

  2. 【Servlet】1、Servlet监听器及相关接口

    Servlet监听器用于监听一些重要事件的发生,监听器对象可以在事情发生前.发生后可以做一些必要的处理. 接口: 目前Servlet2.4和JSP2.0总共有8个监听器接口和6个Event类,其中Ht ...

  3. Spring 的优秀工具类盘点

    文件资源操作 文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等.我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来 ...

  4. 2015第30周三Spring常用工具类

    文件资源操作 文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等.我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来 ...

  5. Spring 的优秀工具类盘点第 1 部分

    文件资源操作 文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等.我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来 ...

  6. web.xml中的主要元素说明(listener, filter, servlet)

    web.xml中加载的顺序为:context-param ---> listener ---> filter ---> servlet. listener:主要针对的是对象的操作,如 ...

  7. web.xml中listener作用及使用

    一.WebContextLoaderListener 监听类 它能捕捉到server的启动和停止,在启动和停止触发里面的方法做对应的操作! 它必须在web.xml 中配置才干使用,是配置监听类的 二. ...

  8. web.xml在listener作用与用途

    一.WebContextLoaderListener 监听类 它能捕捉到server的启动和停止,在启动和停止触发里面的方法做对应的操作! 它必须在web.xml 中配置才干使用,是配置监听类的 二. ...

  9. Servlet 应用程序事件、监听器

    Web容器管理Servlet/JSP相关的生命周期,若对HttpServletRequest对象.HttpSession对象.ServletContxt对象在生成.销毁或相关属性设置发生的时机点有兴趣 ...

  10. SSM框架注解整合

    一.web应用环境 1.ServletContext 对于一个web应用,其部署在web容器(比如:tomcat)中,web容器提供其一个全局的上下文环境,这个上下文就是ServletContext, ...

随机推荐

  1. Paxos算法:如何解决分布式系统中的共识问题?

    背景 Paxos 算法是 Leslie Lamport(莱斯利·兰伯特)在 1990 年提出了一种分布式系统 共识 算法.这也是第一个被证明完备的共识算法(前提是不存在拜占庭将军问题,也就是没有恶意节 ...

  2. VS2019 找不到资产文件 “xxxx\obj\project.assets.json”运行NuGet包还原以生成此文件

    参考地址:https://blog.csdn.net/weixin_42835409/article/details/107033059 下载 log4net 源码打开,编译报错: 严重性 代码 说明 ...

  3. [ABC259F] Select Edges 题解

    很容易想到树形 dp. 考虑在有根树内,每个点都有两种状态: 不选自己和父亲的边: 要选自己和父亲的边. 那么单独对于子树内部而言,就要分两种情况: 最多可以向 \(d_i\) 个孩子连边,对应上述第 ...

  4. 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤

    在1 使用ollama完成DeepSeek本地部署中使用ollama完成deepSeek的本地部署和运行,此时我可以在PowerShell中通过对话的方式与DeepSeek交流,但此时本地模型不具备联 ...

  5. Winform ShowDialog如何让先前Show的窗体可以交互

    背景描述 最近项目中有一个需求,全局有一个共用的窗体,能够打开不同模块的报告,由于需要兼容不同模块,代码复杂,启动速度慢.优化方案为将窗体启动时就创建好,需要查看报告时,使用此单例弹窗加载不同模块下的 ...

  6. docker - [02] 安装部署

    一.环境准备 1.需要会一点点Linux基础 2.CentOS 7+ 3.XShell连接服务器进行远程操作 Centos7.x 虚拟机环境 序号 主机名 IP 操作系统 1 ctos79-01 19 ...

  7. Azkaban - [01] 概述

    简单的任务调度使用crontab.复杂的任务调度使用oozie.azkaban等开发调度系统. 一.为什么学习Azkaban   一个完整的数据分析系统通常都是由大量任务单元(shell脚本.java ...

  8. C++调用动态链接库DLL的隐式链接和显式链接基本方法小结

    C++程序在运行时调用动态链接库,实现逻辑扩展,有两种基本链接方式:隐式链接和显式链接.下面就设立最基本情形实现上述链接. 创建DLL动态链接库 编辑头文件 mydll_3.h: #pragma on ...

  9. 低代码 + DeepSeek:赋能开发者,效率飞跃新高度

    活字格接入 DeepSeek 前段时间,小编陆续发布了关于葡萄城旗下产品 Wyn 和 SpreadJS 成功接入DeepSeek的技术文章,分享了两款产品与 DeepSeek 集成后的功能优势和应用场 ...

  10. 基于Qt的在QGraphicsView中绘制带有可动拐点的连线的一种方法

        摘要:本文详细介绍了基于Qt框架在`QGraphicsView`中实现带有可动拐点连线的绘制方法.通过自定义`CustomItem`和`CustomPath`类,结合`QGraphicsIte ...