ServletContext作用-获取web的上下文路径:
public class ContextDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("到啦");
ServletContext context = this.getServletContext();
String path = context.getContextPath();
/*结果显示:/myFirstServlet
但是注意,这个返回的是网站的路径,并不是我们这个项目的名称*/
//作用:可以让这个获取文件的路径更加灵活
/*当我们需要重定向到一个页面,但是我们的网站可能要修改,这样的话就不会造成什么影响*/
response.sendRedirect(context.getContextPath()+"/hello.html");
}
}
ServletContext作用-获取全局参数:
因为一个网站只存在一份ServletContext,所以该网站中所有的servlet都可以获取到该全局参数
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
//获取所有参数
Enumeration<String> enums = context.getInitParameterNames();
//遍历参数名
while(enums.hasMoreElements()){
String paramName = enums.nextElement();
//通过参数名获取参数值
String paramValue = context.getInitParameter(paramName);
System.out.println(paramName+":"+paramValue);
}
}
ServletContext作用-servlet域对象:
域对象相当于一个容器,可以从一个servlet中用ServletContext存入数据;
从另一个servlet中用ServletContext读取数据;
用ServletContext写入属性和值
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.setAttribute("name", "丁昌江");
context.setAttribute("age", 22);//22会自动装箱为对象
ArrayList list = new ArrayList();
list.add("丁昌江");
list.add("杨燕语");
list.add("黄智欣");
context.setAttribute("list", list);
System.out.println("写入成功");
}
用ServletContext读取属性和值
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ServletContext context = this.getServletContext();
String name = (String) context.getAttribute("name");
Integer age = (Integer) context.getAttribute("age");
List list = (List) context.getAttribute("list");
System.out.println("name:"+name);
System.out.println("age:"+age);
System.out.println("list:"+list);
System.out.println("读取成功");
}