ServletContext的使用

package com.itheima.context;

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;

public class ContextServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//获得ServletContext对象
		ServletContext context = getServletContext();
		//1、获得初始化参数
		String initParameter = context.getInitParameter("driver");
		System.out.println(initParameter);
		//2、获得a b c d.txt的绝对路径
		//2.1 获得a.txt
		String realPath_A = context.getRealPath("a.txt");
		System.out.println(realPath_A);
		//2.2 获得b.txt
		String realPath_B = context.getRealPath("WEB-INF/b.txt");
		System.out.println(realPath_B);
		//2.3 获得c.txt
		String realPath_C = context.getRealPath("WEB-INF/classes/c.txt");
		System.out.println(realPath_C);
		//2.4 获得d.txt----获取不到
		
		
		//在读取src(classes) 下的资源是可以同类加载器----专门加载classes 下的文件的
		//getResource() 参数是一个相对地址 相对classes
		String path = ContextServlet.class.getClassLoader().getResource("c.txt").getPath();
		System.out.println(path);
		
		//3、域对象---向servletContext中存数据
		context.setAttribute("name", "zhangsan");

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

 

package com.itheima.context;

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 ContextServlet2 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//域对象---从servletContext中取数据
		String attribute = (String) this.getServletContext().getAttribute("name");
		System.out.println(attribute);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

初始化参数可以在项目的web.xml中添加,如下

 <context-param>
    <param-name>driver</param-name>
    <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值