ServletContext对象的概述
特点: 该对象是单例的
作用:
* 它是域对象,可以用来存储数据
* 获取文件的MIME类型
* 获取文件运行时候的真实路径
展示存储数据
MIME类型:
MIME类型就是设定某种扩展名的文件用指定的应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。
获取获取方式: public String getMimeType(String file)
获取真实路径
* 问题: 只能在web环境下使用
* JDBCUtils获取路径改进,使用ClassLoader进行获取
ServletContext context = getServletConfig().getServletContext() ; String path = context.getRealPath("/") ; //D: omcatapache-tomcat-7.0.26webappsday05-servlet String path = context.getRealPath("/mv.jpg") ; // 把mv.jpg存储到WebRoot下的获取方式 String path = context.getRealPath("/WEB-INF/classes/mv.jpg") ; // 把mv.jpg存储到了src下的获取方式 String path = context.getRealPath("/WEB-INF/mv.jpg") ; // 把mv.jpg存储到WEB-INF目录下的获取方式 System.out.println(path);
核心API:
java.lang.String getContextPath() --得到当前web应用的路径 java.lang.String getInitParameter(java.lang.String name) --得到web应用的初始化参数 java.util.Enumeration getInitParameterNames() void setAttribute(java.lang.String name, java.lang.Object object) --域对象有关的方法 java.lang.Object getAttribute(java.lang.String name) void removeAttribute(java.lang.String name) RequestDispatcher getRequestDispatcher(java.lang.String path) --转发(类似于重定向) java.lang.String getRealPath(java.lang.String path) --得到web应用的资源文件 java.io.InputStream getResourceAsStream(java.lang.String path)
示例代码:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 读取web应用下的资源文件(例如properties)
*/
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应用时创建ServletContext对象。
得到对象: 从ServletConfig对象的getServletContext方法得到
域对象有关的方法:
ServletContext就是一个域对象!!!!
- 保存数据: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域对象:作用范围在整个web应用中有效!!!
所有域对象:
- HttpServletRequet 域对象
- ServletContext域对象
- HttpSession 域对象
- PageContext域对象
转发:
RequestDispatcher getRequestDispatcher(java.lang.String path)
1)转发
a)地址栏不会改变
b)转发只能转发到当前web应用内的资源
c)可以在转发过程中,可以把数据保存到request域对象中
2)重定向
a)地址栏会改变,变成重定向到地址。
b)重定向可以跳转到当前web应用,或其他web应用,甚至是外部域名网站。
c)不能再重定向的过程,把数据保存到request中。
package com.loaderman.demo; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=utf-8"); //1.得到ServletContext对象 //ServletContext context = this.getServletConfig().getServletContext(); ServletContext context = this.getServletContext(); //(推荐使用) //2.得到web应用路径 /** * web应用路径:部署到tomcat服务器上运行的web应用名称 */ String contextPath = context.getContextPath(); System.out.println(contextPath); /** * 案例:应用到请求重定向 */ response.sendRedirect(contextPath+"/index.jsp"); } }
package com.loaderman.demo; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Enumeration; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=utf-8"); //得到SErvletContext对象 ServletContext context = this.getServletContext(); System.out.println("参数"+context.getInitParameter("AAA")); Enumeration<String> enums = context.getInitParameterNames(); while(enums.hasMoreElements()){ String paramName = enums.nextElement(); String paramValue =context.getInitParameter(paramName); System.out.println(paramName+"="+paramValue); } //尝试得到servlet参数 String path = this.getServletConfig().getInitParameter("path"); System.out.println("path="+path); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- 配置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> <!-- servlet的配置 --> <servlet> <!-- servlet的内部名称,自定义。尽量有意义 --> <servlet-name>mTestServlet</servlet-name> <!-- servlet的类全名: 包名+简单类名 --> <servlet-class>com.loaderman.demo.TestServlet</servlet-class> <!-- 初始参数: 这些参数会在加载web应用的时候,封装到ServletConfig对象中 --> <init-param> <param-name>path</param-name> <param-value>d:/b.txt</param-value> </init-param> <init-param> <param-name>BBB</param-name> <param-value>BBB's value</param-value> </init-param> <init-param> <param-name>CCCC</param-name> <param-value>CCCC's value</param-value> </init-param> </servlet> <!-- servlet的映射配置 --> <servlet-mapping> <!-- servlet的内部名称,一定要和上面的内部名称保持一致!! --> <servlet-name>mTestServlet</servlet-name> <!-- servlet的映射路径(访问servlet的名称) --> <url-pattern>/demotest</url-pattern> </servlet-mapping> </web-app>
运行代码,日志:
参数AAA's value AAA=AAA's value CCC=CCC's value BBB=BBB's value path=d:/b.txt
保存数据到域对象中:
package com.loaderman.demo; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=utf-8"); //1.得到域对象 ServletContext context = this.getServletContext(); //2.把数据保存到域对象中 //context.setAttribute("name", "eric"); context.setAttribute("student", new Student("jacky",20)); System.out.println("保存成功"); } }
package com.loaderman.demo; public 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 + "]"; } }
运行保存即可
获取域对象中的数据:
package com.loaderman.demo; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws 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); } }
运行日志显示:
Student [age=20, name=jacky]
转发示例代码:
package com.loaderman.demo; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { /** * 保存数据到request域对象 */ request.setAttribute("name", "rose"); //转发 /** * 注意:不能转发当前web应用以外的资源。 */ /*RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/GetDataServlet"); rd.forward(request, response);*/ this.getServletContext().getRequestDispatcher("/getdate").forward(request, response); } }
package com.loaderman.demo; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RedirectDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 保存数据到request域对象 */ request.setAttribute("name", "rose"); //重定向 /** * 注意:可以跳转到web应用内,或其他web应用,甚至其他外部域名。 */ response.sendRedirect("/getdate"); } }
package com.loaderman.demo; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class GetDateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 从request域对象中获取数据 */ String name = (String)request.getAttribute("name"); System.out.println("name="+name); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- servlet的配置 --> <servlet> <!-- servlet的内部名称,自定义。尽量有意义 --> <servlet-name>mTestServlet</servlet-name> <!-- servlet的类全名: 包名+简单类名 --> <servlet-class>com.loaderman.demo.TestServlet</servlet-class> </servlet> <servlet> <servlet-name>getdateSerlet</servlet-name> <servlet-class>com.loaderman.demo.GetDateServlet</servlet-class> </servlet> <servlet> <servlet-name>RedirectDemo</servlet-name> <servlet-class>com.loaderman.demo.RedirectDemo</servlet-class> </servlet> <!-- servlet的映射配置 --> <servlet-mapping> <!-- servlet的内部名称,一定要和上面的内部名称保持一致!! --> <servlet-name>RedirectDemo</servlet-name> <!-- servlet的映射路径(访问servlet的名称) --> <url-pattern>/redirect</url-pattern> </servlet-mapping> <servlet-mapping> <!-- servlet的内部名称,一定要和上面的内部名称保持一致!! --> <servlet-name>getdateSerlet</servlet-name> <!-- servlet的映射路径(访问servlet的名称) --> <url-pattern>/getdate</url-pattern> </servlet-mapping> <!-- servlet的映射配置 --> <servlet-mapping> <!-- servlet的内部名称,一定要和上面的内部名称保持一致!! --> <servlet-name>mTestServlet</servlet-name> <!-- servlet的映射路径(访问servlet的名称) --> <url-pattern>/demotest</url-pattern> </servlet-mapping> </web-app>
运行,浏览器请求testdemo和请求redirect日志如下:
name=rose name=null
浏览器请求testdemo地址栏没有改变,请求redirect发生了改变!