ServletContext_功能_域物件以及獲取檔案伺服器路徑
阿新 • • 發佈:2022-12-09
ServletContext_功能_域物件以及獲取檔案伺服器路徑
域物件:共享資料
1.setAttribute(String name,Object value)
2.getAttribute(String name)
3.removeAttribute(String name)
ServletContext物件範圍:所有使用者所有請求的資料
儲存資料:
@WebServlet(name = "ServletContextDemo3", value = "/ServletContextDemo3") public class ServletContextDemo3 extendsHttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, 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); } }