Javaweb ServletContext的使用

1.ServletContext的定义

1.1 ServletContext 是一个接口,表示Servlet 上下文对象

1.2 一个web工程,只有一个ServletContext对象实例

1.3 ServletContext对象是一个域对象

什么是域对象?

  • 域对象,是可以像 Map一样存取数据的对象
  • 这里的域指的的存取数据的操作范围
    在这里插入图片描述

1.4 ServletContext是在web工程部署启动的时候创建;在web工程停止的时候销毁

2. ServletContext的4个作用

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

获取当前的工程路径,格式为: /工程路径

获取工程部署在服务器端硬盘的绝对路径

像 Map一样存取数据

举例如下

Servlet实现类

package com.lchh.servlet;

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;

@SuppressWarnings("serial")
public class ServletContextTest extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
		// 获取上下文参数
		ServletContext servletContext = getServletConfig().getServletContext();
		String imageUrl = servletContext.getInitParameter("imageUrl");
		System.out.println("imageUrl="+imageUrl);
		String web_desc = servletContext.getInitParameter("web_desc");
		System.out.println("web_desc="+web_desc);
		
		// 获取工程路径
		String contextPath = servletContext.getContextPath();
		System.out.println("contextPath="+contextPath);
		
		// 获取服务器端的项目绝对路径
		String realPath = servletContext.getRealPath("/");
		System.out.println("realPath="+realPath);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>servlet_01</display-name>
  <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>
  
  <!-- context-param 配置的上下文参数属于整个web工程 -->
  <context-param>
  	<param-name>imageUrl</param-name>
  	<param-value>www.baidu.com/image</param-value>
  </context-param>
  <!-- context-param 配置的上下文参数属于整个web工程 --> 
  <context-param>
  	<param-name>web_desc</param-name>
  	<param-value>这个网站是一个测试网站</param-value>
  </context-param>
  
  <servlet>
  	<servlet-name>ServletContextTest</servlet-name>
  	<servlet-class>com.lchh.servlet.ServletContextTest</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ServletContextTest</servlet-name>
  	<url-pattern>/servletContext</url-pattern>
  </servlet-mapping>
  
</web-app>

测试结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Java Web中,可以使用文件存储方式来实现网站计数器的功能。具体实现步骤如下: 1. 在Web应用程序的根目录下创建一个名为“counter”的文件夹,用于存储计数器文件。 2. 在Servlet使用以下代码来读取计数器文件的值: ```java String filePath = application.getRealPath("/counter/count.txt"); // 获取计数器文件的路径 File file = new File(filePath); // 创建File对象 int count = 0; // 初始化计数器为0 if (file.exists()) { // 如果文件存在 BufferedReader br = new BufferedReader(new FileReader(file)); // 创建BufferedReader对象 count = Integer.parseInt(br.readLine()); // 读取文件中的计数器值 br.close(); // 关闭BufferedReader } ``` 3. 在Servlet使用以下代码来更新计数器文件的值: ```java String filePath = application.getRealPath("/counter/count.txt"); // 获取计数器文件的路径 File file = new File(filePath); // 创建File对象 PrintWriter pw = new PrintWriter(new FileWriter(file)); // 创建PrintWriter对象 pw.println(count); // 将计数器值写入文件 pw.close(); // 关闭PrintWriter ``` 4. 在Servlet使用以下代码来输出计数器的值: ```java out.print("本站访问量:" + count); // 输出计数器的值 ``` 完整的Servlet代码如下: ```java @WebServlet("/counter") public class CounterServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); ServletContext application = getServletContext(); String filePath = application.getRealPath("/counter/count.txt"); File file = new File(filePath); int count = 0; if (file.exists()) { BufferedReader br = new BufferedReader(new FileReader(file)); count = Integer.parseInt(br.readLine()); br.close(); } count++; PrintWriter pw = new PrintWriter(new FileWriter(file)); pw.println(count); pw.close(); out.print("本站访问量:" + count); } } ``` 在JSP页面中,可以使用以下代码来显示计数器的值: ```jsp 本站访问量:<%=application.getAttribute("count")%> ``` 在JSP页面的`<body>`标签中添加以下代码来调用计数器Servlet: ```jsp <jsp:include page="/counter"/> ``` 在Web应用程序的`web.xml`文件中添加以下代码来初始化计数器的值: ```xml <context-param> <param-name>count</param-name> <param-value>0</param-value> </context-param> ``` 在Web应用程序的`ServletContextListener`实现类中,可以使用以下代码来读取和更新计数器的值: ```java public class MyServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { ServletContext application = event.getServletContext(); String filePath = application.getRealPath("/counter/count.txt"); File file = new File(filePath); int count = 0; if (file.exists()) { try { BufferedReader br = new BufferedReader(new FileReader(file)); count = Integer.parseInt(br.readLine()); br.close(); } catch (IOException e) { e.printStackTrace(); } } application.setAttribute("count", count); } public void contextDestroyed(ServletContextEvent event) { ServletContext application = event.getServletContext(); String filePath = application.getRealPath("/counter/count.txt"); File file = new File(filePath); int count = (Integer)application.getAttribute("count"); PrintWriter pw; try { pw = new PrintWriter(new FileWriter(file)); pw.println(count); pw.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在Web应用程序的`web.xml`文件中添加以下代码来注册`MyServletContextListener`: ```xml <listener> <listener-class>com.example.MyServletContextListener</listener-class> </listener> ``` 这样就可以使用文件存储方式来实现网站计数器的功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

神奇洋葱头

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

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

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

打赏作者

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

抵扣说明:

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

余额充值