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, ...
随机推荐
- .NET Core常用集合的几个坑
C#中的常见集合 注意,箭头线不代表继承关系,只代表功能上的加强,如有错误,欢迎指出. 泛型集合时间复杂度 集合类型 添加 删除 查找 访问(索引/键) 遍历 备注 List<T> O(1 ...
- Esp32s3(立创实战派)移植LVGL
Esp32s3(立创实战派)移植LVGL 移植: 使用软件EEZ studio 创建工程选择带EEZ Flow的,可以使用该软件更便捷的功能 根据屏幕像素调整画布为320*240 复制ui文件至工程 ...
- QStringListModel的使用
主要为 :添加.插入.修改.删除.清空等操作 例子:本例子中QListView 没有做任何处理,只是拖放至ui文件,设置了布局 MainWindow.h #ifndef MAINWINDOW_H #d ...
- 【攻防世界】ezbypass-cat
ezbypass-cat 题目来源 攻防世界 NO.GFSJ1183 题目描述 只有一个登录界面,没有注册界面,扫目录也扫不出有用的文件.sql注入也无果,有些难以下手. 题解一 该题解可能是一个非预 ...
- ABC391D题解
前置知识: map priority_queue 思路 考虑预处理每一个图块在第几秒后会被删除. 如何预处理?我使用了一种非常暴力的做法,首先处理的过程肯定是从下往上的,于是每一个图块能被删除一定是它 ...
- VMware15.5虚拟机下载及安装
一.VMware虚拟机介绍 VMWare虚拟机软件是一个"虚拟PC"软件,它使你可以在一台机器上同时运行二个或更多Windows.DOS.LINUX系统.与"多启动&qu ...
- idea社区版配置springboot项目问题分析及处理
前言 记录一次使用IDEA社区版配置SpringBoot项目的经历,包括遇到的问题及解决过程 IDEA版本:IntelliJ IDEA 2024.2.3 (Community Edition) 问题描 ...
- 为什么将malloc()和printf()称为不可重入?
转载自https://mlog.club/article/1807704 在unix系统中,我们知道malloc()是一个不可重入的函数(系统调用).为什么? 类似地,printf()也被认为是不可重 ...
- React.memo 解决函数组件重复渲染
为什么会存在重复渲染? react 在 v16.8 版本引入了全新的 api,叫做 React Hooks,它的使用与以往基于 class component 的组件用法非常的不一样,不再是基于类,而 ...
- golang中容易遇到的错误
前言 在循环中,有几种情况可能会导致混乱,需要弄清楚. 循环迭代器变量中使用引用 出于效率考虑,我们经常使用单个变量来循环迭代器.但在循环中,每次循环迭代中都会有不同的值,有时候会导致未知的行为. i ...