tomcat——servletcontext学习笔记

一、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文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值