文件下载及上传

package com.boventech.learning.serviceImpl;

import java.io.IOException;

import org.mortbay.http.HttpContext;
import org.mortbay.http.handler.ResourceHandler;
import org.mortbay.jetty.Server;
import org.mortbay.util.InetAddrPort;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

@Service
public class HttpServiceServiceImpl implements ApplicationListener<ApplicationEvent> {

	private String rootPath;
	private String port;
	
	private boolean loaded = false;
	
	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (!(event instanceof ContextRefreshedEvent)) {  
            return;  
        }
		if(!loaded){
			startHttpServer();
		}
	}

    private void startHttpServer(){
    	loaded = true;
    	HttpServer http = new HttpServer();
    	Thread thread = new Thread(http);
    	thread.start();
    }

	public String getRootPath() {
		return rootPath;
	}

	public void setRootPath(String rootPath) {
		this.rootPath = rootPath;
	}
    
	class HttpServer implements Runnable {

	    public void run() {
			Server server = new Server();
			try {
				server.addListener(new InetAddrPort(port));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			// Create a context
			HttpContext context = server.getContext(null,"/");
			context.setResourceBase	(rootPath);
			ResourceHandler resource_handler = new ResourceHandler();
			resource_handler.setAcceptRanges(true);
			resource_handler.setDirAllowed(true);
			context.addHandler (resource_handler);
	        try {
				server.start();
				server.join();
			} catch (Exception e) {
				e.printStackTrace();
			}
	    }
	}

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public boolean isLoaded() {
		return loaded;
	}

	public void setLoaded(boolean loaded) {
		this.loaded = loaded;
	}

}


public interface HttpServerService{
	
}

spring给注入rootPath及port


mvn:

<dependency>
            <groupId>jetty</groupId>
            <artifactId>jetty</artifactId>
            <version>5.1.10</version>
        </dependency>


你可能感兴趣的:(下载,上传)