Java Servlet簡単なインスタンス共有(ファイルアップロードのダウンロードdemo)


プロジェクト構造

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.簡単な例
Show Servlet.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; 
  } 

}
fileuplad.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); 
      } 
   }

}
down load.

<!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の簡単な実例は共有します。つまり、小編集が皆さんに共有している内容の全部です。参考にしてほしいです。どうぞよろしくお願いします。