使用Gradle进行DynamicWebProject的构建

最近项目中使用了Gradle来进行构建,项目选型用的是springboot,打包后是jar方式运行。但是在以前,公司使用的webproject,在不改变tomcat运行环境的情况下,如何做到gradle进行编译和测试呢?下面将用一个实例讲解如何eclipse的web project和gradle进行集成。

新建Dynamic Web Project,命名为GradleWeb。记得勾选生成web.xml复选框。
GIT:http://git.oschina.net/renchhao/gradle-test

在新建的项目下web项目根目录新建build.gradle文件,同时编写构建脚本。如下:

import org.gradle.plugins.ide.eclipse.model.Facet

apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse-wtp'

webAppDirName = 'WebContent'
sourceSets.main.java.srcDir 'src'
version = '1.0'
sourceCompatibility = 1.8
[compileJava]*.options*.encoding = 'UTF-8'

repositories {
  maven { url 'http://maven.aliyun.com/nexus/content/groups/public'}
  mavenLocal()
  mavenCentral()
}

ext {
  warName = 'gradle_test'
  springVersion = '4.2.3.RELEASE'
  hibernateVersion = '5.0.5.Final'
  hibernateSearchVersion = '5.5.1.Final'
  freemarkerVersion = '2.3.23'
  httpclientVersion = '4.5'
  jacksonVersion = '2.6.1'
}

war{
    baseName ="${warName}"
    from("$projectDir/src/") {
        include "**/*.xml"
        include "**/*.properties"
        into('WEB-INF/classes')
    }
}

dependencies {
  compile (
  "org.freemarker:freemarker:${freemarkerVersion}",

  'commons-logging:commons-logging:1.2',
  'commons-io:commons-io:2.4',
  'commons-fileupload:commons-fileupload:1.3.1',
  'commons-codec:commons-codec:1.10',
  'org.apache.commons:commons-collections4:4.0',
  'org.apache.commons:commons-lang3:3.4',

  "org.springframework:spring-context-support:${springVersion}",
  "org.springframework:spring-jdbc:${springVersion}",
  "org.springframework:spring-orm:${springVersion}",
  "org.springframework:spring-webmvc:${springVersion}",

  "org.hibernate:hibernate-core:${hibernateVersion}",
  "org.hibernate:hibernate-ehcache:${hibernateVersion}",
  "org.hibernate:hibernate-search:${hibernateSearchVersion}",

  'c3p0:c3p0:0.9.1.2',
  'mysql:mysql-connector-java:5.1.35',

  "com.fasterxml.jackson.core:jackson-core:${jacksonVersion}",
  "com.fasterxml.jackson.core:jackson-databind:${jacksonVersion}",
  "com.fasterxml.jackson.core:jackson-annotations:${jacksonVersion}",

  "org.apache.httpcomponents:httpclient:${httpclientVersion}",
  "org.apache.httpcomponents:httpmime:${httpclientVersion}",
  "org.apache.httpcomponents:httpclient-cache:${httpclientVersion}",

  'javax.activation:activation:1.1.1',
  'javax.transaction:jta:1.1',
  'javax.mail:mail:1.4.7',
    
  'org.slf4j:slf4j-api:1.7.10',
  'eu.bitwalker:UserAgentUtils:1.15',
  'antlr:antlr:2.7.7',
  'dom4j:dom4j:1.6.1',
  'net.coobird:thumbnailator:0.4.8',

  'org.apache.ant:ant:1.9.4',

  'org.quartz-scheduler:quartz:2.2.1',

  'cglib:cglib-nodep:3.1',
  'dom4j:dom4j:1.6.1'
  )
  compile('javax.servlet:javax.servlet-api:3.1.0')
}

eclipse {
  wtp {
    facet {
      facet name: 'jst.web', type: Facet.FacetType.fixed
      facet name: 'wst.jsdt.web', type: Facet.FacetType.fixed
      facet name: 'jst.java', type: Facet.FacetType.fixed
      facet name: 'jst.java', version: '1.8'
      facet name: 'jst.web', version: '3.1'
      facet name: 'wst.jsdt.web', version: '1.0'
    }
  }
}
task warApp(dependsOn: war){
  doLast{
    def tempWarDirOut = new File("${buildDir}/tmp/warApplication")
    tempWarDirOut.mkdirs()
    ant.unwar(src: "${buildDir}/libs/${warName}-${version}.war",
              dest: "${buildDir}/tmp/warApplication")
  }
}


在构建脚本中,主要做了几件事,引用war插件,引用eclipse-wtp插件,用于识别eclipse项目和war包的打包。
repositories中指定了阿里云的maven仓库,国内比较快。ext中定义了几个变量,包括war包名称和依赖项的版本号。
其中的warApp这个自定义task是用于把war进行解压的操作,有些时候,可能使用war中的文件,所以进行一个war解压,以便后续的操作。

  • 修改web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>gradle-test</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param> 
              <param-name>contextConfigLocation</param-name>
              <param-value>/WEB-INF/app-servlet.xml</param-value>
             </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>  
        <filter-name>characterEncodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter>  
    <filter-mapping>  
        <filter-name>characterEncodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  

    <!-- Spring配置 -->
    <!-- ====================================== -->
    <listener>
      <listener-class>
            org.springframework.web.context.ContextLoaderListener
      </listener-class>
    </listener>
    <!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:xin/lowang/config/app-context.xml</param-value>
    </context-param>
</web-app>

为了做一个完成的mvc项目,我们继续增加mvc配置和代码。在WebContent/WEB-INF下新增app-servlet.xml

  • /gradle-test/WebContent/WEB-INF/app-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
                        http://www.springframework.org/schema/mvc 
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
                        http://www.springframework.org/schema/context 
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd 
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- 启用spring mvc 注解 -->
    <context:annotation-config />
    <!-- 设置使用注解的类所在的jar包 -->
    <context:component-scan base-package="xin.lowang"></context:component-scan>
    <!-- 完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
    <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
    <mvc:annotation-driven>  
        <mvc:message-converters register-defaults="true">  
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
                <property name="supportedMediaTypes" value = "text/html;charset=UTF-8" />  
            </bean>  
        </mvc:message-converters>  
    </mvc:annotation-driven>
</beans>
  • /gradle-test/src/xin/lowang/config/app-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 启用spring mvc 注解 -->
    <context:annotation-config />
    <!-- 设置使用注解的类所在的jar包 -->
    <context:component-scan base-package="xin.lowang" />
</beans>
  • /gradle-test/src/xin/lowang/web/IndexController.java

package xin.lowang.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("indexController")
public class IndexController {
    @RequestMapping("/hello")
    @ResponseBody
    public String home() {
        return "你好";
    }
}

在eclipse中可以直接run on server,如果需要打包或者抽取文件,则执行gradle build/gradle warApp

    原文作者:LoWang
    原文地址: https://www.jianshu.com/p/f95528930424
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞