ServletContext_獲取以及獲取MIME型別
阿新 • • 發佈:2022-12-09
ServletContext_獲取以及獲取MIME型別
1.獲取:
1.通過request物件獲取
request.getServletContext();
2.通過HTTPServlet獲取
this.getServletContext();
@WebServlet(name = "ServletContextDemo1", value = "/ServletContextDemo1") public class ServletContextDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException { this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* ServletContext物件獲取 1.通過request物件獲取 request.getServletContext(); 2.通過HTTPServlet獲取 this.getServletContext();*/ //1.通過request物件獲取 ServletContext context1 = request.getServletContext(); //2.通過HTTPServlet獲取 ServletContext context2 = this.getServletContext(); System.out.println(context1); System.out.println(context2); System.out.println(context1==context2); } }
獲取MIME型別:
MIME型別:在網際網路通訊過程中定義的一種檔案資料型別
格式:大型別/小型別 text/html image
方法:
獲取:String getMimeType(String file)
2.域物件,共享資料
3.獲取檔案的真實(伺服器)路徑
@WebServlet(name = "ServletContextDemo2", value = "/ServletContextDemo2") public class ServletContextDemo2 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.域物件,共享資料 3.獲取檔案的真實(伺服器)路徑 */ //1.通過HttpServlet物件獲取 ServletContext context = this.getServletContext(); //2.定義檔名稱 String filename = "a.jpg"; // image/jpeg //3.獲取MIME型別 String mimeType = context.getMimeType(filename); System.out.println(mimeType); } }