Jetty嵌入式集成方式可以很方便的集成到java应用中,对于小型应用来说不需要额外安装web服务器,部署起来方便很多。从jetty8以后开始支持https的访问。


下面用代码说明jetty9嵌入式集成方式如何支持https访问。

try {
    Server server = new Server();
    int port = 8080;
    
    System.out.println("Web Server Listener Port:" + port);
    
    //配置HTTP及对应的HTTPS
    HttpConfiguration httpConfig = new HttpConfiguration();
    httpConfig.setSecureScheme("https");
    httpConfig.setSecurePort(httpsPort);
    httpConfig.setSendServerVersion(true);
    httpConfig.setSendDateHeader(false);

    //设置HTTP连接
    ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
    http.setPort(port);
    http.setIdleTimeout(30000);
    server.addConnector(http);
    
    //配置SSL证书相关
    URL url = Thread.currentThread().getContextClassLoader().getResource("keystore.jks");
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(url.getFile());
    sslContextFactory.setKeyStorePassword("123456");
    sslContextFactory.setKeyManagerPassword("123456");

    // SSL HTTP配置
    HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.setSecurePort(port);
    httpsConfig.setSecureScheme("https");
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    //SSL配置
    ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory,
        HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(httpsPort);
    server.addConnector(sslConnector);

    //加载test应用
    url = Thread.currentThread().getContextClassLoader().getResource("/test");
    WebAppContext context = new WebAppContext("test", "/test");
    context.setLogUrlOnStart(true);
    context.setBaseResource(Resource.newResource(url.getAbsolutePath()));
    context.setClassLoader(Thread.currentThread().getContextClassLoader());
    context.setParentLoaderPriority(true);
    
    //启动应用
    server.setHandler(context);
    
    //启动web服务
    server.start();
    server.join();
    System.out.println("Web Server Startup Successfully!!!");
} catch (Throwable e) {
    e.printStackTrace(System.err);
    System.exit(1);
}