我有一个用于文件上传的主要表单。一个 servlet 正在执行上传工作。所有文件都具有相同的名称结构,因此我将其拆分并获取参数。然后我将它们放入 a 中,然后将这些参数传递给索引页面,在我的例子中JSONArray
命名。test.jsp
问题是,我不知道如何创建一个表并用 JSON 中的详细信息填充它。
这里我的 index(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 个小时寻求帮助,但我找不到它。