1、ServletContext代表着整个JavaWeb应用,每个项目只有唯一的ServletContext的实例。

2、生命周期

  服务器启动时创建

  服务器关闭时销毁

3、获取ServletContext对象:从ServletConfig对象的getServletContext方法得到

  方式1:通过ServletConfig来获取ServeltContext

//获取ServletContext的引用
public class ServletDemo1 extends HttpServlet {
//获取ServletConfig
private ServletConfig config; public void init(ServletConfig config) throws ServletException {
this.config = config;
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
     //获取servletContext
ServletContext sc = config.getServletContext();
sc.setAttribute("p", "abc"); //获取全局参数
System.out.println(sc.getInitParameter("encoding")); System.out.println("Demo1:"+sc);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

方式2:直接获取,推荐

public class ServletDemo2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
     //获取ServletContext
ServletContext sc = this.getServletContext();
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }

4、ServletContext对象的核心API

java.lang.String getContextPath()   --得到当前web应用的路径(就是运行的项目名称)

public class ContextDemo1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.得到ServletContext对象
//ServletContext context = this.getServletConfig().getServletContext();
ServletContext context = this.getServletContext(); //(推荐使用) //2.得到web应用路径 /Demo
/**
* web应用路径:部署到tomcat服务器上运行的web应用名称
*/
String contextPath = context.getContextPath(); System.out.println(contextPath); /**
* 案例:应用到请求重定向
*/
response.sendRedirect(contextPath+"/index.html");
} }

--得到web应用的初始化参数

java.lang.String getInitParameter(java.lang.String name)   根据初始化参数名字得到参数的值

java.util.Enumeration getInitParameterNames()  获取所有参数的值

注意:初始化参数配置在web.xml文件中。用<context-param>标签,web应用参数可以让当前web应用的所有servlet获取!!!

<!-- 配置web应用参数 -->
<context-param>
<param-name>AAA</param-name>
<param-value>AAA's value</param-value>
</context-param>
<context-param>
<param-name>BBB</param-name>
<param-value>BBB's value</param-value>
</context-param>
<context-param>
<param-name>CCC</param-name>
<param-value>CCC's value</param-value>
</context-param>

代码:

/**
* 得到web应用参数
*
*
*/
public class ContextDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//得到SErvletContext对象
ServletContext context = this.getServletContext(); //根据初始化参数的名字得到初始化参数的值:java.lang.String getInitParameter(java.lang.String name)
String gp =sc.getInitParameter("AAA");
System.out.println(gp); //获取所有初始化参数 java.util.Enumeration getInitParameterNames()
Enumeration<String > en =sc.getInitParameterNames();
//遍历
while(en.hasMoreElements()){
String paramterName = en.nextElement();
String paramterValue = sc.getInitParameter(paramterName);
System.out.println(paramterName+":"+paramterValue);
}
//尝试得到ConfigDemo中的servlet参数
String path = this.getServletConfig().getInitParameter("path");
System.out.println("path="+path);
} }

域对象有关的方法

void setAttribute(java.lang.String name, java.lang.Object object)  保存数据

java.lang.Object getAttribute(java.lang.String name)  等到数据

void removeAttribute(java.lang.String name)  移除数据

域对象:作用是用于保存数据,获取数据。可以在不同的动态资源之间共享数据。

    ServletContext就是一个域对象!!!!

ServletContext域对象:作用范围在整个web应用中有效!!!

/**
* 保存数据
*
*
*/
public class ContextDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.得到域对象
ServletContext context = this.getServletContext(); //2.把数据保存到域对象中
//context.setAttribute("name", "eric");
context.setAttribute("student", new Student("jacky",20));
System.out.println("保存成功");
} } class Student{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + "]";
} }
=============================================
/**
* 获取数据
*
*
*/
public class ContextDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1.得到域对象
ServletContext context = this.getServletContext(); //2.从域对象中取出数据
//String name = (String)context.getAttribute("name");
Student student = (Student)context.getAttribute("student");
//System.out.println("name="+name); System.out.println(student);
} }

转发

RequestDispatcher getRequestDispatcher(java.lang.String path)   --转发(类似于重定向)

/**
* 转发(效果:跳转页面)
*
*
*/
public class ForwardDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { /**
* 保存数据到request域对象
*/
request.setAttribute("name", "rose"); //转发
/**
* 注意:不能转发当前web应用以外的资源。getRequsertDispatcher后面的路径必须以“/“开头,目标servlet的访问路径
*/
/*RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/GetDataServlet");
rd.forward(request, response);*/
this.getServletContext().getRequestDispatcher("/GetDateServlet").forward(request, response);
} }
=================================
public class GetDataServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { /**
* 从request域对象中获取数据
*/
String name = (String)request.getAttribute("name");
System.out.println("name="+name);
} }
===============================================================

public class RedirectDemo1 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  /**
   * 保存数据到request域对象
   */
  request.setAttribute("name", "rose");
  
  //重定向
  /**
   * 注意:可以跳转到web应用内,或其他web应用,甚至其他外部域名。
   */
  //response.sendRedirect("/demo11/adv.html");
  response.sendRedirect("/demo/GetDataServlet");
 }


}

 

转发与重定向的区别:

  1)转发

a)地址栏不会改变

b)转发只能转发到当前web应用内的资源

c)可以在转发过程中,可以把数据保存到request域对象中

2)重定向

a)地址栏会改变,变成重定向到地址。

b)重定向可以跳转到当前web应用,或其他web应用,甚至是外部域名网站。

c)不能再重定向的过程,把数据保存到request中。

结论: 如果要使用request域对象进行数据共享,只能用转发技术!!!

得到web应用的资源文件

    java.lang.String getRealPath(java.lang.String path)    返回资源文件的绝对路径

java.io.InputStream getResourceAsStream(java.lang.String path)  得到资源文件,返回的是输入流

/**
* 读取web应用下的资源文件(例如properties)
* @author APPle
*/
public class ResourceDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* . 代表java命令运行目录。java运行命令在哪里?? 在tomcat/bin目录下
* 结论: 在web项目中, . 代表在tomcat/bin目录下开始,所以不能使用这种相对路径。
*/ //读取文件。在web项目下不要这样读取。因为.表示在tomcat/bin目录下
/*File file = new File("./src/db.properties");
FileInputStream in = new FileInputStream(file);*/ /**
* 使用web应用下加载资源文件的方法
*/
/**
* 1. getRealPath读取,返回资源文件的绝对路径
*/
/*String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
System.out.println(path);
File file = new File(path);
FileInputStream in = new FileInputStream(file);*/ /**
* 2. getResourceAsStream() 得到资源文件,返回的是输入流
*/
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties();
//读取资源文件
prop.load(in); String user = prop.getProperty("user");
String password = prop.getProperty("password");
System.out.println("user="+user);
System.out.println("password="+password); } }

补充: web应用的路径问题

/**
* web应用中路径问题
*
*
*/
public class PathDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//目标资源: target.html
/**
* 思考: 目标资源是给谁使用的。
* 给服务器使用的: / 表示在当前web应用的根目录(webRoot下)
* 给浏览器使用的: / 表示在webapps的根目录下
*/
/**
* 1.转发
*/
//request.getRequestDispatcher("/target.html").forward(request, response); /**
* 2.请求重定向
*/
//response.sendRedirect("/demo/target.html"); /**
* 3.html页面的超连接href
*/
response.getWriter().write("<html><body><a href='/demo/target.html'>超链接</a></body></html>"); /**
* 4.html页面中的form提交地址
*/
response.getWriter().write("<html><body><form action='/demo/target.html'><input type='submit'/></form></body></html>");
} }

ServlertContext的更多相关文章

  1. JavaWeb中读取文件资源的路径问题

    在做javaweb开发的时候,我们可能会需要从本地硬盘上读取某一个文件资源,或者修改某一个文件,这个时候就需要先找到这个文件,然后用FileInputStrem等文件字节.字符流来将这个文件读取到内存 ...

  2. JavaWeb中读取文件资源的路径问题 -- 转自新浪博客

    在做javaweb开发的时候,我们可能会需要从本地硬盘上读取某一个文件资源,或者修改某一个文件,这个时候就需要先找到这个文件,然后用FileInputStrem等文件字节.字符流来将这个文件读取到内存 ...

  3. Spring和SpringMVC整合及关系

    SpringMVC扼要的讲,就是控制请求和处理.有必要将Spring和SpringMVC整合,否则仅配置SpringMVC并完成Spring的功能,会造成业务逻辑混乱. 简要总结:①原理:采用监听器, ...

随机推荐

  1. (转) GIS 中地理坐标和屏幕坐标的标准转换方法

    from :http://www.cnblogs.com/WonKerr/archive/2010/01/01/Coord_Transform.html 在GIS中,当你拿到一个图层的地理坐标后,如果 ...

  2. Python学习进程(13)文件与IO

        本节介绍基本的IO函数和文件的读写操作.     (1)读取键盘输入: Python用于读取键盘输入的函数有两个:raw_input与input. 1)raw_input函数 从标准输入读取一 ...

  3. $Android制作和使用Nine-Patch图片

    Nine-Patch图片是一种经过特殊处理的png图片,能够指定图片的哪些区域可以被拉伸而哪些区域不可以. (一)普通图片被拉伸时的缺陷 有如下xml文件,其中子LinearLayout的背景图片设置 ...

  4. iOS获取设备IP地址

    项目用到要获取iOS设备的IP地址,有2种方法: 1)第一种比较简单,但是只有当你的设备连接到WIFI时才能获取到IP地址,倘若你的设备用的是流量,那就不行.代码如下: #import <ifa ...

  5. h5新特性 File API详解

    之前一直觉得h5的新特性就是一些新标签呢,直到想研究一下图片上传预览的原理,才发现还是有好多新的api的,只是不兼容ie低版本,挺可惜的, File API在表单中文件输入字段基础上,又添加了一些直接 ...

  6. Python绿色版

    Python 安装的时候,有个选项,是问你要安装给所有用户还是只安装给当前用户,你只要选择当前用户,就会把那些需要的 dll ,包括 msvcr90.dll 都给装到 Python 目录下,你只要把 ...

  7. Nginx错误日志配置信息详解

    Nginx的错误日志可以配置在Main区块,也可以配置在虚拟主机区块中.Nginx软件会把自身运行的故障信息及用户访问的日志信息记录到指定的日志文件里,是我们调试Nginx服务的重要参考. error ...

  8. H3C 交换机设置telnet WEB用户

    huwei : local-user admin password cipher @#$@#$ service-type telnet ssh service-type telnet ssh leve ...

  9. 使用 Apache Spark 让 MySQL 查询速度提升 10 倍以上

    转: https://coyee.com/article/11012-how-apache-spark-makes-your-slow-mysql-queries-10x-faster-or-more ...

  10. idel 中 生成 jar包 和项目中自己需要的包

    一.首先在自己的项目中创建一个类类中创建一个构造方法构造方法中传入一个字符串参数(这个字符串参数是为了传入路径) 在方法体内通过file类创建文件夹(换而言之就是项目中的包) 二 .就是对这个项目中的 ...