文档章节

Jetty 基本使用样例

k
 kunping
发布于 2018/01/20 20:37
字数 554
阅读 101
收藏 1

 

package com.jetty.example;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServlet;

import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.util.thread.ScheduledExecutorScheduler;

/**
 * <pre>
 * 	样例:
 * 		JettyServer server = new JettyServer("demo");
 * 		server.addHttpServlet("", "/h1", new HelloServlet("h1"));
 * 		server.addHttpServlet("", "/h2", new HelloServlet("h2"));
 * 		server.addFilter("com.jetty.example.MyFilter", null);
 * 		server.start("127.0.0.1", 8080);
 * 		server.awaitUninterruptibly();
 * 
 * </pre>
 * 
 * Created by 黄坤平 on 2018/1/20.
 */
public class JettyServer {

    private String serverName;
    private Server server;
    private QueuedThreadPool pool;
    private ScheduledExecutorScheduler serverExecutor;
    private volatile boolean running = false;
    private List<ServletContextHandler> handlers = new ArrayList<ServletContextHandler>();
    private List<FilterHolder> filters = new ArrayList<FilterHolder>();
    
	public JettyServer(String serverName) throws Exception {
		this.serverName = serverName;
		pool = new QueuedThreadPool();
		if (serverName == null) {
			serverName = "";
		}
		if (!serverName.isEmpty()) {
			pool.setName(serverName);
		}
		pool.setDaemon(true);

		server = new Server(pool);

		ErrorHandler errorHandler = new ErrorHandler();
		errorHandler.setShowStacks(true);
		errorHandler.setServer(server);
		server.addBean(errorHandler);
		
		serverExecutor = new ScheduledExecutorScheduler(serverName + "-JettyScheduler", true);
	}
	
	public void start(String hostName, int port) throws Exception {
		start(hostName, port, null);
	}
	
	public void start(String hostName, int port, String[] virtualHosts) throws Exception {
		
		for (FilterHolder filter : filters) {
			EnumSet<DispatcherType> enumDispatcher = EnumSet.of(DispatcherType.ASYNC, DispatcherType.ERROR,
                    DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.REQUEST);
            for (ServletContextHandler handler: handlers) {
                handler.addFilter(filter, "/*", enumDispatcher);
            }
		}
		
		ContextHandlerCollection collection = new ContextHandlerCollection();
		server.setHandler(collection);
		
        try {
            server.start();

            int minThreads = 1;

            ServerConnector connector = newConnector(server, serverExecutor, new ConnectionFactory[]{ new HttpConnectionFactory()},
                        hostName, port);
            connector.setName(serverName);

            minThreads += connector.getAcceptors() * 2;
            server.addConnector(connector);

            for (ServletContextHandler handler : handlers) {
            	if (virtualHosts != null) {
            		handler.setVirtualHosts(virtualHosts);
				}
                GzipHandler gzipHandler = new GzipHandler();
                gzipHandler.setHandler(handler);
                collection.addHandler(gzipHandler);
                gzipHandler.start();
            }
            pool.setMaxThreads(Math.max(pool.getMaxThreads(), minThreads));
            
            running = true;
        } catch (Exception e) {
            server.stop();
            if (serverExecutor.isStarted()) {
                serverExecutor.stop();
            }
            if (pool.isStarted()) {
                pool.stop();
            }
            throw e;
        }
	}
	
	public void awaitUninterruptibly() throws InterruptedException {
		server.join();
	}
	
	public void stop() throws Exception {
		if(!running) {
			return;
		}
		server.stop();
		
        if (serverExecutor.isStarted()) {
            serverExecutor.stop();
        }
        
        if (pool.isStarted()) {
            pool.stop();
        }
	}
	
    public void addHttpServlet(String basePath, String path, HttpServlet servlet) {
    	ServletContextHandler handler = createServletHandler(basePath, path, servlet);
    	handlers.add(handler);
    }

    private ServletContextHandler createServletHandler(String basePath, String path, HttpServlet servlet) {
        String prefixedPath = "";
        if("".equals(basePath) && "/".equals(path)) {
            prefixedPath = path;
        } else {
            prefixedPath = basePath + path;
        }

        ServletContextHandler contextHandler = new ServletContextHandler();
        ServletHolder holder = new ServletHolder(servlet);
        contextHandler.setContextPath(prefixedPath);
        contextHandler.addServlet(holder, "/");
        return contextHandler;
    }

    public void addFilter(String filterClassName, Map<String, Object> params) {
    	FilterHolder holder = new FilterHolder();
    	holder.setClassName(filterClassName);
    	if (params != null && !params.isEmpty()) {
    		for (Entry<String, Object> entry : params.entrySet()) {
        		holder.setInitParameter(entry.getKey(), entry.getValue().toString());
    		}
		}
    	filters.add(holder);
	}
    
	private ServerConnector newConnector(Server server,
			ScheduledExecutorScheduler serverExecutor,
			ConnectionFactory[] connectionFactories, String hostName, int port)
			throws Exception {
        ServerConnector connector = new ServerConnector(
                server,
                null,
                serverExecutor,
                null,
                -1,
                -1,
                connectionFactories);
        connector.setPort(port);
        connector.start();
        connector.setAcceptQueueSize(Math.min(connector.getAcceptors(), 8));
        connector.setHost(hostName);
        return connector;
    }

}

 

pom.xml

<jetty.version>9.3.20.v20170531</jetty.version>

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-http</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-continuation</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlets</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-proxy</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-client</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-util</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-security</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-plus</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>${jetty.version}</version>
            <scope>provided</scope>
        </dependency>

 

© 著作权归作者所有

k
粉丝 3
博文 61
码字总数 29867
作品 0
深圳
私信 提问
oschina maven 问题

在 idea 中使用 maven,每次运行 jetty ,都好有下面的提示,卡上三两分钟。 Downloading: http://maven.oschina.net/content/groups/public/org/glassfish/javax.el/maven-metadata.xml 我的......

javadever
2013/12/23
658
5
ActiveMQ的安装与使用(单节点)

IP:192.168.4.101 环境:CentOS 6.6、JDK7 1、 安装JDK并配置环境变量(略) JAVAHOME=/usr/local/java/jdk1.7.072 2、 下载Linux版的ActiveMQ(当前最新版apache-activemq-5.11.1-bin.tar.......

芝麻绿豆
2016/11/08
230
0
11,使用maven构建web应用

一.Web项目的目录结构 Web 项目的 POM 中需要显示地指定打包方式为 war ,其默认的 web 资源目录为 src/main/webapp/ ,在该目录下必须包含 WEB-INF/web.xml 。 二.Account-service 同一项...

小米米儿小
2013/08/07
851
2
用groovy写H2数据库的存储过程

以前看H2的roadmap,里边有这样一条“Groovy Stored Procedures: http://groovy.codehaus.org/GSQL”,就一直期盼着哪一天能够用上groovy写存储过程。如果能够这样,用groovy.sql.Sql写数据库...

wonder365
2013/02/21
2.6K
5
Jetty9.2.2集群Session共享

针对Jetty就不过多的介绍了,自行研究去吧! 1.准备环境 MySQL数据库;下载地址:自行百度。 jetty-distribution-9.2.2:下载地址:http://download.eclipse.org/jetty/ 2.配置方式 在JETTY...

Ryan-瑞恩
2015/02/26
5.9K
0

没有更多内容

加载失败,请刷新页面

加载更多

前端技术之:Prisma Demo服务部署过程记录

安装前提条件: 1、已经安装了docker运行环境 2、以下命令执行记录发生在MackBook环境 3、已经安装了PostgreSQL(我使用的是11版本) 4、Node开发运行环境可以正常工作 首先需要通过Node包管...

popgis
今天
5
0
数组和链表

数组 链表 技巧一:掌握链表,想轻松写出正确的链表代码,需要理解指针获引用的含义: 对指针的理解,记住下面的这句话就可以了: 将某个变量赋值给指针,实际上就是将这个变量的地址赋值给指...

code-ortaerc
今天
4
0
栈-链式(c/c++实现)

上次说“栈是在线性表演变而来的,线性表很自由,想往哪里插数据就往哪里插数据,想删哪数据就删哪数据...。但给线性表一些限制呢,就没那么自由了,把线性表的三边封起来就变成了栈,栈只能...

白客C
今天
43
0
Mybatis Plus service

/** * @author beth * @data 2019-10-20 23:34 */@RunWith(SpringRunner.class)@SpringBootTestpublic class ServiceTest { @Autowired private IUserInfoService iUserInfoS......

一个yuanbeth
今天
5
0
php7-internal 7 zval的操作

## 7.7 zval的操作 扩展中经常会用到各种类型的zval,PHP提供了很多宏用于不同类型zval的操作,尽管我们也可以自己操作zval,但这并不是一个好习惯,因为zval有很多其它用途的标识,如果自己...

冻结not
昨天
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部