JavaWeb——ServletContext对象的使用及文件下载案例实战

举报
Winter_world 发表于 2021/09/29 00:48:30 2021/09/29
【摘要】 目录 1 ServletContext对象 1.1 获取MIME类型 1.2 域对象:共享数据 1.3 获取文件的真实路径 2 文件下载案例实战 1 ServletContext对象 ServletContext代表整个web应用,可以和程序的容器(服务器)来通信,功能如下: 获取MIME类型;域对...

目录

1 ServletContext对象

1.1 获取MIME类型

1.2 域对象:共享数据

1.3 获取文件的真实路径

2 文件下载案例实战


1 ServletContext对象

ServletContext代表整个web应用,可以和程序的容器(服务器)来通信,功能如下:

  • 获取MIME类型;
  • 域对象:共享数据;
  • 获取文件的真实路径(服务器路径);

ServletContextd的获取方式:

  • 通过request对象获取,request.getServletContext();
  • 通过HttpServlet获取,this.getServletContext();

  
  1. @WebServlet("/servletContextDemo1")
  2. public class ServletContextDemo1 extends HttpServlet {
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. //ServletContext对象的获取
  5. //通过request对象获取
  6. ServletContext context1 = request.getServletContext();
  7. //通过HttpServlet获取
  8. ServletContext context2 = this.getServletContext();
  9. System.out.println(context1);
  10. System.out.println(context2);
  11. System.out.println(context1==context2); //true
  12. }
  13. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  14. this.doPost(request,response);
  15. }
  16. }

1.1 获取MIME类型

MIME类型,是在互联网通信过程中定义的一种文件数据类型:

  • 格式:大类型/小类型,如 text/html  image/jpeg
  • 获取方法:String getMIMEType(String file)

  
  1. @WebServlet("/servletContextDemo2")
  2. public class ServletContextDemo2 extends HttpServlet {
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. //ServletContext功能
  5. ServletContext context = this.getServletContext();
  6. //定义文件名称
  7. String fileName = "a.jpg";
  8. String mimeType = context.getMimeType(fileName);
  9. System.out.println(mimeType); //image/jpeg
  10. }
  11. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. this.doPost(request,response);
  13. }
  14. }

1.2 域对象:共享数据

1)setAttribute(String name, Object value)

2)getAttribute(String name)

3)removeAttribute(String name)

ServletContext的对象范围是最大的,可以共享所以用户的数据,如下举例,在demo3中设置数据,在访问demo4,可以看见打印的hello。

注意:因为范围比较大,且生命周期很长(跟随服务器的启用和关闭),所以应用时一定要谨慎。


  
  1. @WebServlet("/servletContextDemo3")
  2. public class ServletContextDemo3 extends HttpServlet {
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. //ServletContext功能
  5. ServletContext context = this.getServletContext();
  6. //设置数据
  7. context.setAttribute("msg","hello");
  8. }
  9. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  10. this.doPost(request,response);
  11. }
  12. }

  
  1. @WebServlet("/servletContextDemo4")
  2. public class ServletContextDemo4 extends HttpServlet {
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. //ServletContext功能
  5. ServletContext context = this.getServletContext();
  6. //获取数据
  7. Object msg = context.getAttribute("msg");
  8. System.out.println(msg);
  9. }
  10. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  11. this.doPost(request,response);
  12. }
  13. }

1.3 获取文件的真实路径

方法:String getRealPath(String path)

注意src、web、web/WEB-INF不同目录下的资源路径:


  
  1. @WebServlet("/servletContextDemo5")
  2. public class ServletContextDemo5 extends HttpServlet {
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. //ServletContext功能
  5. ServletContext context = this.getServletContext();
  6. //获取文件真实路径(服务器路径)
  7. //先在src、web、web/WEB-INF目录下分别建个a.txt、b.txt、c.txt
  8. String b = context.getRealPath("/b.txt"); //web目录下资源访问
  9. System.out.println(b);
  10. // File file = new File(realPath);
  11. String c = context.getRealPath("/WEB-INF/c.txt");//WEB-INF目录下资源访问
  12. System.out.println(c);
  13. String a = context.getRealPath("/WEB-INF/classes/a.txt");//src目录下的资源访问
  14. System.out.println(a);
  15. }
  16. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  17. this.doPost(request,response);
  18. }
  19. }

2 文件下载案例实战

通过对http请求和响应,以及上一节ServletContext的学习,本章以文件下载作为一个综合案例进行实战练习。

【需求】:

  • 1)页面显示超链接
  • 2)点击超链接后弹出下载提示框
  • 3)完成图片下载

【分析】:

  • 1)如果超链接指向的资源可以被浏览器解析,如图片,则会直接在浏览器显示,若不能解析,才会弹出下载提示框;
  • 2)需求是任何资源都要弹出下载提示框
  • 3)需要使用响应头设置资源的打开方式:content-disposition:attachment;filename=xxx

【实现步骤】:

  • 1)定义页面,编辑超链接hred属性,指向servlet,传递资源名filename
  • 2)定义servlet:
          --获取文件名称;
          --使用字节输入流加载文件进内存;  
          --指定response响应头:content-disposition:attachment;filename=xxx;
          --将数据写出到response输出流。

【代码实现】:

在web目录下新建img,其中存放一个图片

download.html:


  
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <a href="/response/img/test.png">图片</a>
  9. <hr>
  10. <a href="/response/downloadServlet?filename=test.png">图片-跳转至servlet-出现下载提示框</a>
  11. </body>
  12. </html>

DownloadServlet:


  
  1. @WebServlet("/downloadServlet")
  2. public class DownloadServlet extends HttpServlet {
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. //1、获取请求参数
  5. String filename = request.getParameter("filename");
  6. //2、使用字节输入流加载文件至内存
  7. String realPath = this.getServletContext().getRealPath("/img/" + filename);
  8. FileInputStream fis = new FileInputStream(realPath);
  9. //3、设置response响应头
  10. response.setContentType(this.getServletContext().getMimeType(filename));
  11. response.setHeader("content-disposition","attachment"+filename);
  12. //4、将输入流的数据写出到输出流中
  13. ServletOutputStream sos = response.getOutputStream();
  14. byte[] buff = new byte[1024*8];
  15. int length = 0;
  16. while (fis.read(buff)!= -1){
  17. sos.write(buff,0,length);
  18. }
  19. fis.close();
  20. }
  21. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  22. this.doPost(request,response);
  23. }
  24. }

【中文文件名的问题】:若我们把test.png更换为  测试图片.png,会发现问题,且不同浏览器表现不一,解决思路:

1)获取客户端使用的浏览器版本信息;

2)根据不同的版本信息,设置filename编码方式不同


  
  1. public class DownLoadUtils {
  2. public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {
  3. if (agent.contains("MSIE")) {
  4. // IE浏览器
  5. filename = URLEncoder.encode(filename, "utf-8");
  6. filename = filename.replace("+", " ");
  7. } else if (agent.contains("Firefox")) {
  8. // 火狐浏览器
  9. BASE64Encoder base64Encoder = new BASE64Encoder();
  10. filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
  11. } else {
  12. // 其它浏览器
  13. filename = URLEncoder.encode(filename, "utf-8");
  14. }
  15. return filename;
  16. }
  17. }

作于202007191805,已归档

———————————————————————————————————

本文为博主原创文章,转载请注明出处!

若本文对您有帮助,轻抬您发财的小手,关注/评论/点赞/收藏,就是对我最大的支持!

祝君升职加薪,鹏程万里!

文章来源: winter.blog.csdn.net,作者:Winter_world,版权归原作者所有,如需转载,请联系作者。

原文链接:winter.blog.csdn.net/article/details/107445514

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。