什么是ServletContext?
- Servlet环境上下文对象
- web容器启动的时候,会为每一个web程序创建一个ServletContext对象,它代表了当前的web应用;
- 一个web应用是由若干个JSP,JavaBean,Servlet等web组件的集合构成
- 可以通过ServletContext对象得到以下资源信息:
.初始化参数
.存储在context中的对象
.与context关联的资源
.日志
ServletContext应用:
1.共享数据
放置数据
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context=this.getServletContext();
String name = "灵儿";
context.setAttribute("name",name);
}
读取数据
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
ServletContext context = this.getServletContext();
String name = (String) context.getAttribute("name");
resp.getWriter().println("名字"+name);
}
两个Servlet在同一个web应用里,所以是相同的ServletContext对象
- 获取初始化参数
<!--初始化一些参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
//取得参数
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String url=context.getInitParameter("url");
resp.getWriter().println(url);
}
3.请求转发
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
System.out.println("进入了demo4方法");
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp");//请求转发的路径
requestDispatcher.forward(req,resp);//调用forward进行转发
}
注意与请求重定向的差别:访问的路径没有改变
4.读取资源文件
Properties:
- Java路径下新建properties
- resources目录下新建properties文件
这两个文件都被打包至同一路径下:classes(target),俗称为classpath
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
InputStream is = servletContext.getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(is);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
resp.getWriter().println(username+":"+password);
}