[服务器] 用Servlet搭建自己的HTTP服务|后台向前端传输文件|Java文件传输

背景:WebGIS Demo1选择要素并下载shp文件到本地

完整Demo:https://blog.csdn.net/summer_dew/article/details/80712591

功能:使用Servlet搭建自己的HTTP服务

  1. 在 Eclipse 中创建项目 File > New > Project > Web > Dynamic Web Project,并选择 Apache Tomcat作为网络服务器;
  2. 创建 Java Servlet,右键 project > New > Other > Web > Servelt,输入 Servlet的名称为 DonwloadFileServlet;
  3. 若有报错,需要手动加入Servlet包Build Path > Configure Build Path > 定位到tomcat/lib下 > servlet-api.jar
  4. 将下面的代码替换新建的 Servlet 中的代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 填写你的业务逻辑
        response.getOutputStream().println("get");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 填写你的业务逻辑

        // 这里以WebGIS Demo1的业务逻辑为例
        String zippath = request.getParameter("zippath");
        System.out.println(zippath);

        File file = new File(zippath.trim() );

        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=" + file.getName() );
        response.setContentLength((int) file.length());

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] buffer = new byte[128];
            int count = 0;
            while ((count = fis.read(buffer)) > 0) {
                response.getOutputStream().write(buffer, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            response.getOutputStream().flush();
            response.getOutputStream().close();
            fis.close();
        }
    }
  1. 右键 Servlet project > Run as > Run on Server,选择 “Manually define a newserver” 并指定 Apache Tomcat 的安装目录,然后打开 web 浏览器并输入
    http://localhost:8080/DonwloadFileServlet/DownloadFileServlet
    网页访问是get模式,所以可以看到以下页面:
    这里写图片描述

关于网址:http://localhost:8080/项目名/WebServlet后的字符串
此例子:http://localhost:8080/DonwloadFileServlet/DownloadFileServlet

@WebServlet("/DownloadFileServlet")
public class DownloadFileServlet extends HttpServlet {
    ...
}

猜你喜欢

转载自blog.csdn.net/summer_dew/article/details/80713921