ServletContext对象
- 概念:代表整个web应用,可以和程序的容器(服务器)来通信
- 获取:
- 通过request对象获取
- request.getServletContext();
- 通过HttpServlet获取
- this.getServletContext();
package com.ailyt.servletContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/scs1")
public class ServletContextStudy01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
* ServletContext对象获取
* * 通过request对象获取
* * request.getServletContext();
* * 通过HttpServlet获取
* * this.getServletContext();
*/
//通过request对象获取
ServletContext context1 = req.getSession().getServletContext();
//通过HttpServlet获取
ServletContext context2 = this.getServletContext();
System.out.println(context1);
System.out.println(context2);
System.out.println(context1 == context2);
}
}
- 功能:
- 获取MIME类型:
- MIME类型:在互联网通信过程中定义的一种文件数据类型
- 格式:大类型/小类型 text/html image/jpeg
- 获取:String getMimeType(String file):
- 域对象:共享数据
- 获取文件的真实(服务器)路径
package com.ailyt.servletContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/scs2")
public class ServletContextStudy02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/**
* ServletContext功能
* 获取MIME类型:
* MIME类型:在互联网通信过程中定义的一种文件数据类型
* 格式:大类型/小类型 text/html image/jpeg
* 获取:String getMimeType(String file):
*/
//通过request对象获取
ServletContext context1 = req.getSession().getServletContext();
//定义文件名称
String fileName = "a.jpg";
//获取MIME类型
String mimeType = context1.getMimeType(fileName);
System.out.println(mimeType);
}
}