您的位置:首页 > Web前端 > JavaScript

【Head First Servlets and JSP】迷你MVC:JarDownload的完整实现

2017-05-31 23:14 716 查看
1、首先,写一个download.html放至D:\apache-tomcat-7.0.77\webapps\JarDownload-v1。

<!DOCTYPE HTML>
<html>
<body>
<form action="JarDownload.do" method="get">
<br />
提取码:<input type="text" name="passwd" /><br />
<br />
<input type="submit" />
</form>

<br />
<p>提取码为123456。</p>
</body>
</html>


2、启动tomcat,并通过浏览器测试页面。

先执行命令行指令D:\apache-tomcat-7.0.77\bin>startup.sh

然后打开浏览器,输入URL:http://localhost:8080/JarDownload-v1/download.html



3、编写web.xml并测试,放至D:\apache-tomcat-7.0.77\webapps\JarDownload-v1\WEB-INF,最好重启一下tomcat。

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>com.example.web.JarDownload</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/JarDownload.do</url-pattern>
</servlet-mapping>

</web-app>


4、准备一个测试Jar包,放在D:\apache-tomcat-7.0.77\webapps\JarDownload-v1

5、编写全名为com.example.web.JarDownload的Servlet,编译成.class文件后部署到D:\apache-tomcat-7.0.77\webapps\JarDownload-v1\WEB-INF\classes\com\example\web

package com.example.web;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class JarDownload extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("application/jar"); // 想让浏览器知道的事情

ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("/hello.jar");

int read = 0;
byte[] bytes = new byte[1024];

OutputStream os = resp.getOutputStream();
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
} // 把JAR包先读到内存里再转写到输出流中。
os.flush();
os.close();
}
}


6、最后,测试一下能否通过网页下载这个Jar包。



7、经过检查,发现JarDownload.do的的确是hello.jar(只是名称不同罢了),但是文件名却是url-pattern,修改一下html和web.xml就可以了。



这里体现了把逻辑名映射到servlet文件的好处。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: