Servlet ServletContext
来源:互联网 发布:冰点文库网络连接失败 编辑:程序博客网 时间:2024/06/05 23:07
简介
WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。可以通过ServletConfig.getServletContext方法获得ServletContext对象。
由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。
getRequestDispatcher()
参考这篇博客
http://twilight.net.cn/2017/04/09/Servlet-%E4%BD%BF%E7%94%A8RequestDispathcher%E8%B0%83%E6%B4%BE%E8%AF%B7%E6%B1%82/
getResourcePaths(“url”)
url 必须以/开头
for(String temp : getServletContext().getResourcePaths("/")){ output.println(temp); }
效果如下
/JSP-useBean//FormTest.html/AutoLogin.jsp/Hello.jsp/Cookie//Main.html/CheckNum//META-INF//index.jsp/test.html/WEB-INF//includes//JSP-Include//AutoLogin.html/error.jsp
获取webRoot下的所有图片
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter output = resp.getWriter(); ServletContext context = getServletContext(); // '/' 表示 WebRoot for(String temp : context.getResourcePaths("/img")){ temp = temp.substring(temp.indexOf("/")+1); output.println("<img src='"+temp+"' width=200 height=200></img>"); } }
getResourceAsStream(“url”)
获取文件流,返回类型是InputStream,URL必须以”/”开头
向页面中发送图片
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = req.getServletContext(); // 获取输入流 InputStream input = context.getResourceAsStream("/img/P70114-101325.jpg"); // 获取输出流 OutputStream output = resp.getOutputStream(); byte [] data = new byte [1024]; int len = 0 ; while(-1 != (len = input.read(data))){ output.write(data,0,len); } output.close(); input.close(); }
这是从服务器端向客户端发送文件,如果需要接受客户端发来的文件,具体操作方式请参考
Servlet 上传文件
0 0
- Servlet:ServletContext
- Servlet ServletContext
- [servlet] ServletContext
- javax.servlet.ServletContext接口
- javax.servlet.ServletContext翻译
- Servlet之ServletContext
- Servlet上下文ServletContext接口
- Servlet中的ServletContext对象
- Servlet注意+ServletConfig+ServletContext
- Servlet ---- ServletContext接口
- Servlet中的ServletContext
- Servlet API 之ServletContext
- Servlet之ServletContext总结
- 【servlet】servletContext / servletRequest/servletResponse
- Servlet ServletContext类
- Servlet------ServletContext接口
- Servlet、servletConfig、ServletContext简介
- [Servlet]研究ServletContext对象
- 【BZOJ4719】[Noip2016]天天爱跑步
- [一]RabbitMQ-客户端源码之ConnectionFactory
- ElasticSearch 入门介绍
- kubernetes 源码分析之kubeadm(一)
- 漫步数理统计十八——相关系数
- Servlet ServletContext
- 什么是FEC/NACK/RTX
- 查询 函数
- MySQL函数
- 51nod 1001 数组中和等于K的数对【二分】
- fputs函数和fputc函数
- 二叉树的遍历 递归以及非递归
- android 获取SHA1值
- Tomcat7.0 启动时,webapps目录下的项目没有加载