官方对ServeletContext的解释是定义了一组可以使servelet和web容器通信的方法。
也就是servelet对象可以通过serveletcontext对象与web容器进行交互。
接下来讲解ServeletContext的获取及其作用
-
获取:(两种方法)
- 通过request对象获取:request.getServletContext();
- 通过当前类获取:this.getServletContext();
注意:无论通过哪种方式我们获得的ServeletContext对象是同一个对象。
-
作用:
- 获取文件对应的MIME类型
- 获取文件的真实路径(真实路径是部署在服务器上的文件路径,也就是真实访问的路径)
- 在整个web项目中共享数据
演示:
- 获取文件对应的MIME类型:
代码:
@WebServlet("/servlet01") public class Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServeletContext对象 ServletContext context = this.getServletContext(); String s="a.txt"; //获取对应的MIME类型 String mimeType = context.getMimeType(s); System.out.println(mimeType); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
结果:
2.获取文件的真实路径(真实路径是部署在服务器上的文件路径,也就是真实访问的路径)
- 首先我们先分别在src,web,WEB-INF下分别创建a.txt,b.txt,c.txt文件
然后获得它们部署在服务器中的真实路径:
代码:
@WebServlet("/servlet01") public class Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServeletContext对象 ServletContext context = this.getServletContext(); //获取b.txt文件的真实路径: String brealPath = context.getRealPath("/b.txt"); System.out.println("b.txt的真实路径是:"+brealPath); //获取c.txt文件的真实路径: String crealPath = context.getRealPath("/WEB-INF/c.txt"); System.out.println("c.txt的真实路径是:"+crealPath); //获取a.txt文件的真实路径: String arealPath = context.getRealPath("/WEB-INF/classes/a.txt"); System.out.println("a.txt的真实路径是:"+arealPath); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
结果:
注意:
src下的文件在项目中部署的真实路径在WEB-INF下的classes文件下(src相当于classes)
3.在整个web项目中共享数据
ServeletContext对象的作用域是整个项目:
代码:
@WebServlet("/servlet01") public class Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取ServeletContext对象 ServletContext context = this.getServletContext(); context.setAttribute("name", "zhangsan"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
在资源类2中打开另一个浏览器模拟另一个用户获取:
@WebServlet("/servlet02") public class Servlet02 extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = (String) request.getServletContext().getAttribute("name");//在另一个资源类中获取 System.out.println(name); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
结果: