[服务器] 用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 {
    ...
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

geodoer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值