Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用json数据填充网格/表格_Java_Json_Jsp_Servlets_Tomcat6 - Fatal编程技术网

Java 用json数据填充网格/表格

Java 用json数据填充网格/表格,java,json,jsp,servlets,tomcat6,Java,Json,Jsp,Servlets,Tomcat6,我有一个文件上传的主表单。servlet正在执行上载作业。所有文件都具有相同的名称结构,所以我将其拆分并获取参数。然后我将它们放入一个JSONArray,然后我将这些参数传递到索引页面,在我的例子中名为test.jsp 问题是,我不知道如何创建一个表并用JSON中保存的细节填充它 这里我的索引(test.jsp)页面是: 下面是我的servlet: import java.io.File; import java.io.IOException; import java.io.PrintWrite

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

问题是,我不知道如何创建一个表并用JSON中保存的细节填充它

这里我的索引(test.jsp)页面是:

下面是我的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);
    }
}
导入java.io.File;
导入java.io.IOException;
导入java.io.PrintWriter;
导入java.util.List;
导入javax.servlet.RequestDispatcher;
导入javax.servlet.ServletException;
导入javax.servlet.http.HttpServlet;
导入javax.servlet.http.HttpServletRequest;
导入javax.servlet.http.HttpServletResponse;
导入org.apache.commons.fileupload.FileItem;
导入org.apache.commons.fileupload.disk.DiskFileItemFactory;
导入org.apache.commons.fileupload.servlet.ServletFileUpload;
导入org.json.JSONArray;
导入org.json.JSONObject;
/**
*处理从客户端上传文件的Java servlet。
*
*@author www.codejava.net
*/
公共类FileUploadServlet扩展了HttpServlet{
私有静态最终长serialVersionUID=1L;
//存储上载文件的位置
私有静态最终字符串上载\u DIRECTORY=“UPLOAD”;
//上载设置
私有静态最终整数内存_阈值=1024*1024*3;
私有静态最终int MAX_FILE_SIZE=1024*1024*40;
私有静态最终整数最大请求大小=1024*1024*50;
/**
*收到文件上传提交后,解析读取请求
*上传数据并将文件保存在磁盘上。
*/
受保护的void doPost(HttpServletRequest请求,
HttpServletResponse响应)引发ServletException,IOException{
//检查请求是否确实包含上载文件
如果(!ServletFileUpload.isMultipartContent(请求)){
//如果不是,我们就到此为止
PrintWriter=response.getWriter();
println(“错误:表单必须有enctype=multipart/formdata.”);
writer.flush();
返回;
}
//JSON声明
JSONArray splitDetailsArray=新的JSONArray();
//配置上载设置
DiskFileItemFactory=新的DiskFileItemFactory();
//设置内存阈值-超过该阈值,文件将存储在磁盘中
设置SizeThreshold(内存_阈值);
//设置存储文件的临时位置
setRepository(新文件(System.getProperty(“java.io.tmpdir”));
ServletFileUpload upload=新的ServletFileUpload(工厂);
//设置上载文件的最大大小
upload.setFileSizeMax(最大文件大小);
//设置请求的最大大小(包括文件+表单数据)
upload.setSizeMax(最大请求大小);
//构造用于存储上载文件的目录路径
//此路径相对于应用程序的目录
字符串uploadPath=getServletContext().getRealPath(“”)
+File.separator+上传目录;
//如果目录不存在,则创建该目录
文件上传目录=新文件(上传路径);
如果(!uploadDir.exists()){
uploadDir.mkdir();
}
试一试{
//解析请求的内容以提取文件数据
@抑制警告(“未选中”)
List formItems=upload.parseRequest(请求);
if(formItems!=null&&formItems.size()>0){
//迭代窗体的字段
用于(文件项:表单项){
//仅处理非表单字段的字段
如果(!item.isFormField()){
字符串文件名=新文件(item.getName()).getName();
字符串filePath=uploadPath+File.separator+fileName;
文件存储文件=新文件(文件路径);
//将文件保存在磁盘上
item.write(存储文件);
request.setAttribute(“消息”,
“上传成功!”;
}
}
File folder=new文件(“D:/Workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/hdshubtargethived/upload”);
File[]listOfFiles=folder.listFiles();
for(int i=0;i[
    {
        "MDName": "Angel Bankov",
        "MDCode": "2288",
        "month": "April",
        "year": "2013",
        "target/achieved": "Target"
    },
    {
        "MDName": "Angel Bankovsky",
        "MDCode": "2289",
        "month": "April",
        "year": "2015",
        "target/achieved": "Achieved"
    }
]
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);
    }
}