使用json数据填充网格/表

时间:2013-04-30 10:57:48

标签: java json jsp servlets tomcat6

我有一个用于文件上传的主表单。 servlet正在执行上载作业。所有文件都具有相同的名称结构,所以我将它拆分并获取参数。然后我将它们放入JSONArray,然后我将这些参数传递给索引页面,在我的案例中名为test.jsp

问题是,我不知道如何创建表并用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 个答案:

答案 0 :(得分:1)

基本上你会使用javascript循环你的JSON数组并打印出html表标签。以下是一个可以帮助您的示例答案。我只是在Google上搜索“从json打印html表”。

Convert json data to a html table