Java Servlet简单实例分享(文件上传下载demo)

所属分类: 软件编程 / java 阅读数: 30
收藏 0 赞 0 分享

项目结构

src
  com
    servletdemo
        DownloadServlet.java
        ShowServlet.java
        UploadServlet.java
        
WebContent
  jsp
    servlet
        download.html
        fileupload.jsp
        input.jsp
        
  WEB-INF
    lib
        commons-fileupload-1.3.1.jar
        commons-io-2.4.jar

1.简单实例

ShowServlet.java

package com.servletdemo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ShowServlet
 */
@WebServlet("/ShowServlet")
public class ShowServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  PrintWriter pw=null;  
  /**
   * @see HttpServlet#HttpServlet()
   */
  public ShowServlet() {
    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
    this.doPost(request, response);
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    request.setCharacterEncoding("gb2312");
    response.setContentType("text/html;charset=gb2312");
    pw=response.getWriter();
    String name=request.getParameter("username");
    String password=request.getParameter("password");
    pw.println("user name:" + name);
    pw.println("<br>");
    pw.println("user password:" + password);
  }

}

input.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>servlet demo</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/ShowServlet"> 
    <table> 
      <tr> 
        <td>name</td> 
        <td><input type="text" name="username"></td> 
      </tr> 
      <tr> 
        <td>password</td> 
        <td><input type="text" name="password"></td> 
      </tr> 
      <tr> 
        <td><input type="submit" value="login"></td> 
        <td><input type="reset" value="cancel"></td> 
      </tr> 
    </table> 
  </form>
</body>
</html>

2.文件上传实例

UploadServlet.java

package com.servletdemo;

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.io.PrintWriter; 
import java.text.DateFormat; 
import java.util.Date; 
import java.util.List; 
import java.util.UUID; 

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.ProgressListener; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/servlet/UploadServlet")
public class UploadServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
    
  /**
   * @see HttpServlet#HttpServlet()
   */
  public UploadServlet() {
    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
    //设置编码 
    request.setCharacterEncoding("UTF-8"); 
    response.setContentType("text/html;charset=UTF-8"); 
    PrintWriter pw = response.getWriter(); 
    try { 
      //设置系统环境 
      DiskFileItemFactory factory = new DiskFileItemFactory(); 
      //文件存储的路径 
      String storePath = getServletContext().getRealPath("/WEB-INF/files"); 
      //判断传输方式 form enctype=multipart/form-data 
      boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
      if(!isMultipart) 
      { 
        pw.write("传输方式有错误!"); 
        return; 
      } 
      ServletFileUpload upload = new ServletFileUpload(factory); 
      upload.setFileSizeMax(4*1024*1024);//设置单个文件大小不能超过4M 
      upload.setSizeMax(4*1024*1024);//设置总文件上传大小不能超过6M 
      //监听上传进度 
      upload.setProgressListener(new ProgressListener() { 
 
        //pBytesRead:当前以读取到的字节数 
        //pContentLength:文件的长度 
        //pItems:第几项 
        public void update(long pBytesRead, long pContentLength, 
            int pItems) { 
          System.out.println("已读去文件字节 :"+pBytesRead+" 文件总长度:"+pContentLength+"  第"+pItems+"项"); 
           
        } 
      }); 
      //解析 
      List<FileItem> items = upload.parseRequest(request); 
      for(FileItem item: items) 
      { 
        if(item.isFormField())//普通字段,表单提交过来的 
        { 
          String name = item.getFieldName(); 
          String value = item.getString("UTF-8"); 
          System.out.println(name+"=="+value); 
        }else 
        { 
//         String mimeType = item.getContentType(); 获取上传文件类型 
//         if(mimeType.startsWith("image")){ 
          InputStream in =item.getInputStream(); 
          String fileName = item.getName();  
          if(fileName==null || "".equals(fileName.trim())) 
          { 
            continue; 
          } 
          fileName = fileName.substring(fileName.lastIndexOf("\\")+1); 
          fileName = UUID.randomUUID()+"_"+fileName; 
           
          //按日期来建文件夹 
          String newStorePath = makeStorePath(storePath); 
          String storeFile = newStorePath+"\\"+fileName; 
          OutputStream out = new FileOutputStream(storeFile); 
          byte[] b = new byte[1024]; 
          int len = -1; 
          while((len = in.read(b))!=-1) 
          { 
             out.write(b,0,len);     
          } 
          in.close(); 
          out.close(); 
          item.delete();//删除临时文件 
        } 
       } 
//     } 
    }catch(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException e){  
       //单个文件超出异常 
      pw.write("单个文件不能超过4M"); 
    }catch(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e){ 
      //总文件超出异常 
      pw.write("总文件不能超过6M"); 
       
    }catch (FileUploadException e) { 
      e.printStackTrace(); 
    }
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
  
  private String makeStorePath(String storePath) { 
    
    Date date = new Date(); 
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM); 
    String s = df.format(date); 
    String path = storePath+"\\"+s; 
    File file = new File(path); 
    if(!file.exists()) 
    { 
      file.mkdirs();//创建多级目录,mkdir只创建一级目录 
    } 
    return path; 
      
  } 
  private String makeStorePath2(String storePath, String fileName) { 
    int hashCode = fileName.hashCode(); 
    int dir1 = hashCode & 0xf;// 0000~1111:整数0~15共16个 
    int dir2 = (hashCode & 0xf0) >> 4;// 0000~1111:整数0~15共16个 
   
    String path = storePath + "\\" + dir1 + "\\" + dir2; // WEB-INF/files/1/12 
    File file = new File(path); 
    if (!file.exists()) 
      file.mkdirs(); 
   
    return path; 
  } 

}

fileupload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>

<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload File Demo</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/servlet/UploadServlet" method="post" enctype="multipart/form-data"> 
  user name<input type="text" name="username"/> <br/> 
  <input type="file" name="f1"/><br/> 
  <input type="file" name="f2"/><br/> 
  <input type="submit" value="save"/> 
 </form>
</body>
</html>

3.文件下载实例

DownloadServlet.java

package com.servletdemo;

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.io.PrintWriter; 



import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletResponse; 

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
    
  /**
   * @see HttpServlet#HttpServlet()
   */
  public DownloadServlet() {
    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
    download1(response); 
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
  }
  
  public void download1(HttpServletResponse response) throws IOException{ 
    //获取所要下载文件的路径 
     String path = this.getServletContext().getRealPath("/files/web配置.xml"); 
     String realPath = path.substring(path.lastIndexOf("\\")+1); 
   
     //告诉浏览器是以下载的方法获取到资源 
     //告诉浏览器以此种编码来解析URLEncoder.encode(realPath, "utf-8")) 
    response.setHeader("content-disposition","attachment; filename="+URLEncoder.encode(realPath, "utf-8")); 
    //获取到所下载的资源 
     FileInputStream fis = new FileInputStream(path); 
     int len = 0; 
      byte [] buf = new byte[1024]; 
      while((len=fis.read(buf))!=-1){ 
        response.getOutputStream().write(buf,0,len); 
      } 
   }

}

download.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Download Demo</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="this is my page"> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<a href = "/JavabeanDemo/DownloadServlet">download</a>
</body>
</html>

以上这篇Java Servlet简单实例分享(文件上传下载demo)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Java的面向对象编程基本概念学习笔记整理

这篇文章主要介绍了Java的面向对象编程基本概念学习笔记整理,包括类与方法以及多态等支持面向对象语言中的重要特点,需要的朋友可以参考下
收藏 0 赞 0 分享

Eclipse下编写java程序突然不会自动生成R.java文件和包的解决办法

这篇文章主要介绍了Eclipse下编写java程序突然不会自动生成R.java文件和包的解决办法 的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

基于Java实现杨辉三角 LeetCode Pascal's Triangle

这篇文章主要介绍了基于Java实现杨辉三角 LeetCode Pascal's Triangle的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Java中Spring获取bean方法小结

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架,如何在程序中获取Spring配置的bean呢?下面通过本文给大家介绍Java中Spring获取bean方法小结,对spring获取bean方法相关知识感兴趣的朋友一起学习吧
收藏 0 赞 0 分享

如何计算Java对象占用了多少空间?

在Java中没有sizeof运算符,所以没办法知道一个对象到底占用了多大的空间,但是在分配对象的时候会有一些基本的规则,我们根据这些规则大致能判断出来对象大小,需要的朋友可以参考下
收藏 0 赞 0 分享

剖析Java中的事件处理与异常处理机制

这篇文章主要介绍了Java中的事件处理与异常处理机制,讲解Java是如何对事件或者异常作出响应以及定义异常的一些方法,需要的朋友可以参考下
收藏 0 赞 0 分享

详解Java的Struts2框架的结构及其数据转移方式

这篇文章主要介绍了详解Java的Struts2框架的结构及其数据转移方式,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
收藏 0 赞 0 分享

Java封装好的mail包发送电子邮件的类

本文给大家分享了2个java封装好的mail包发送电子邮件的类,并附上使用方法,小伙伴们可以根据自己的需求自由选择。
收藏 0 赞 0 分享

在Java的Struts中判断是否调用AJAX及用拦截器对其优化

这篇文章主要介绍了在Java的Struts中判断是否调用AJAX及用拦截器对其优化的方法,Struts框架是Java的SSH三大web开发框架之一,需要的朋友可以参考下
收藏 0 赞 0 分享

java多线程Future和Callable类示例分享

JAVA多线程实现方式主要有三种:继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。其中前两种方式线程执行完后都没有返回值,只有最后一种是带返回值的。今天我们就来研究下Future和Callab
收藏 0 赞 0 分享
查看更多