【jsp+servler实战】中的ServletContext对象详细了解

ServletContext对象

通过前面知识点的学习,我们对于请求的处理已经可以说比较灵
活了,但是还不够。我们再介绍两个重要的对象 ServletContext 对象
和 ServletConfig 对象 可以看综合例子锻炼。
问题:
Request 解决了一次请求内的数据共享问题,session 解决了
用户不同请求的数据共享问题,那么不同的用户的数据共享该怎
么办呢
解决:
使用 ServletContext 对象
作用:
解决了不同用户的数据共享问题
原理:
ServletContext 对象由服务器进行创建,一个项目只有一个对
象。不管在项目的任意位置进行获取得到的都是同一个对象,那
么不同用户发起的请求获取到的也就是同一个对象了,该对象由
用户共同拥有。
特点:
服务器进行创建用户共享
一个项目只有一个
生命周期:
服务器启动到服务器关闭
作用域:
项目内
使用:
获取 ServletContext 对象
使用作用域进行共享数据流转
获取 web.xml 中的全局配置
获取 webroot 下项目资源流对象
获取 webroot 下资源绝对路径
案例:网页浏览器次数统计,详见源码

详解servletconfig的细节

使用 ServletContext 对象可以获取 web.xml 中的全局配置文件,
在 web.xml 中
每个 Servlet 也可以进行单独的配置,那么该怎么获取配置信
息呢?
解决:
使用 ServletConfig 对象作用:
ServletConfig 对象是 Servlet 的专属配置对象,每个 Servlet 都
单独拥有一个 ServletConfig 对象,用来获取 web.xml 中的配置信
息。
使用:
获取 ServletConfig 对象
获取 web.xml 中 servlet 的

public class ServletConfigServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//获取ServletConfig对象
		ServletConfig sc=this.getServletConfig();
		//获取web.xml中的配置数据
		String code=sc.getInitParameter("config");
		System.out.println(code);
	}
}
web.xml中的代码 全局上下文配置(全局配置参数)
Servlet 配置
过滤器配置
监听器配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>07-ServletConfig</display-name>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ServletConfigServlet</servlet-name>
    <servlet-class>com.bjsxt.servlet.ServletConfigServlet</servlet-class>
    <init-param>
    	<param-name>config</param-name>
    	<param-value>utf-8</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>ServletConfigServlet</servlet-name>
    <url-pattern>/sg</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿超程序

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

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

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

打赏作者

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

抵扣说明:

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

余额充值