jsp和sevlet上传文件并在界面回显示代码
时间: 2024-12-24 11:20:29 浏览: 16
JSP(Java Server Pages)和Servlet是Java Web开发中常用的组件,用于动态生成网页内容。在JSP页面上处理文件上传,并在界面上显示上传信息,你需要遵循以下步骤:
1. **创建HTML表单**:
```html
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload" />
<input type="submit" value="Upload" />
</form>
```
这里`enctype="multipart/form-data"`是必需的,因为它允许发送二进制数据如文件。
2. **创建Servlet(例如,UploadServlet.java)**:
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = "";
try {
// 获取请求头中的文件名
fileName = request.getHeader("fileName");
File file = new File(getServletContext().getRealPath("/") + "uploads/" + fileName);
// 读取并保存文件到服务器指定目录
InputStream inputStream = request.getInputStream();
FileOutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
// 显示成功消息给用户
request.setAttribute("message", "File uploaded successfully!");
request.getRequestDispatcher("result.jsp").forward(request, response);
} catch (Exception e) {
request.setAttribute("message", "Error occurred during file upload.");
request.getRequestDispatcher("error.jsp").forward(request, response);
}
}
}
```
3. **结果页面(例如,result.jsp或error.jsp)**:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>File Upload Result</title>
</head>
<body>
<% if (request.getAttribute("message") != null) { %>
<h2><%= request.getAttribute("message") %></h2>
<% } else { %>
No message found.
<% } %>
</body>
</html>
```
阅读全文