使用Gradle在嵌入式Web容器Jetty中運行Web應用

使用Gradle第一次構建Web應用的代碼基礎上我們進行修改

Jetty 插件

在 Maven 等構建的項目中,我們要使用 Jetty 做嵌入式 Web 容器運行 Web 應用,通常需要添加 Jetty 相關依賴以及進行類似下面代碼配置:

    package com.coderknock.jettystudy; 

    import org.eclipse.jetty.server.Server;  
    import org.eclipse.jetty.webapp.WebAppContext;  

    public class WebAppContextWithFolderServer {  
        public static void main(String[] args) throws Exception {  
            Server server = new Server(8080);  

            WebAppContext context = new WebAppContext();  
            context.setContextPath("/myapp");  
            context.setDescriptor("E:/share/test/struts2-blank/WEB-INF/web.xml");  
            context.setResourceBase("E:/share/test/struts2-blank");  
            context.setParentLoaderPriority(true);  
            server.setHandler(context);  

            server.start();  
            server.join();  
        }  
    }  

在 Gradle 構建的項目中,我們可以使用 Jetty 插件從而省略相關依賴的引入以及上面代碼的編寫 build.gradle:

apply plugin:'jetty'

通過 Gradle 的 API 一個插件可以訪問另一個插件的配置,所以就可以減少相當部分的代碼。
在添加了 Jetty 插件後我們運行項目【爲了避免不必要的麻煩,我們將項目的目錄改爲了 project 避免使用中文】:

www.coderknock.com$ gradle jettyRun
 Starting a Gradle Daemon (subsequent builds will be faster)
 The Jetty plugin has been deprecated and is scheduled to be removed in Gradle 4.0. Consider using the Gretty (https://github.com/akhikhl/gretty) plugin instead.
         at build_6ecrowvh1t5jyzhh29knepzxf.run(D:\Windows\Desktop\LearnGradle\使用Gradle在嵌入式Web容器Jetty中運行Web應 用\project\build.gradle:2)
 :compileJava
 :processResources NO-SOURCE
 :classes
 > Building 75% > :jettyRun > Running at http://localhost:8080/project

此時我們通過 http://localhost:8080/project 就可以訪問我們的項目了,通過 Ctrl + c 可以停止項目。
我們可以通過一些配置來修改 Jetty 的配置例如下面配置可以修改啓動的項目名以及端口:

jettyRun {
    httpPort = 9091
    contextPath = 'coderknockJetty'
}

Gretty 插件

通過上面的編譯輸出我們可以看到 Jetty 插件在 Gradle 4.0 中將會被刪除,推薦使用 Gretty 插件,我們再次修改項目 build.gradle 將 apply plugin:'jetty' 更改爲 apply from: 'https://raw.github.com/akhikhl/gretty/master/pluginScripts/gretty.plugin'並刪除或註釋掉jettyRun相關配置,然後運行項目【需要聯網下載相關依賴】:

 www.coderknock.com$ gradle appRun
 :prepareInplaceWebAppFolder UP-TO-DATE
 :createInplaceWebAppFolder UP-TO-DATE
 :compileJava UP-TO-DATE
 :processResources NO-SOURCE
 :classes UP-TO-DATE
 :prepareInplaceWebAppClasses UP-TO-DATE
 :prepareInplaceWebApp UP-TO-DATE
 :appRun
 15:52:07 INFO  Jetty 9.2.15.v20160210 started and listening on port 8080
 15:52:07 INFO  ToDo Application runs at:
 15:52:07 INFO    http://localhost:8080/project
 Press any key to stop the server.
 > Building 87% > :appRun 

Gretty 自定義配置與 Jetty 大致相同:

//gretty 配置 更詳細的文檔可以查看 http://akhikhl.github.io/gretty-doc/
    gretty {
        httpPort = 9090
        contextPath = 'coderknock'
    }

相關代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章