前言
之前工作的時候, 經常聽人提及JSP
與Java Servlet
的概念. 本章就主要
本章涉及的例子都可以在https://github.com/SeanYanxml/arsenal/tree/master/arsenal-java/arsenal-servlet下找到.
如果你覺得我的項目不錯, 不妨給我一個Star. 你的支持就是我的動力.
前置準備
- JDK
- Maven
- Eclipse
- Tomcat
- Maven依賴
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yanxml</groupId>
<artifactId>arsenal-java-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.yanxml</groupId>
<artifactId>arsenal-jsp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>arsenal-jsp</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
</project>
基本操作
- upload.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>文件上傳實例</title>
</head>
<body>
<h1>文件上傳實例</h1>
<form method="post" action="/arsenal-jsp/UploadServlet" enctype="multipart/form-data">
選擇一個文件:
<input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="上傳" />
</form>
</body>
</html>
與之前一樣的是, 需要在<form action="">
處指定需要調用的api請求地址.
- message.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>文件上傳結果</title>
</head>
<body>
<center>
<h2>${message}</h2>
</center>
</body>
</html>
- UploadServlet.java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
/**
* Servlet implementation class UploadServlet
*/
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
// 上傳文件存儲目錄
private static final String UPLOAD_DIRECTORY = "upload";
// 上傳配置
private static final int MEMORY_THRESHOLD = 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
/**
* 上傳數據及保存文件
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 檢測是否爲多媒體上傳
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是則停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上傳參數
DiskFileItemFactory factory = new DiskFileItemFactory();
// 設置內存臨界值 - 超過後將產生臨時文件並存儲於臨時目錄中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 設置臨時存儲目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 設置最大文件上傳值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 設置最大請求值 (包含文件和表單數據)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文處理
upload.setHeaderEncoding("UTF-8");
// 構造臨時路徑來存儲上傳的文件
// 這個路徑相對當前應用的目錄
String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
// 如果目錄不存在則創建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 解析請求的內容提取文件數據
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表單數據
for (FileItem item : formItems) {
// 處理不在表單中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// 在控制檯輸出文件的上傳路徑
System.out.println(filePath);
// 保存文件到硬盤
item.write(storeFile);
request.setAttribute("message",
"文件上傳成功!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message",
"錯誤信息: " + ex.getMessage());
}
// 跳轉到 message.jsp
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
}
此處和之前提及的Servlet
教程一致, 都是繼承了HttpServlet
. 並且實現了doPost()
和doGet()
方法.
文件上傳地址: http://localhost:8080/arsenal-jsp/upload.jsp
文件上傳後回覆:
Q&A
- 發佈後的包內缺少類
org/apache/commons/fileupload/FileItemFactory
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/arsenal-jsp]]
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:162)
... 6 more
Caused by: java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2583)
at java.lang.Class.getDeclaredFields(Class.java:1916)
at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:256)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:132)
at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:65)
at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:336)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:786)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
... 6 more
Caused by: java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
... 20 more
A: 因爲配置不當導致. 在發佈時加上Maven
的依賴即可.
巧建Spring Web的Maven項目來解決java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory