使用Jetty作为开发容器(非部署容器)

1. 说明:依旧使用tomcat作为容器,Jetty在这里只作为开发时测试方便,所以采取工具类形式,而非下载Jetty容器包配置方式。

2. 为什么要用Jetty?

此处用Jetty只是方便测试,运行个main方法即可启动Jetty容器,然后就可以调用接口和访问jsp等页面。无需启动tomcat,个人认为Jetty启动速度远快于tomcat。所以方便测试,更改代码只需要重新运行main方法即可。(Jetty自带热部署)

3. 如何使用?

  • pom.xml定义如下
<!-- jetty plugin -->
      <dependency>
          <groupId>org.eclipse.jetty.aggregate</groupId>
          <artifactId>jetty-all-server</artifactId>
          <version>8.1.18.v20150929</version>
      </dependency>
      <dependency>
          <groupId>org.eclipse.jetty</groupId>
          <artifactId>jetty-jsp</artifactId>
          <version>8.1.18.v20150929</version>
      </dependency>
  • 工具类
package test.bshf.clinic.util;

import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.Scanner;
import org.eclipse.jetty.webapp.WebAppContext;

import javax.management.MBeanServer;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;


public class JettyServerStarter {
    private int           port;
    private String        context;
    private String        webappPath;
    private int           scanIntervalSeconds;
    private boolean       jmxEnabled;
    private Server        server;
    private WebAppContext webapp;

    public JettyServerStarter(String webappPath, int port, String context) {
        this(webappPath, port, context, 0, false);
    }

    public JettyServerStarter(String webappPath, int port, String context, int scanIntervalSeconds, boolean jmxEnabled) {
        this.webappPath = webappPath;
        this.port = port;
        this.context = context;
        this.scanIntervalSeconds = scanIntervalSeconds;
        this.jmxEnabled = jmxEnabled;
        validateConfig();
    }

    private void validateConfig() {
        if (port < 0 || port > 65536) {
            throw new IllegalArgumentException("Invalid port of web server: " + port);
        }
        if (context == null) {
            throw new IllegalStateException("Invalid context of web server: " + context);
        }
        if (webappPath == null) {
            throw new IllegalStateException("Invalid context of web server: " + webappPath);
        }
    }

    public void start() {
        if (server == null || server.isStopped()) {
            try {
                doStart();
            } catch (Throwable e) {
                e.printStackTrace();
                System.err.println("System.exit() ......");
                System.exit(1);
            }
        } else {
            throw new RuntimeException("Jetty Server already started.");
        }
    }

    private void doStart() throws Throwable {
        if (!portAvailable(port)) {
            throw new IllegalStateException("port: " + port + " already in use!");
        }

        System.setProperty("org.eclipse.jetty.util.URI.charset", "UTF-8");
        System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.Slf4jLog");
        System.setProperty("org.eclipse.jetty.server.Request.maxFormContentSize", "20000000");

        server = new Server(port);
        server.setHandler(getHandler());

        if (jmxEnabled) {
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
            MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
            server.addBean(mBeanContainer);
        }

        if (scanIntervalSeconds > 0) {
            startFileWatchScanner();
        }

        long ts = System.currentTimeMillis();
        server.start();

        ts = System.currentTimeMillis() - ts;
        System.err.println("Jetty Server started: " + String.format("%.2f sec", ts / 1000d));

        server.join();
    }
    
    
    protected Handler getHandler(){
        webapp = new WebAppContext(webappPath, context);
        return webapp;
    }

    private void startFileWatchScanner() throws Exception {
        List<File> scanList = new ArrayList<File>();
        scanList.add(new File(webappPath, "WEB-INF"));

        Scanner scanner = new Scanner();
        scanner.setReportExistingFilesOnStartup(false);
        scanner.setScanInterval(scanIntervalSeconds);
        scanner.setScanDirs(scanList);
        scanner.addListener(new Scanner.BulkListener() {

            @SuppressWarnings("rawtypes")
            public void filesChanged(List changes) {
                try {
                    System.err.println("Loading changes ......");
                    webapp.stop();
                    webapp.start();
                    System.err.println("Loading complete.\n");
                } catch (Exception e) {
                    System.err.println("Error reconfiguring/restarting webapp after change in watched files");
                    e.printStackTrace();
                }
            }
        });
        System.err.println("Starting scanner at interval of " + scanIntervalSeconds + " seconds.");
        scanner.start();
    }

    private static boolean portAvailable(int port) {
        if (port <= 0) {
            throw new IllegalArgumentException("Invalid start port: " + port);
        }

        ServerSocket ss = null;
        DatagramSocket ds = null;
        try {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            ds = new DatagramSocket(port);
            ds.setReuseAddress(true);
            return true;
        } catch (IOException e) {
        } finally {
            if (ds != null) {
                ds.close();
            }
            if (ss != null) try {
                ss.close();
            } catch (IOException e) {
            }
        }
        return false;
    }
}
  • 主方法
package test.bshf.clinic.demo;

import test.bshf.clinic.util.JettyServerStarter;

/**
 * 启动jetty容器
 * 
 */
public class JettyStarterTest {

    public static void main(String[] args) {
        String webapp = "src/main/webapp";

        new JettyServerStarter(webapp, 8012, "/clinic-demo").start();
    }
}
解释说明:
pom和工具类直接复制粘贴
主方法
  • String webapp = "src/main/webapp";: 是当前web项目的webapp这层目录结构(因为里面包含了class和页面等)
  • new JettyServerStarter(webapp, 8012, "/clinic-demo").start(); new 一个Jetty容器,第一个参数是webapp地址,第二个参数是端口号(自定义),第三个参数是当前web项目名称。
  • 访问路径:http://localhost:8012(自定义Jetty的端口)/clinic-demo

若有兴趣,欢迎来加入群,【Java初学者学习交流群】:458430385,此群有Java开发人员、UI设计人员和前端工程师。有问必答,共同探讨学习,一起进步!
欢迎关注我的微信公众号【Java码农社区】,会定时推送各种干货:


qrcode_for_gh_577b64e73701_258.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,803评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,651评论 18 139
  • 1.简介 之前的maven项目打包类型都为pom或者POM,今天讲一下用maven构建web应用,web应用的打包...
    zlcook阅读 3,379评论 0 12
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,239评论 11 349
  • 近段,公司想要招一个人来接替我的工作,以前一直是我一个人做这个工作,所以自然而然的需要转变到一个面试官的角色。但是...
    旺家分享会阅读 354评论 0 0