zoukankan      html  css  js  c++  java
  • Jetty + Servlet 实现文件下载

    Jetty非常适合做嵌入式web开发,正如Jetty的口号"Don’t deploy your application in Jetty, deploy Jetty in your application!"。

    这个简单的例子是使用Jetty提供文件下载:

    首先pom.xml配置文件如下

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.luangeng</groupId>
      <artifactId>jettydownload</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>jettydownload</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jetty.version>8.1.9.v20130131</jetty.version>
      </properties>
    
      <dependencies>
        <!-- jetty -->
        <dependency>
          <groupId>org.eclipse.jetty.aggregate</groupId>
          <artifactId>jetty-webapp</artifactId>
          <version>${jetty.version}</version>
        </dependency>
        <dependency>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-jsp</artifactId>
          <version>${jetty.version}</version>
        </dependency>
    
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </project>
    View Code

    ---

    main方法启动Jetty:

    package com.luangeng;
    
    import org.eclipse.jetty.server.Connector;
    import org.eclipse.jetty.server.Handler;
    import org.eclipse.jetty.server.Server;
    import org.eclipse.jetty.server.handler.DefaultHandler;
    import org.eclipse.jetty.server.handler.HandlerCollection;
    import org.eclipse.jetty.server.nio.SelectChannelConnector;
    import org.eclipse.jetty.servlet.ServletContextHandler;
    import org.eclipse.jetty.webapp.WebAppContext;
    
    public class App 
    {
        public static void main( String[] args ) throws Exception {
    
            Server server = new Server();
            server.setStopAtShutdown(true);
            SelectChannelConnector connector = new SelectChannelConnector();
            connector.setPort(8080);
            connector.setReuseAddress(true);
            server.setConnectors(new Connector[] { connector });
            ServletContextHandler context = new ServletContextHandler();
            context.setContextPath("/lg");
            context.addServlet(DownLoadServlet.class, "/download");
            context.addServlet(TestServlet.class, "/test/*");
            HandlerCollection handlers = new HandlerCollection();
            handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
            server.setHandler(handlers);
    
            server.start();
            server.join();
    
        }
    }

    ---

    提供简单的测试 TestServlet.java

    package com.luangeng;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * Created by LG.
     */
    public class TestServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
    
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.println("<HTML>");
                out.println("<HEAD><TITLE>test</TITLE></HEAD>");
                out.println("<BODY>");
                out.println("GET method");
                out.println("</BODY>");
                out.println("</HTML>");
                out.flush();
                out.close();
    
        }
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<HTML>");
            out.println("<HEAD><TITLE>test</TITLE></HEAD>");
            out.println("<BODY>");
            out.println("POST method");
            out.println("</BODY>");
            out.println("</HTML>");
            out.flush();
            out.close();
        }
    
    
    
    }

    ---

    完成下载功能的Servlet:

    DownloadServlet.java

    package com.luangeng;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URLEncoder;
    
    /**
     * Created by LG.
     */
    public class DownLoadServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) {
    
            //PrintWriter pw = null;
            FileInputStream in = null;
            OutputStream outs = null;
    
            //String path = request.getParameter("filepath");
            String path = "/Users/LG/test.txt";
            //path = new String(fileName.getBytes("iso8859-1"),"UTF-8");
    
            try {
                File file = new File(path);
                if(!file.exists())
                {
                    response.setStatus(404);
                    //pw.println("file not found!");
                    //request.getRequestDispatcher("/err.jsp").forward(request, response);
                    return;
                }
                response.setContentType("text/html");
                String realname = path.substring(path.indexOf("/")+1);
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
                in = new FileInputStream(path);
                outs = response.getOutputStream();
                byte buffer[] = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    outs.write(buffer, 0, len);
                }
    
                System.out.println(response.getStatus());
            }
            catch(Exception e)
            {
                //pw.println(e.getMessage());
                response.setStatus(300);
                //log
            }
            finally {
                response.setStatus(200);
                try {
                    if(outs != null) {
                        outs.flush();
                        outs.close();
                    }
                    if(in != null) {
                        in.close();
                    }
    
                } catch (IOException e) {
                }
    //            if(pw!=null) {
    //                pw.flush();
    //                pw.close();
    //            }
            }
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doGet(request, response);
        }
    
    }

    ---

    浏览器访问网址 http://localhost:8080/lg/download 即可看到下载

     

    end

  • 相关阅读:
    脚本——猜拳
    脚本——基础命令
    脚本——1-100奇数的和
    脚本——判断文件类型
    脚本——判断分数是否合格
    脚本——判断服务是否开启
    脚本——ping一个网址三次
    脚本——判断是否root用户
    脚本——查看目录是否存在
    第十八天:CSV、JSON、Excel、SQLite
  • 原文地址:https://www.cnblogs.com/luangeng/p/6079604.html
Copyright © 2011-2022 走看看