ServletContext相关
简介
每个web工程都只有一个ServletContext对象。 说白了也就是不管在哪个servlet里面,获取到的这个类的对象都是同一个。
如何得到对象
//1. 获取对象
ServletContext context = getServletContext();
有什么作用
- 获取全局配置参数
- 获取web工程中的资源
- 存取数据,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相关的更多相关文章
- 与ServletContext相关的监听器
概述 与ServletContext相关的监听器有ServletContextListener与ServletContextAttributeListener. ServletContextListe ...
- 【Servlet】1、Servlet监听器及相关接口
Servlet监听器用于监听一些重要事件的发生,监听器对象可以在事情发生前.发生后可以做一些必要的处理. 接口: 目前Servlet2.4和JSP2.0总共有8个监听器接口和6个Event类,其中Ht ...
- Spring 的优秀工具类盘点
文件资源操作 文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等.我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来 ...
- 2015第30周三Spring常用工具类
文件资源操作 文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等.我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来 ...
- Spring 的优秀工具类盘点第 1 部分
文件资源操作 文件资源的操作是应用程序中常见的功能,如当上传一个文件后将其保存在特定目录下,从指定地址加载一个配置文件等等.我们一般使用 JDK 的 I/O 处理类完成这些操作,但对于一般的应用程序来 ...
- web.xml中的主要元素说明(listener, filter, servlet)
web.xml中加载的顺序为:context-param ---> listener ---> filter ---> servlet. listener:主要针对的是对象的操作,如 ...
- web.xml中listener作用及使用
一.WebContextLoaderListener 监听类 它能捕捉到server的启动和停止,在启动和停止触发里面的方法做对应的操作! 它必须在web.xml 中配置才干使用,是配置监听类的 二. ...
- web.xml在listener作用与用途
一.WebContextLoaderListener 监听类 它能捕捉到server的启动和停止,在启动和停止触发里面的方法做对应的操作! 它必须在web.xml 中配置才干使用,是配置监听类的 二. ...
- Servlet 应用程序事件、监听器
Web容器管理Servlet/JSP相关的生命周期,若对HttpServletRequest对象.HttpSession对象.ServletContxt对象在生成.销毁或相关属性设置发生的时机点有兴趣 ...
- SSM框架注解整合
一.web应用环境 1.ServletContext 对于一个web应用,其部署在web容器(比如:tomcat)中,web容器提供其一个全局的上下文环境,这个上下文就是ServletContext, ...
随机推荐
- JUC并发—6.AQS源码分析二
大纲 1.ReentractReadWriteLock的基本原理 2.基于AQS实现的ReentractReadWriteLock 3.ReentractReadWriteLock如何竞争写锁 4.R ...
- 安川机器人HW1171766-A本体线缆维修详解
随着工业自动化程度的不断提高,安川机器人在生产线上的应用越来越广泛.然而,在长期运行过程中,安川机器人本体线缆可能会出现磨损.老化.断裂问题,这些问题不仅会影响机器人的正常运行,还可能导致生产线的停滞 ...
- 了解了这些你就是一位优秀的CTO
spring cloud 分布式 Ngix协议层做阻断应射处理 SpringBoot 容器+MVC框架 SpringSecurity 认证和授权框架 MyBatis ORM框架 Swagger-UI ...
- 不到24小时,AOne让全员用上DeepSeek的秘诀是……
DeepSeek引发新一轮AI浪潮,面对企业数字化智能升级与数据安全红线的急迫需求,IT负责人的压力山大!如何在24小时内实现全员AI落地,同时为后续安全部署铺平道路? Step1:一键开启全员智能时 ...
- Linux 提升CPU利用率
由于同学项目CPU利用率不高,客户要降他们服务器配置,所以下下策. # 提升一个核CPU利用率 cat /dev/urandom | gzip -9 > /dev/null # 提升更大的CPU ...
- Typecho输出html颜色字教程
!!! 这里是红色 !!! !!! 这里是绿色 !!! typecho输出html教程 只需要用!!!包裹html即可实现! 用法 !!! <font color="red" ...
- 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
前言 今天大姚给大家分享 3 个 .NET 开源.免费的文件压缩处理库,希望可以快速帮助同学们实现文件压缩和解压功能! SharpCompress SharpCompress 是一个基于 C# 编写的 ...
- Window10永久暂停(禁用)自动更新
终于彻底设置window10不自动更新了(禁用自动更新) 设置成功后的标识 设置成功后,重启电脑再打开就会显示这样的,这个才是禁用成功的标识: 之前安装了window 10 ,但是window 10 ...
- python3 ModuleNotFoundError: No module named 'CommandNotFound'
前言 python3 报错:ModuleNotFoundError: No module named 'CommandNotFound' 这是 linux 安装多版本 python 时的一个遗留问题, ...
- ant design pro 使用 getFieldValue、setFieldsValue
getFieldValue 获取表单指定 name 值,setFieldsValue 为表单指定 name 设定值 import type { ProFormInstance } from '@ant ...