• 文件上传的三种模式-Java


    转载自: http://www.myexception.cn/web/1935104.html
    文件上传的三种方式-Java
    前言:因自己负责的项目(jetty内嵌启动的SpringMvc)中需要实现文件上传,而自己对java文件上传这一块未接触过,且对 Http 协议较模糊,故这次采用渐进的方式来学习文件上传的原理与实践。该博客重在实践。
     
    一. Http协议原理简介  
        HTTP是一个属于应用层的面向对象的协议,由于其简捷、快速的方式,适用于分布式超媒体信息系统。它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展。目前在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的规范化工作正在进行之中,而且HTTP-NG(Next Generation of HTTP)的建议已经提出。
        简单来说,就是一个基于应用层的通信规范:双方要进行通信,大家都要遵守一个规范,这个规范就是HTTP协议。
     1.特点:
      (1)支持客户/服务器模式。
      (2)简单快速:客户向服务器请求服务时,只需传送请求方法和路径。请求方法常用的有GET、HEAD、POST。每种方法规定了客户与服务器联系的类型不同。由于HTTP协议简单,使得HTTP服务器的程序规模小,因而通信速度很快。
      (3)灵活:HTTP允许传输任意类型的数据对象。正在传输的类型由Content-Type加以标记。
      (4)无连接:无连接的含义是限制每次连接只处理一个请求。服务器处理完客户的请求,并收到客户的应答后,即断开连接。采用这种方式可以节省传输时间。
      (5)无状态:HTTP协议是无状态协议。无状态是指协议对于事务处理没有记忆能力。缺少状态意味着如果后续处理需要前面的信息,则它必须重传,这样可能导致每次连接传送的数据量增大。另一方面,在服务器不需要先前信息时它的应答就较快。
      注意:其中(4)(5)是面试中常用的面试题。虽然HTTP协议(应用层)是无连接,无状态的,但其所依赖的TCP协议(传输层)却是常连接、有状态的,而TCP协议(传输层)又依赖于IP协议(网络层)。
     2.HTTP消息的结构
     (1)Request 消息分为3部分,第一部分叫请求行, 第二部分叫http header消息头, 第三部分是body正文,header和body之间有个空行, 结构如下图
     (2)Response消息的结构, 和Request消息的结构基本一样。 同样也分为三部分,第一部分叫request line状态行, 第二部分叫request header消息体,第三部分是body正文, header和body之间也有个空行,  结构如下图
     
    下面是使用Fiddler捕捉请求baidu的Request消息机构和Response消息机构:
    因为没有输入任何表单信息,故request的消息正文为空,大家可以找一个登录的页面试试看。
    先到这里,HTTP协议的知识网上很丰富,在这里就不再熬述了。
     
    二. 文件上传的三种实现
    1. Jsp/servlet 实现文件上传
     这是最常见也是最简单的方式
     (1)实现文件上传的Jsp页面  
    复制代码
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <h2>File upload demo</h2>
        <form action="fileload"  method="post" enctype="multipart/form-data">
            <input type="file" name="filename" size="45"><br>
            <input type="submit" name="submit" value="submit">
        </form>
    </body>
    </html>
    复制代码

     (2)负责接文件的FileUploadServlet
     
    复制代码
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.log4j.Logger;

    // @WebServlet(name = "FileLoadServlet", urlPatterns = {"/fileload"})
    public class FileLoadServlet extends HttpServlet {

    </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> Logger logger = Logger.getLogger(FileLoadServlet.<span style="color: #0000ff;">class</span><span style="color: #000000;">);
    
    private static final long serialVersionUID = 1302377908285976972L;
    @Override
    </span><span style="color: #0000ff;">protected</span> <span style="color: #0000ff;">void</span> service(HttpServletRequest request, HttpServletResponse response) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> ServletException, IOException {
        logger.info(</span>"------------ FileLoadServlet ------------"<span style="color: #000000;">);
        
        </span><span style="color: #0000ff;">if</span> (request.getContentLength() &gt; 0<span style="color: #000000;">) {            
               InputStream inputStream </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;
               FileOutputStream outputStream </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;               
            </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {                
                inputStream </span>=<span style="color: #000000;"> request.getInputStream();
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 给新文件拼上时间毫秒,防止重名</span>
                <span style="color: #0000ff;">long</span> now =<span style="color: #000000;"> System.currentTimeMillis();
                File file </span>= <span style="color: #0000ff;">new</span> File("c:/", "file-" + now + ".txt"<span style="color: #000000;">);
                file.createNewFile();
                
                outputStream </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> FileOutputStream(file);
                
                </span><span style="color: #0000ff;">byte</span> temp[] = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[1024<span style="color: #000000;">];
                </span><span style="color: #0000ff;">int</span> size = -1<span style="color: #000000;">;
                </span><span style="color: #0000ff;">while</span> ((size = inputStream.read(temp)) != -1) { <span style="color: #008000;">//</span><span style="color: #008000;"> 每次读取1KB,直至读完</span>
                    outputStream.write(temp, 0<span style="color: #000000;">, size);
                }                
                logger.info(</span>"File load success."<span style="color: #000000;">);
            } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (IOException e) {
                logger.warn(</span>"File load fail."<span style="color: #000000;">, e);
                request.getRequestDispatcher(</span>"/fail.jsp"<span style="color: #000000;">).forward(request, response);
            } </span><span style="color: #0000ff;">finally</span><span style="color: #000000;"> {
                outputStream.close();
                inputStream.close();
            }
        }        
        request.getRequestDispatcher(</span>"/succ.jsp"<span style="color: #000000;">).forward(request, response);
    }    
    

    }

    复制代码
    
    
      FileUploadServlet的配置,推荐采用servlet3.0注解的方式更方便 
    复制代码
    <servlet>
        <servlet-name>FileLoadServlet</servlet-name>
        <servlet-class>com.juxinli.servlet.FileLoadServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileLoadServlet</servlet-name>
        <url-pattern>/fileload</url-pattern>
    </servlet-mapping>
    复制代码
     
    (3)运行效果
    点击"submit" 
    页面转向文件上传成功的页面,再去C盘看看,发现多了一个文件:file-1433417127748.txt,这个就是刚上传的文件
     
    我们打开看看,发现和原来的文本有些不一样
                 
    结合前面讲的HTTP协议的消息结构,不难发现这些文本就是去掉"请求头"后的"Request消息体"。所以,如果要得到与上传文件一致的文本,还需要一些字符串操作,这些就留给大家了。
    另外,大家可以试试一个Jsp页面上传多个文件,会有不一样的精彩哦o(∩_∩)o ,不解释。
     
    2. 模拟Post请求/servlet 实现文件上传 
    刚才我们是使用Jsp页面来上传文件,假如客户端不是webapp项目呢,显然刚才的那种方式有些捉襟见衬了。
    这里我们换种思路,既然页面上通过点击可以实现文件上传,为何不能通过HttpClient来模拟浏览器发送上传文件的请求呢。关于HttpClient ,大家可以自己去了解。
     (1)还是这个项目,启动servlet服务 
     (2)模拟请求的FileLoadClient 
    复制代码
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    

    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.multipart.FilePart;
    import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
    import org.apache.commons.httpclient.methods.multipart.Part;
    import org.apache.log4j.Logger;

    public class FileLoadClient {

    </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> Logger logger = Logger.getLogger(FileLoadClient.<span style="color: #0000ff;">class</span><span style="color: #000000;">);
    
    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> String fileload(String url, File file) {
        String body </span>= "{}"<span style="color: #000000;">;
        
        </span><span style="color: #0000ff;">if</span> (url == <span style="color: #0000ff;">null</span> || url.equals(""<span style="color: #000000;">)) {
            </span><span style="color: #0000ff;">return</span> "参数不合法"<span style="color: #000000;">;
        }
        </span><span style="color: #0000ff;">if</span> (!<span style="color: #000000;">file.exists()) {
            </span><span style="color: #0000ff;">return</span> "要上传的文件名不存在"<span style="color: #000000;">;
        }
        
        PostMethod postMethod </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> PostMethod(url);
        
        </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {            
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> FilePart:用来上传文件的类,file即要上传的文件</span>
            FilePart fp = <span style="color: #0000ff;">new</span> FilePart("file"<span style="color: #000000;">, file);
            Part[] parts </span>=<span style="color: #000000;"> { fp };
    
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装</span>
            MultipartRequestEntity mre = <span style="color: #0000ff;">new</span><span style="color: #000000;"> MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(mre);
            
            HttpClient client </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> HttpClient();
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间</span>
            client.getHttpConnectionManager().getParams() .setConnectionTimeout(50000<span style="color: #000000;">);
            
            </span><span style="color: #0000ff;">int</span> status =<span style="color: #000000;"> client.executeMethod(postMethod);
            </span><span style="color: #0000ff;">if</span> (status ==<span style="color: #000000;"> HttpStatus.SC_OK) {
                InputStream inputStream </span>=<span style="color: #000000;"> postMethod.getResponseBodyAsStream();
                BufferedReader br </span>= <span style="color: #0000ff;">new</span> BufferedReader(<span style="color: #0000ff;">new</span><span style="color: #000000;"> InputStreamReader(inputStream));
                
                StringBuffer stringBuffer </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> StringBuffer();
                String str </span>= ""<span style="color: #000000;">;
                </span><span style="color: #0000ff;">while</span> ((str = br.readLine()) != <span style="color: #0000ff;">null</span><span style="color: #000000;">) {
                    stringBuffer.append(str);
                }                
                body </span>=<span style="color: #000000;"> stringBuffer.toString();                
            } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {
                body </span>= "fail"<span style="color: #000000;">;
            }
        } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception e) {
            logger.warn(</span>"上传文件异常"<span style="color: #000000;">, e);
        } </span><span style="color: #0000ff;">finally</span><span style="color: #000000;"> {
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 释放连接</span>
    

    postMethod.releaseConnection();
    }
    return body;
    }

    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> main(String[] args) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> Exception {
        String body </span>= fileload("http://localhost:8080/jsp_upload-servlet/fileload", <span style="color: #0000ff;">new</span> File("C:/1111.txt"<span style="color: #000000;">));
        System.out.println(body);
    }    
    

    }

    复制代码
      
     (3)在Eclipse中运行FileLoadClient程序来发送请求,运行结果: 
    <html><head>  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head><body><h2>File upload success</h2><a href="index.jsp">return</a></body></html>
    打印了:文件上传成功的succ.jsp页面 


    有没有发现什么,是不是和前面Jsp页面上传的结果类似?对的,还是去掉"请求头"后的"Request消息体"。 
    这种方式也很简单,负责接收文件的FileUploadServlet没有变,只要在客户端把文件读取到流中,然后模拟请求servlet就行了。
     3.模拟Post请求/Controller(SpringMvc)实现文件上传 
    终于到第三种方式了,主要难点在于搭建maven+jetty+springmvc环境,接收文件的service和模拟请求的客户端 和上面相似。 
     (1)模拟请求的FileLoadClient未变 
    复制代码
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    

    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.methods.multipart.FilePart;
    import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
    import org.apache.commons.httpclient.methods.multipart.Part;
    import org.apache.log4j.Logger;

    public class FileLoadClient {
    private static Logger logger = Logger.getLogger(FileLoadClient.class);

    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span><span style="color: #000000;"> String fileload(String url, File file) {
        String body </span>= "{}"<span style="color: #000000;">;        
        </span><span style="color: #0000ff;">if</span> (url == <span style="color: #0000ff;">null</span> || url.equals(""<span style="color: #000000;">)) {
            </span><span style="color: #0000ff;">return</span> "参数不合法"<span style="color: #000000;">;
        }
        </span><span style="color: #0000ff;">if</span> (!<span style="color: #000000;">file.exists()) {
            </span><span style="color: #0000ff;">return</span> "要上传的文件名不存在"<span style="color: #000000;">;
        }
        
        PostMethod postMethod </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> PostMethod(url);        
        </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {            
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> FilePart:用来上传文件的类,file即要上传的文件</span>
            FilePart fp = <span style="color: #0000ff;">new</span> FilePart("file"<span style="color: #000000;">, file);
            Part[] parts </span>=<span style="color: #000000;"> { fp };
    
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装</span>
            MultipartRequestEntity mre = <span style="color: #0000ff;">new</span><span style="color: #000000;"> MultipartRequestEntity(parts, postMethod.getParams());
            postMethod.setRequestEntity(mre);
            
            HttpClient client </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> HttpClient();
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 由于要上传的文件可能比较大 , 因此在此设置最大的连接超时时间</span>
            client.getHttpConnectionManager().getParams() .setConnectionTimeout(50000<span style="color: #000000;">);
            
            </span><span style="color: #0000ff;">int</span> status =<span style="color: #000000;"> client.executeMethod(postMethod);
            </span><span style="color: #0000ff;">if</span> (status ==<span style="color: #000000;"> HttpStatus.SC_OK) {
                InputStream inputStream </span>=<span style="color: #000000;"> postMethod.getResponseBodyAsStream();
                BufferedReader br </span>= <span style="color: #0000ff;">new</span> BufferedReader(<span style="color: #0000ff;">new</span><span style="color: #000000;"> InputStreamReader(inputStream));
                
                StringBuffer stringBuffer </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> StringBuffer();
                String str </span>= ""<span style="color: #000000;">;
                </span><span style="color: #0000ff;">while</span> ((str = br.readLine()) != <span style="color: #0000ff;">null</span><span style="color: #000000;">) {
                    stringBuffer.append(str);
                }                
                body </span>=<span style="color: #000000;"> stringBuffer.toString();                
            } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> {
                body </span>= "fail"<span style="color: #000000;">;
            }
        } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception e) {
            logger.warn(</span>"上传文件异常"<span style="color: #000000;">, e);
        } </span><span style="color: #0000ff;">finally</span><span style="color: #000000;"> {
            </span><span style="color: #008000;">//</span><span style="color: #008000;"> 释放连接</span>
    

    postMethod.releaseConnection();
    }
    return body;
    }

    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> main(String[] args) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> Exception {
        String body </span>= fileload("http://localhost:8080/fileupload/upload", <span style="color: #0000ff;">new</span> File("C:/1111.txt"<span style="color: #000000;">));
        System.out.println(body);
    }<br>}</span></pre>
    
    复制代码

     (2)servlet换为springMvc中的Controller
    复制代码
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.log4j.Logger;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;

    @Controller
    @RequestMapping("/fileupload")
    public class FileUploadService {

    </span><span style="color: #0000ff;">private</span> Logger logger = Logger.getLogger(FileUploadService.<span style="color: #0000ff;">class</span><span style="color: #000000;">);
    
    @RequestMapping(consumes </span>= "multipart/form-data", value = "/hello", method =<span style="color: #000000;"> RequestMethod.GET)
    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> hello(HttpServletRequest request, HttpServletResponse response) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> IOException {        
        response.getWriter().write(</span>"Hello, jetty server start ok."<span style="color: #000000;">);
    }
    
    @RequestMapping(consumes </span>= "multipart/form-data", value = "/upload", method =<span style="color: #000000;"> RequestMethod.POST)
    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> uploadFile(HttpServletRequest request, HttpServletResponse response) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> IOException {
        String result </span>= ""<span style="color: #000000;">;
        
        </span><span style="color: #0000ff;">if</span> (request.getContentLength() &gt; 0<span style="color: #000000;">) {            
               InputStream inputStream </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;
               FileOutputStream outputStream </span>= <span style="color: #0000ff;">null</span><span style="color: #000000;">;               
            </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
                inputStream </span>=<span style="color: #000000;"> request.getInputStream();
                </span><span style="color: #008000;">//</span><span style="color: #008000;"> 给新文件拼上时间毫秒,防止重名</span>
                <span style="color: #0000ff;">long</span> now =<span style="color: #000000;"> System.currentTimeMillis();
                File file </span>= <span style="color: #0000ff;">new</span> File("c:/", "file-" + now + ".txt"<span style="color: #000000;">);
                file.createNewFile();
                
                outputStream </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> FileOutputStream(file);                
                </span><span style="color: #0000ff;">byte</span> temp[] = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span>[1024<span style="color: #000000;">];
                </span><span style="color: #0000ff;">int</span> size = -1<span style="color: #000000;">;
                </span><span style="color: #0000ff;">while</span> ((size = inputStream.read(temp)) != -1) { <span style="color: #008000;">//</span><span style="color: #008000;"> 每次读取1KB,直至读完</span>
                    outputStream.write(temp, 0<span style="color: #000000;">, size);
                }
                
                logger.info(</span>"File load success."<span style="color: #000000;">);
                result </span>= "File load success."<span style="color: #000000;">;
            } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (IOException e) {
                logger.warn(</span>"File load fail."<span style="color: #000000;">, e);
                result </span>= "File load fail."<span style="color: #000000;">;
            } </span><span style="color: #0000ff;">finally</span><span style="color: #000000;"> {
                outputStream.close();
                inputStream.close();
            }
        }        
        response.getWriter().write(result);
    }
    

    }

    复制代码
    
    
     (3)启动jetty的核心代码,在Eclipse里面右键可以启动,也可以把项目打成jar报启动 
    复制代码
    import org.apache.log4j.Logger;
    import org.eclipse.jetty.server.Connector;
    import org.eclipse.jetty.server.Server;
    import org.eclipse.jetty.server.ServerConnector;
    import org.eclipse.jetty.webapp.WebAppContext;
    

    public class Launcher {
    private static Logger logger = Logger.getLogger(Launcher.class);

    </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">final</span> <span style="color: #0000ff;">int</span> PORT = 8080<span style="color: #000000;">;
    </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">final</span> String WEBAPP = "src/main/webapp"<span style="color: #000000;">;
    </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">final</span> String CONTEXTPATH = "/"<span style="color: #000000;">;
    </span><span style="color: #0000ff;">private</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">final</span> String DESCRIPTOR = "src/main/webapp/WEB-INF/web.xml"<span style="color: #000000;">;
    
    </span><span style="color: #008000;">/*</span><span style="color: #008000;">
     * 创建 Jetty Server,指定其端口、web目录、根目录、web路径
     * @param port
     * @param webApp
     * @param contextPath
     * @param descriptor
     * @return Server
     </span><span style="color: #008000;">*/</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> Server createServer(<span style="color: #0000ff;">int</span><span style="color: #000000;"> port, String webApp, String contextPath, String descriptor) {
        Server server </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> Server();
        </span><span style="color: #008000;">//</span><span style="color: #008000;">设置在JVM退出时关闭Jetty的钩子
        </span><span style="color: #008000;">//</span><span style="color: #008000;">这样就可以在整个功能测试时启动一次Jetty,然后让它在JVM退出时自动关闭</span>
        server.setStopAtShutdown(<span style="color: #0000ff;">true</span><span style="color: #000000;">);
        
        ServerConnector connector </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> ServerConnector(server); 
        connector.setPort(port); 
        </span><span style="color: #008000;">//</span><span style="color: #008000;">解决Windows下重复启动Jetty不报告端口冲突的问题
        </span><span style="color: #008000;">//</span><span style="color: #008000;">在Windows下有个Windows + Sun的connector实现的问题,reuseAddress=true时重复启动同一个端口的Jetty不会报错
        </span><span style="color: #008000;">//</span><span style="color: #008000;">所以必须设为false,代价是若上次退出不干净(比如有TIME_WAIT),会导致新的Jetty不能启动,但权衡之下还是应该设为False</span>
        connector.setReuseAddress(<span style="color: #0000ff;">false</span><span style="color: #000000;">);
        server.setConnectors(</span><span style="color: #0000ff;">new</span><span style="color: #000000;"> Connector[]{connector});
        
        WebAppContext webContext </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> WebAppContext(webApp, contextPath);
        webContext.setDescriptor(descriptor);
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> 设置webapp的位置</span>
    

    webContext.setResourceBase(webApp);
    webContext.setClassLoader(Thread.currentThread().getContextClassLoader());

        server.setHandler(webContext);        
        </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> server;
    }
    
    </span><span style="color: #008000;">/**</span><span style="color: #008000;">
     * 启动jetty服务 
     </span><span style="color: #008000;">*/</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> startJetty() {
        </span><span style="color: #0000ff;">final</span> Server server =<span style="color: #000000;"> Launcher.createServer(PORT, WEBAPP, CONTEXTPATH, DESCRIPTOR);
        
        </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
            server.start();
            server.join();            
        } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception e) {
            logger.warn(</span>"启动 jetty server 失败"<span style="color: #000000;">, e);
            System.exit(</span>-1<span style="color: #000000;">);
        }
    }
    
    </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> main(String[] args) {        
        (</span><span style="color: #0000ff;">new</span><span style="color: #000000;"> Launcher()).startJetty();
        </span><span style="color: #008000;">//</span><span style="color: #008000;"> jetty 启动后的测试url
        </span><span style="color: #008000;">//</span> <span style="color: #008000; text-decoration: underline;">http://localhost</span><span style="color: #008000;">:8080/fileupload/hello</span>
    

    }
    }

    复制代码
    springMvc的配置不贴了,大家可以下载源码下来看。

     (4)运行效果
    运行 Launcher 后可以访问http://localhost:8080/fileupload/hello 查看jetty+springMvc启动是否正常
     
    运行 FileLoadClient后打印的日志: 
    说明文件上传成功 
     
    附源码下载:
    jsp_upload-servlet项目: (1).Jsp/servlet 实现文件上传  (2).模拟Post请求/servlet 实现文件上传
    jetty_upload-springmvc项目: (3).模拟Post请求/Controller(SpringMvc)实现文件上传
    csdn下载地址: 文件上传的三种方式-Java 
    GitHub下载地址: 
    https://github.com/leonzm/jsp_upload-servlet.git
    https://github.com/leonzm/jetty_upload-springmvc.git
     时间比较仓促,可能有不对或者不完善的地方,大家可以提出来一起学习。
     
    参考&引用:
    浅析HTTP协议: http://www.cnblogs.com/gpcuster/archive/2009/05/25/1488749.html 
    HTTP协议详解: http://blog.csdn.net/gueter/article/details/1524447
    HTTP 协议详解: http://kb.cnblogs.com/page/130970/
    HttpClient学习整理: http://www.cnblogs.com/ITtangtang/p/3968093.html 
    TCP/IP、Http、Socket的区别: http://jingyan.baidu.com/article/08b6a591e07ecc14a80922f1.html 
    Spring MVC 教程,快速入门,深入分析: http://yinny.iteye.com/blog/1926799
    jetty启动以及嵌入式启动:http://yinny.iteye.com/blog/1926799
    启动jetty方式: http://hbiao68.iteye.com/blog/2111007
    Jetty较实用引导程序: http://www.xuebuyuan.com/1400368.html
  • 相关阅读:
    【转】Oracle 查询每天执行慢的SQL
    【转】StringBuilder与String的区别
    【转】C#单例模式实现
    【转】设计模式
    【转】十大排序算法
    ASP.NET jQuery 随笔 从DropDownList获取选择的text和value值
    ASP.NET jQuery 随笔 显示CheckBoxList成员选中的内容
    ASP.NET jQuery 随笔 在TextBox里面阻止复制、剪切和粘贴事件
    ASP.NET JQuery 随笔-搜索框默认提示
    JS 某一区域内所有CheckBox全选和取消全选(.net)
  • 原文地址:https://www.cnblogs.com/jpfss/p/9466616.html
Copyright © 2020-2023  润新知