ServletContext_功能_域对象以及获取文件服务器路径
ServletContext_功能_域对象以及获取文件服务器路径
域对象:共享数据
1.setAttribute(String name,Object value)
2.getAttribute(String name)
3.removeAttribute(String name)
ServletContext对象范围:所有用户所有请求的数据
存储数据:
@WebServlet(name = "ServletContextDemo3", value = "/ServletContextDemo3") public class ServletContextDemo3 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* 获取MIME类型: MIME类型:在互联网通信过程中定义的一种文件数据类型 格式:大类型/小类型 text/html image 方法: 获取:String getMimeType(String file) 2.域对象,共享数据 1.setAttribute(String name,Object value) 2.getAttribute(String name) 3.removeAttribute(String name) 3.获取文件的真实(服务器)路径 */ //1.通过HttpServlet对象获取 ServletContext context = this.getServletContext(); //设置数据 context.setAttribute("msg", "haha"); } }
获取数据
@WebServlet(name = "ServletContextDemo4", value = "/ServletContextDemo4") public class ServletContextDemo4 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* 获取MIME类型: MIME类型:在互联网通信过程中定义的一种文件数据类型 格式:大类型/小类型 text/html image 方法: 获取:String getMimeType(String file) 2.域对象,共享数据 1.setAttribute(String name,Object value) 2.getAttribute(String name) 3.removeAttribute(String name) 3.获取文件的真实(服务器)路径 */ //1.通过HttpServlet对象获取 ServletContext context = this.getServletContext(); //获取数据 Object msg = context.getAttribute("msg"); System.out.println(msg); } }
ServletContext功能获取文件服务器路径
获取文件的真实(服务器)路径
方法:String getRealPath(String path)
@WebServlet(name = "ServletContextDemo5", value = "/ServletContextDemo5") public class ServletContextDemo5 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = this.getServletContext(); //获取文件的服务器路径 String realPath = context.getRealPath("/b.txt");// web目录下资源访问 System.out.println(realPath); String c = context.getRealPath("/WEB-INF/c.txt");// WEB-INF目录下的资源访问 System.out.println(c); String a = context.getRealPath("/day2_text/src/a.txt");// src目录下的资源访问 System.out.println(a); } }

浙公网安备 33010602011771号