Servlet之ServletContext获取web上下文路径、全局参数、和Attribute(域)

本文详细介绍了Servlet技术中的关键操作,包括获取Web上下文路径、获取全局参数以及如何利用ServletContext对象进行数据的保存、获取与删除,为读者提供了清晰的操作流程。

 

1)获取web上下文路径

 

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取ServletContext对象
		//this.getServletConfig().getServletContext();
		//等同于下面一句,因为创建getServletContext必须要通过getServletConfig对象
		ServletContext context = this.getServletContext();
		
		//获取web的上下文路径,
		String path = context.getContextPath();
		
		//请求重定向,这样的好处可以让获取的路径更加灵活。不用考虑项目名是否发生了变化。
		response.sendRedirect(context.getContextPath()+"/index.jsp");
	}
}


2)获取全局参数

 

 

public class ServletContextDemo1 extends HttpServlet {
	/**
	 * 获取全局参数
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 ServletContext context = this.getServletContext();
		 //根据参数名获取参数值
		 System.out.println(context.getInitParameter("MMM"));
		 //获取所有的参数名,返回枚举类型
		 Enumeration<String> emn = context.getInitParameterNames();
		 while(emn.hasMoreElements()){
			 String paramName = emn.nextElement();
			 String paramValue = context.getInitParameter(paramName);
			 System.out.println(paramName+"="+paramValue);
		 }
	}

}

 

 

3)和域相关

域:域对象在不同的资源之间来共享数据,保存数据,获取数据。

这个我使用了三个Servlet来说明这个问题,ScopeDemo1用于获取Attribute,ScopeDemo2用于设置Attribute,ScopeDemo3用于删除Attribute。

 

保存共享数据:

 

public class ScopeDemo2 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//首先创建ServletContext对象
	ServletContext context = 	this.getServletContext();
	//保存共享数据
	context.setAttribute("name", "zhangsan");//第一个参数为字符串,第二个是Object(也就是任意类型)
	System.out.println("设置成功");
	
	}

}

 

获取共享数据:

 

public class ScopeDemo1 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//创建ServletContext对象
		ServletContext context = this.getServletContext();
		//获取共享数据内容
		String name = (String)context.getAttribute("nnn");
		System.out.println(name);
	}
}


删除共享数据:

 

 

public class ScopeDemo3 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取ServletContext对象
		ServletContext context = 	this.getServletContext();
		//删除共享数据
		context.removeAttribute("name");
		System.out.println("删除成功");		
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值