一、servletcontext之获得方法
servletcontext有两种获得方法:一个是在request类中,另一个是在HttpServlet类中,如代码所示:
public class servletDemo10_ServletContext 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 sc = req.getServletContext();
//方式二
ServletContext sc2 = this.getServletContext();
}
}
二、servletcontext之获得文件的格式Mime
String filename = "j.jpg";
String str = sc2.getMimeType(filename);
System.out.println(str);
输出为
image/jpeg
三、servletcontext之域对象
servletcontext是域对象,所有服务器上的Servlet都可以共享数据,有三个基本方法。所以,三思而后用,过度使用会导致服务器内存压力过大
sc.setAttribute("nihao","haha");
String str = (String)sc.getAttribute("nihao");
sc.removeAttribute("nihao");
四、servletcontext之获取服务器文件真实路径
为了测试,一开始建立了a.txt b.txt c.tx三个文件分别放在如图所示的目录
(1)获取a.txt
String realpath3 = context.getRealPath("/WEB-INF/classes/a.txt");
File file3 = new File(realpath3);
InputStream is3 = new FileInputStream(file3);
System.out.println(realpath3);
(2)获取b.txt
String realpath = context.getRealPath("/b.txt");
File file = new File(realpath);
System.out.println(realpath);
(3)获取c.txt
String realpath = context.getRealPath("/WEB-INF/c.txt");
File file = new File(realpath);
System.out.println(realpath);
备注1:
使用类加载器虽然也能加载文件,但是只能加载src目录下的文件,无法加载web目录下的文件
Thread.currentThread().getContextClassLoader().getResourceAsStream("a.txt");
备注2:
在Servlet中的File文件中的默认的路径是tomcat安装路径中的bin路径
new File("test.png");
发现,test.png文件会存储在E:\tomcat\apache-tomcat-8.5.59\bin,所以在tomcat中一般不建议这样使用,有可能会损坏服务器的bin文件