java学习基础

来源:互联网 发布:淘宝助理增量下载订单 编辑:程序博客网 时间:2024/05/01 23:44
java 从零开始,学习笔记之基础入门<servlet_文件下载>(二十六)
分类: java基础学习 2013-12-02 10:13 249人阅读 评论(2) 收藏 举报
java从零开始入门基础学习笔记
servlet_文件下载
文件下载
1.        利用BufferedInputStream读取服务器上的文件
2.        利用ServletOutputStream将读取到的字节内容传递到客户端
3.        注意在进行文件下载时,指定被下载文件的类型
 
文件下载步骤:
1.        下载页面。在页面上提供出下载的列表,如果和数据库连接,则动态从数据库中读取文件列表
2.        构建下载的Servlet,来处理下载的请求
 


两个servlet
1.  一个servlet处理显示文件列表
2.  一个servlet负责单独处理下载的事件
 
一个页面
一个页面显示所有文件列表信息
 


Action:视图所对应的活动会话
Dao:数据访问对象
Dto:数据持久(传输)对象
Factory:各种类型的工厂。在slesson2中表示的是连接工厂
Util:工具辅助类,开发中将经常抽象的重复的方法可以汇总之后存放到此包中,以供复用
 
 
文件下载代码:
Web.html
Web.html
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ShowFileAction</servlet-name>
    <servlet-class>com.ibm.action.ShowFileAction</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>download</servlet-name>
    <servlet-class>com.ibm.action.download</servlet-class>
 <!--配置pdf文件下载路径 -->
  <init-param>
  <param-name>pdfdir</param-name>
  <param-value>pdf</param-value>
  </init-param>
  </servlet>
 
 
  <servlet-mapping>
    <servlet-name>ShowFileAction</servlet-name>
    <url-pattern>/showfile</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>download</servlet-name>
    <url-pattern>/download</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
 
 
Index.jsp
Index.jsp
<%@ pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <basehref="<%=basePath%>">
   
    <title>导航页面</title>
    <metahttp-equiv="pragma"content="no-cache">
    <metahttp-equiv="cache-control"content="no-cache">
    <metahttp-equiv="expires"content="0">   
    <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
    <metahttp-equiv="description"content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
 
  <body>
    导航
    <br>
    <ahref="showfile">跳转到下载页面</a>
  </body>
</html>
 
UFile.java
package com.ibm.dto;
/**
 *用户文件类
 *@author123
 *
 */
public class UFile {
   privateint fileId;
   private StringfiName;
public int getFileId() {
    returnfileId;
}
public void setFileId(int fileId) {
    this.fileId = fileId;
}
public String getFiName() {
    returnfiName;
}
public void setFiName(String fiName) {
    this.fiName = fiName;
}
  
}
 
IFileDAO.java
IFileDAO.java
package com.ibm.dao;
 
import java.util.List;
 
import com.ibm.dto.UFile;
 
/**
 *文件操作接口
 *@author123
 *
 */
public interface IFileDAO {
    //ctrl+shift+o批量导包快捷键
    //获得所有文件信息
   public List<UFile> getAllFile();
}
 
 
FileDAOImp.java
FileDAOImp.java
package com.ibm.dao.imp;
 
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
import com.ibm.dao.IFileDAO;
import com.ibm.dto.UFile;
 
public class FileDAOImpimplements IFileDAO {
    //申明连接对象
    private Connectionconn;
    //通过构造函数为对连接对象赋值
    public FileDAOImp(Connection conn){
       this.conn=conn;
    }
    public List<UFile> getAllFile() {
       //文件列表
       List<UFile> list=null;
       Statement stmt=null;
       ResultSet rs=null;
       try {
           list=new ArrayList<UFile>();
           String sql="select * from filetb";
           //获取命令执行对象
           stmt=conn.createStatement();
           //执行sql语句获得结果集
           rs=stmt.executeQuery(sql);
           //边循环边取出文件信息并存到list中
           while(rs.next()){
              UFile ufile=new UFile();
              ufile.setFileId(rs.getInt(1));
              ufile.setFiName(rs.getString(2));
              list.add(ufile);
           }
       } catch (Exception e) {
           //TODO: handle exception
           e.printStackTrace();
       }finally{
           //关闭是由小到大关闭
              try {
                  if(rs!=null){
                  rs.close();
                  }
                  if(stmt!=null){
                     stmt.close();
                  }
                  if(conn!=null){
                     conn.close();
                  }
              } catch (SQLException e) {
                  //TODO Auto-generated catch block
                  e.printStackTrace();
              }
           }
      
      
       return list;
    }
 
}
 
 
Test.java(测试)
Test.java(测试)
package com.ibm.test;
 
import java.util.List;
 
import com.ibm.dao.IFileDAO;
import com.ibm.dto.UFile;
import com.ibm.factory.DAOFactory;
import com.ibm.factory.SqlDAOFactory;
 
public class Test {
    public staticvoid main(String[] args) {
       //根据选择的产品获得DAO工厂
       SqlDAOFactory daoFactory=(SqlDAOFactory)DAOFactory.getDaoFactory(1);
       //获得具体的DAO
       IFileDAO dao=daoFactory.getFileDAO();
       //调用getAllFile方法获得文件信息列表
       List<UFile> list=dao.getAllFile();
        //循环输出获得的信息
       for(UFile file:list){
        System.out.println("文件名是:"+file.getFiName());
        }
    }
 
}
 
 
ShowFileAction.java
ShowFileAction.java
package com.ibm.action;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.ibm.dao.IFileDAO;
import com.ibm.dto.UFile;
import com.ibm.factory.DAOFactory;
import com.ibm.factory.SqlDAOFactory;
 
public class ShowFileActionextends HttpServlet {
 
    /**
     *Constructoroftheobject.
     */
    public ShowFileAction() {
       super();
    }
 
    /**
     *Destructionoftheservlet.<br>
     */
    publicvoid destroy() {
       super.destroy();// Just puts "destroy" string in log
       // Put your code here
    }
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
 
       SqlDAOFactory daoFactory=(SqlDAOFactory)DAOFactory.getDaoFactory(1);
       //获得具体的DAO
       IFileDAO dao=daoFactory.getFileDAO();
       //调用getAllFile方法获得文件信息列表
       List<UFile> list=dao.getAllFile();
        request.setAttribute("filelist", list);
        //服务器内部转发对象将文件信息列表传递到filelist.jsp页面中
        RequestDispatcher rd=request.getRequestDispatcher("filelist.jsp");
        rd.forward(request,response);
    }
 
    public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
 
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out
              .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
       out.println("<HTML>");
       out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
       out.println(" <BODY>");
       out.print("   This is ");
       out.print(this.getClass());
       out.println(", using the POST method");
       out.println(" </BODY>");
       out.println("</HTML>");
       out.flush();
       out.close();
    }
 
    /**
     *Initializationoftheservlet.<br>
     *
     *@throwsServletExceptionifanerroroccurs
     */
    public void init()throws ServletException {
       // Put your code here
    }
 Filelist.java
Filelist.java
<%@ pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@pageimport="com.ibm.dto.UFile"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//从request对象中获得文件列表信息
List<UFile> list=(ArrayList<UFile>)request.getAttribute("filelist");
%>
 
<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <basehref="<%=basePath%>">
   
    <title>My JSP 'filelist.jsp' starting page</title>
   
    <metahttp-equiv="pragma"content="no-cache">
    <metahttp-equiv="cache-control"content="no-cache">
    <metahttp-equiv="expires"content="0">   
    <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
    <metahttp-equiv="description"content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
 
  </head>
 
  <body>
  文件列表
  <hr>
  <table>
  <tr>
  <td>文件名称</td>
  <td>操作</td>
  </tr>
  <%for(UFile file:list){%>
  <tr>
  <td><%=file.getFiName()%></td>
  <!--文件下载连接 -->
  <td><ahref="download?filename=<%=file.getFiName()%>">下载</a></td>
  </tr>
  <% }%>
  </table>
  </body>
</html>
 
 
Download.java
Download.java
package com.ibm.action;
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class downloadextends HttpServlet {
    
    //pdf文件在web应用存放的文件夹名称
    private StringpdfDir;
    /**
     *Constructoroftheobject.
     */
    public download() {
       super();
    }
 
    /**
     *Destructionoftheservlet.<br>
     */
    publicvoid destroy() {
       super.destroy();// Just puts "destroy" string in log
       // Put your code here
    }
 
    /**
     *ThedoGetmethodoftheservlet.<br>
     *
     *Thismethodiscalledwhenaformhasitstagvaluemethodequalstoget.
     *
     *@paramrequesttherequestsendbytheclienttotheserver
     *@paramresponsetheresponsesendbytheservertotheclient
     *@throwsServletExceptionifanerroroccurred
     *@throwsIOExceptionifanerroroccurred
     */
    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
//默认的连接方式的请求都是用doGet方式来处理的
       //获得用户需要下载的文件名称
       String fileName=request.getParameter("filename");
       System.out.println("用户需要下载的文件是:"+fileName);
       //getServletContext获得当前servlet在容器中的上下文信息
       String appPath=this.getServletContext().getRealPath("/");
       System.out.println("服务器中应用所在的根目录是:"+appPath);
      //第一步:拼装需要下载的文件的完整路径
        String filePath=appPath+File.separator+"pdf"+File.separator+fileName;
        System.out.println("下载的文件所在的完整路径是:"+filePath);
        //第二步指定文件下载的类型,并将相关文件信息写出到客户端浏览器的头部
        response.setContentType("application/pdf");
        //以附件的形式传递到客户端附件名称由"attachment;filename="中的filename指定
        response.addHeader("Content-Disposition","attachment;filename="+fileName);
        //第三步:边读取服务器上的文件边以字节流的形式向客户端输出
        BufferedInputStream br=new BufferedInputStream(new FileInputStream(filePath));
        //读取的大小
        byte[] buffer=newbyte[1024];
        int len=0;
        //获取网络传递流对象
        ServletOutputStream os=response.getOutputStream();
        while((len=br.read(buffer))!=-1){
        os.write(buffer,0,len);
        }
        //都写完后关闭流
        os.flush();
        os.close();
        br.close();
       
    }
 
    /**
     *ThedoPostmethodoftheservlet.<br>
     *
     *Thismethodiscalledwhenaformhasitstagvaluemethodequalstopost.
     *
     *@paramrequesttherequestsendbytheclienttotheserver
     *@paramresponsetheresponsesendbytheservertotheclient
     *@throwsServletExceptionifanerroroccurred
     *@throwsIOExceptionifanerroroccurred
     */
    publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
 
       response.setContentType("text/html");
       PrintWriter out = response.getWriter();
       out
              .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
       out.println("<HTML>");
       out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
       out.println(" <BODY>");
       out.print("   This is ");
       out.print(this.getClass());
       out.println(", using the POST method");
       out.println(" </BODY>");
       out.println("</HTML>");
       out.flush();
       out.close();
    }
 
    /**
     *Initializationoftheservlet.<br>
     *
     *@throwsServletExceptionifanerroroccurs
     */
    public void init()throws ServletException {
       // Put your code here
      
          //pdfdir来自于web.xml中servlet节点中配置的param-name
       this.getInitParameter("pdfdir");
       System.out.println("pdf所存放的路径名是:"+pdfDir);
 
      
    }
 
}
}
原创粉丝点击