用javaweb写一个下载网页
时间: 2023-10-02 16:11:31 浏览: 95
以下是一个简单的JavaWeb下载网页的示例代码:
1. 首先创建一个名为DownloadServlet的Servlet,用于处理用户的请求。
```
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = request.getParameter("url");
String filename = request.getParameter("filename");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(filename);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
2. 在web.xml文件中添加Servlet的映射。
```
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
```
3. 创建一个下载页面,该页面接收用户输入的URL和文件名,并将其作为参数传递给DownloadServlet。
```
<html>
<head>
<title>Download Page</title>
</head>
<body>
<form action="download" method="get">
<label for="url">URL:</label>
<input type="text" name="url" id="url"><br>
<label for="filename">Filename:</label>
<input type="text" name="filename" id="filename"><br>
<input type="submit" value="Download">
</form>
</body>
</html>
```
当用户输入URL和文件名并提交表单时,DownloadServlet将下载网页,并将其保存为指定的文件名。该文件将自动下载到用户计算机中。
阅读全文