2013-04-30 70 views
-1

我有一個用於文件上傳的主窗體。一個servlet正在完成上傳工作。所有文件都具有相同的名稱結構,所以我將它分開並獲取參數。然後我將它們放入JSONArray,然後我將這些參數傳遞給索引頁面,在我的情況下命名爲test.jsp使用json數據填充表格/表格

問題是,我不知道如何創建一個表,並用JSON中的細節填充它。

這裏我的索引(test.jsp的)頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8" 
    pageEncoding="UTF-8"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<!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=UTF-8"> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
<title>File Upload Demo</title> 
</head> 
<body> 
    <center> 
     <form method="post" action="uploadFile" enctype="multipart/form-data"> 
      Select file to upload: 
      <input type="file" name="uploadFile" multiple/> 
      <br/><br/> 
      <input type="submit" value="Upload" /> 
     </form> 
     ${message} 
     <br /> 
     ${jsonString} 
    </center> 
</body> 
</html> 

我使用${jsonString}來檢查,如果JSON是正確傳遞。 它看起來像:

[ 
    { 
     "MDName": "Angel Bankov", 
     "MDCode": "2288", 
     "month": "April", 
     "year": "2013", 
     "target/achieved": "Target" 
    }, 
    { 
     "MDName": "Angel Bankovsky", 
     "MDCode": "2289", 
     "month": "April", 
     "year": "2015", 
     "target/achieved": "Achieved" 
    } 
] 

這裏我的servlet是:

import java.io.File; 
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 org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.json.JSONArray; 
import org.json.JSONObject; 

/** 
* A Java servlet that handles file upload from client. 
* 
* @author www.codejava.net 
*/ 
public class FileUploadServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 

    // location to store file uploaded 
    private static final String UPLOAD_DIRECTORY = "upload"; 

    // upload settings 
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; 
    private static final int MAX_FILE_SIZE  = 1024 * 1024 * 40; 
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; 

    /** 
    * Upon receiving file upload submission, parses the request to read 
    * upload data and saves the file on disk. 
    */ 
    protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // checks if the request actually contains upload file 
     if (!ServletFileUpload.isMultipartContent(request)) { 
      // if not, we stop here 
      PrintWriter writer = response.getWriter(); 
      writer.println("Error: Form must has enctype=multipart/form-data."); 
      writer.flush(); 
      return; 
     } 
     //JSON Declaration 
     JSONArray splitDetailsArray = new JSONArray(); 

     // configures upload settings 
     DiskFileItemFactory factory = new DiskFileItemFactory(); 
     // sets memory threshold - beyond which files are stored in disk 
     factory.setSizeThreshold(MEMORY_THRESHOLD); 
     // sets temporary location to store files 
     factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); 

     ServletFileUpload upload = new ServletFileUpload(factory); 

     // sets maximum size of upload file 
     upload.setFileSizeMax(MAX_FILE_SIZE); 

     // sets maximum size of request (include file + form data) 
     upload.setSizeMax(MAX_REQUEST_SIZE); 

     // constructs the directory path to store upload file 
     // this path is relative to application's directory 
     String uploadPath = getServletContext().getRealPath("") 
       + File.separator + UPLOAD_DIRECTORY; 

     // creates the directory if it does not exist 
     File uploadDir = new File(uploadPath); 
     if (!uploadDir.exists()) { 
      uploadDir.mkdir(); 
     } 

     try { 
      // parses the request's content to extract file data 
      @SuppressWarnings("unchecked") 
      List<FileItem> formItems = upload.parseRequest(request); 

      if (formItems != null && formItems.size() > 0) { 
       // iterates over form's fields 
       for (FileItem item : formItems) { 
        // processes only fields that are not form fields 
        if (!item.isFormField()) { 
         String fileName = new File(item.getName()).getName(); 
         String filePath = uploadPath + File.separator + fileName; 
         File storeFile = new File(filePath); 

         // saves the file on disk 
         item.write(storeFile); 
         request.setAttribute("message", 
          "Upload has been done successfully!"); 
        } 
       } 
       File folder = new File("D:/Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/HDSHubTargetAchieved/upload"); 
       File[] listOfFiles = folder.listFiles(); 


        for (int i = 0; i < listOfFiles.length; i++) { 
         if (listOfFiles[i].isFile()) { 
          String[] parts = listOfFiles[i].getName().split("[_.']"); 
          String part1 = parts[0]; 
          String part2 = parts[1]; 
          String part3 = parts[2]; 
          String part4 = parts[3]; 
          String part5 = parts[4]; 

          // JSON   
          JSONObject splitDetails = new JSONObject(); 

          splitDetails.put("MDCode", part1); 
          splitDetails.put("target/achieved", part2); 
          splitDetails.put("month", part3); 
          splitDetails.put("year", part4); 
          splitDetails.put("MDName", part5); 

          splitDetailsArray.put(splitDetails); 

          // TEST OUTPUT \\ 
          System.out.println("Code:" + part1 + "\n Target/Achieved: " + part2 + "\n Month: " + part3 + "\n Year: " + part4 + "\n Name: " + part5);             
         } 
        } 
        // TEST OUTPUT \\ 
        System.out.println(splitDetailsArray.toString()); 
      } 
     } catch (Exception ex) { 
      request.setAttribute("message", 
        "There was an error: " + ex.getMessage()); 
     } 
     // redirects client to message page 
     request.setAttribute("jsonString", splitDetailsArray.toString()); 
     RequestDispatcher dispatcher = request.getRequestDispatcher("/test.jsp"); 
     dispatcher.forward(request, response); 
//  getServletContext().getRequestDispatcher("/test.jsp").forward(
//    request, response); 
    } 
} 

上述代碼在tomcat 6

再次運行時,我正在尋找一種方式來傳遞這個JSON到表中的test.jsp文件。 在大多數情況下,我只是想要一個建議,但這次我需要一些代碼示例,因爲我真的不知道如何去做。這是我第一次接觸到servlet。我失去了2個小時尋求幫助,但我無法找到它。

回答

1

基本上你會通過使用JavaScript循環你的JSON數組並打印出html表標籤。下面是一個示例答案,可以幫助你。我剛剛在Google上搜索「從json打印html表格」。

Convert json data to a html table

+0

謝謝!這是一個很好的例子。不知道我是如何錯過它的,可能我太累了。 – Slim 2013-05-07 07:20:34