前段时间事情比较多,导致二月份没有记录自己的学习情况。最近接触了servlet,参考韩老师的教程自己写了一个web站点文件下载的小项目,该项目中还加入了简单的反盗链技术。

  1、首先创建一个SharedFilesServlet用于返回一个文件分享界面

 package com.hyman.view;

 import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class SharedFilesServlet
*/
public class SharedFilesServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public SharedFilesServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script type='text/javascript' language='javascript'>"
+ "function fileDown(obj){"
+ "var resourceName = '';"
+ "var buttonId = obj.getAttribute('id');"
+ "var eleName = buttonId.substring(0,3) + 'File';"
+ "resourceName = document.getElementsByName(eleName)[0].value;"
+ "var url = '/SharingSite/DownFileServlet?fileName=' + resourceName;"
+ "window.location.href=url;"
+ "}"
+ "</script>");
out.println("<h1>文件共享网站</h1>");
out.println("mp3资源:<input type='text' name='mp3File' />&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value ='点击下载' id='mp3Down' onclick='fileDown(this)' /><br/>");
out.println("avi资源:<input type='text' name='aviFile' />&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value ='点击下载' id='aviDown' onclick='fileDown(this)' /><br/>");
out.println("jpg资源:<input type='text' name='jpgFile' />&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value ='点击下载' id='jpgDown' onclick='fileDown(this)' /><br/>");
out.println("txt资源:<input type='text' name='txtFile' />&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' value ='点击下载' id='txtDown' onclick='fileDown(this)' /><br/>");
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
} }

  2、然后创建一个控制器,来判断是否盗链,以及处理文件下载逻辑:

 package com.hyman.controller;

 import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class DownFileServlet
*/
public class DownFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public DownFileServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html; charset=utf-8");
String referer = request.getHeader("Referer");
if (referer == null || !referer.startsWith("http://localhost:8080/SharingSite/")) {
response.sendRedirect("/SharingSite/AntiPirateLink");
} else {
String fileName = request.getParameter("fileName");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
String path = this.getServletContext().getRealPath("/resources/"+fileName);
FileInputStream fis = null;
OutputStream os = null;
try {
fis = new FileInputStream(new File(path));
byte buff[] = new byte[1024];
int len = 0;
os = response.getOutputStream();
while ((len = fis.read(buff)) > 0) {
os.write(buff, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
} finally {
if (os != null) os.close();
if (fis != null) fis.close();
}
} } /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
} }

  3、创建一个AntiPirateLink返回盗链提醒界面,并在10秒后自动刷新跳转到SharedFilesServlet

 package com.hyman.view;

 import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class AntiPirateLink
*/
public class AntiPirateLink extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public AntiPirateLink() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script type='text/javascript' language='javascript'>"
+ "var i = 10;"
+ "function showTime(){"
+ "if(i > 0) {document.getElementById('time').innerHTML = '请不要盗链下载... ' + i +' 秒后自动跳转到下载首页...';"
+ "i--;}"
+ "}"
+ "setInterval('showTime()',1000);"
+ "</script>");
out.println("<span id='time'></span>");
response.setHeader("Refresh", "10; url=/SharingSite/SharedFilesServlet");
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
} }

【分析】文件下载部分实现步骤:

1、response.setHeader("Content-Disposition", "attachment; filename="+fileName);在http回复消息头中的Content-Disposition中指明下文件的文件名;
2、调用this.getServletContext().getRealPath("/resources/"+fileName);函数获取到文件的全路径;
3、使用文件流FileInputStream将文件读入到服务器内存,重要要用到缓存处理,然后再调用response的getOutputStream()方法获得向客户端写文件的输出文件流;

Servlet实现web站点文件下载功能示例的更多相关文章

  1. 【Servlet】java web 文件下载功能实现

    需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片 两种实现方法: 一:通过超链接实现下载 在HTML网页中,通过超链接链接到要下载的文件的地址 <!DOCTYPE html> & ...

  2. 解决springmvc中文件下载功能中使用javax.servlet.ServletOutputStream out = response.getOutputStream();后运行出异常但结果正确的问题

    问题描述: 在springmvc中实现文件下载功能一般都会使用javax.servlet.ServletOutputStream out = response.getOutputStream();封装 ...

  3. WebLech是一个功能强大的Web站点下载与镜像工具

    WebLech是一个功能强大的Web站点下载与镜像工具.它支持按功能需求来下载web站点并能够尽可能模仿标准Web浏览器的行为.WebLech有一个功能控制台并采用多线程操作. http://sour ...

  4. java web文件下载功能实现 (转)

    http://blog.csdn.net/longshengguoji/article/details/39433307 需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片 两种实现方法: 一 ...

  5. 启动Nginx目录浏览功能及 让用户通过用户名密码认证访问web站点

    一.启动Nginx目录浏览功能  [root@abcdocker extra]# cat w.conf server { listen 80; server_name IP地址; location / ...

  6. 为Windows Azure Web站点添加MIME类型解决文件下载失败的问题

    这几天在倒腾Autodesk 360 Viewer,前面的文章也介绍过了,这将是一个全新的在线模型浏览工具.我做了个实验,把A360Viewer放在一个web 站点,然后发布到Windows Azur ...

  7. Java精选笔记_Tomcat开发Web站点

    Tomcat开发Web站点 Web开发的相关知识 B/S架构和C/S架构 C/S架构是Client/Server的简写,也就是客户机/服务器端的交互.常见应用 : QQ. 迅雷. 360. 旺旺等 B ...

  8. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点

    在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...

  9. JAVA文件下载功能问题解决日志

    今天给报告系统做了个下载功能,遇到了挺多问题,通过查资料一一解决了. 1.首先遇到的问题是:java后台的输出流输出之后,没有任何报错,浏览器端不弹出保存文件的对话框,原本是ajax请求到后台的con ...

随机推荐

  1. Understanding Spring Web Application Architecture: The Classic Way--转载

    原文地址:http://www.petrikainulainen.net/software-development/design/understanding-spring-web-applicatio ...

  2. byte[] bytes和string转换

    public static string ToHexString ( byte[] bytes ) // 0xae00cf => "AE00CF "        {     ...

  3. 使用 Feedly RSS阅读器订阅技术大牛的博客

    这几天一直都在自己看书,可是书上面的东西都比较落后一点,而且没有大牛博文上的东西讲的深入,可是来回跳转各位大牛的博客又非常的麻烦,有一些公众账号虽然也会推荐一些知识内容,可是你应该有过看到多个公众号发 ...

  4. git merge branches

    git clone url #克隆新的版本库 git init git pull repo_name #有关联的远程库,抽取并和本地合并 git fetch remote_repo_name #抽取并 ...

  5. hibernate 查询

                String hql = "select * from Commodity where commodityName like :commodityname" ...

  6. CentOS(四)--Linux系统的启动级别

    对于绝大多数Linux程序员来说,进入Linux系统后一般看到的是黑乎乎的界面(开发模式),因为系统如果启动选择开发模式,会减少启动时间,优化内存等.但是通常我们刚安装完Linux系统,然后进去以后是 ...

  7. poj 1848 树形dp

    思路:表示我很弱,这个想不出dp方程,参考网上代码 #include<iostream> #include<algorithm> #include<cstring> ...

  8. 初学JSP+Servlet常见的错误

    web编程中常见的错误: 一.404(要访问的资源没有找到) 1.web程序有没有部署(将项目到tomcat中) 2.url有没有写错(包括大小写,包括项目有没有重命名) 3.有没有将jsp/html ...

  9. MongoDB - Installing MongoDB on Linux

    1. 下载最新稳定版本的安装包. [huey@huey mongodb]$ wget -c --no-check-certificate https://fossies.org/linux/misc/ ...

  10. ASP多行多列显示代码

    <table width="98%" border="0" align="center"> <tr> <% S ...