使用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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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