我开发了一个Java servlet(tomcat 6.0),用于处理从客户端上传到服务器的文件。到目前为止,我所有的javaapp现在都可以上传一个文件。我编写了另一个java应用程序,它扫描文件(excel文档,apachi POI),并从中解析特定信息,然后打印出信息。
目标基本上是使用上传的文件,然后调用java程序来处理文件。然后将数据从java控制台(结果)吐出到HTML页面。
这是我的servlet代码。我按照this教程进行了此操作。
的Servlet
package net.codejava.upload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
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;
/**
* A Java servlet that handles file upload from client.
* @author www.codejava.net
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "upload";
private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
/**
* handles file upload via HTTP POST method
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
PrintWriter writer = response.getWriter();
writer.println("Request does not contain upload data");
writer.flush();
return;
}
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
// constructs the directory path to store upload file
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
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 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!");
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
Web XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>UploadServletApp</display-name>
<servlet>
<description></description>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>net.codejava.upload.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
</web-app>
我的上传JSP页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>File Upload</title>
</head>
<body>
<center>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload: <input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="Upload" />
</form>
</center>
</body>
</html>
我的消息jsp页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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">
<title>Upload</title>
</head>
<body>
<center>
<h2>${requestScope.message}</h2>
</center>
</body>
</html>
有人可以告诉我现在要做什么,关于如何调用我制作的单独的java程序(这里没有发布代码)来处理文件,然后让它从java控制台吐出数据(结果)发送消息&#39; HTML jsp页面?我到处寻找,无法找到解决这个问题的方法。它让我发疯了。
答案 0 :(得分:0)
如果您编写了其他java代码,只需在项目中包含该类:实例化该类并将其传递给该文件。在您的servlet中,将文件写入磁盘
// saves the file on disk
item.write(storeFile);
您可以实例化您的类并将其传递给File对象或文件的路径。
答案 1 :(得分:0)
首先,您需要创建一个返回String的方法,并将String作为参数。
public String getContent(String filePath) {
// logic goes here
}
您已经为此创建了一个类,您需要创建此方法。 然后你需要改变servlet的一些部分:
在String fileName = "";
方法中声明变量doPost
并更改
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
到
if (!item.isFormField()) {
fileName = new File(item.getName()).getName(); // remove String
在while循环后调用您的课程(假设FilterData
是您的班级名称)
while (iter.hasNext()) {
// Code
}
FilterData fd = new FilterData();
String data = fd.getData(uploadPath + "//" + fileName);
request.setAttribute("message", data);
并删除
request.setAttribute("message", "Upload has been done successfully!");
希望这有帮助!!!