gradle中使用嵌入式(embedded) tomcat, debug 启动

在gradle项目中使用embedded tomcat。

最开始部署项目需要手动将web项目打成war包,然后手动上传到tomcat的webapp下,然后启动tomcat来部署项目。这种手动工作通常还要指定端口,指定项目位置等,这些操作是重复的操作。

开发的时候,ide自然想到集成这些功能,于是都是server模块,设置好参数就可以run server,测试了。个人操作的时候确实挺方便的,然而当团队协作的时候,每个人都要手动去设置这些参数,而且大家或许还在使用着各种各样的idea。eclipse和idea的配置方式截然不同。这好在都是java程序员,但还有前端呢,前端的同事一起开发的时候,他们会感觉这些配置繁琐。

后来发现,框架发展到现在反而更倾向于命令行的方式了。embedded 就是一种流行的方式。

当项目集成了embedded tomcat之后,只要type gradlew tomcatRun就可以运行项目。这样即使是前端程序员也可以本地调试项目了。

1.创建一个gradle web项目

在idea中,new -> project -> gradle -> web 就可以创建一个空的gradle web项目。

在build.gradle 中添加tomcat的依赖:

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.5'
    }
}
dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'

    def tomcatVersion = '7.0.59'
    tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
            "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}",
            "org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}"
}

添加tomcat 插件:

apply plugin: 'com.bmuschko.tomcat'

2. 运行

这时候就可以运行了。在命令行中输入:

gradlew tomcatRun

第一次运行会下载对应的jar包,然后显示:

Started Tomcat Server                                          
The Server is running at http://localhost:8080/embTomcat

端口默认8080,contextPath默认为项目名。

2.1 Task

tomcatRun 为 运行 exploded web application;

tomcatRunWar 则是运行war包。

Task Name

Depends On

Type

Description

tomcatRun

-

TomcatRun

Starts a Tomcat instance and deploys the exploded web application to it.

tomcatRunWar

-

TomcatRunWar

Starts a Tomcat instance and deploys the WAR to it.

tomcatStop

-

TomcatStop

Stops the Tomcat instance.

tomcatJasper

-

TomcatJasper

Runs the JSP compiler and turns JSP pages into Java source usingJasper.

2.2修改默认配置

习惯了'/'作为contextPath:

tomcatRun.contextPath = '/'
tomcatRunWar.contextPath = '/'

这时候运行结果:

:tomcatRunWar                 
Started Tomcat Server
The Server is running at http://localhost:8080

8080端口就挺好的,当然,如果想要自定义也是可以的:

tomcatRun.httpPort=8089

事实上,也提供可更加细腻的自定设置。这时候需要再添加一个依赖:

apply plugin: 'com.bmuschko.tomcat-base'

然后一个自定配置实例

tomcat {
    httpPort = 8090
    httpsPort = 8091
    enableSSL = true
    contextPath = 'sample-app'

    users {
        user {
            username = 'user1'
            password = '123456'
            roles = ['developers', 'admin']
        }

        user {
            username = 'user2'
            password = 'abcdef'
            roles = ['manager']
        }
    }
}

启动运行:

D:\workspace\springboot\embTomcat>gradlew tomcatRun --stacktrace
:compileJava UP-TO-DATE                                                                                                                                                             
:processResources UP-TO-DATE
:classes UP-TO-DATE
:tomcatRun                                                     
Started Tomcat Server
The Server is running at http://localhost:8090/sample-app

可以看到,这个开启了https,页面可以直接访问https的地址了。端口设置为8091. 通过都设置为8443.

2.3 Extension properties

The Tomcat plugin exposes the following properties through the extension named tomcat:

  • httpPort: The TCP port which Tomcat should listen for HTTP requests on (defaults to 8080).
  • httpsPort: The TCP port which Tomcat should listen for HTTPS requests on (defaults to 8443).
  • ajpPort: The TCP port which Tomcat should listen for AJP requests on (defaults to 8009).
  • stopPort: The TCP port which Tomcat should listen for admin requests on (defaults to 8081).
  • stopKey: The key to pass to Tomcat when requesting it to stop (defaults to null).
  • contextPath: The URL context path under which the web application will be registered (defaults to WAR name).
  • enableSSL: Determines whether the HTTPS connector should be created (defaults to false).
  • daemon: Specifies whether the Tomcat server should run in the background. When true, this task completes as soon as the server has started. When false, this task blocks until the Tomcat server is stopped (defaults to false).
  • keystoreFile: The keystore file to use for SSL, if enabled (by default, a keystore will be generated).
  • httpProtocol: The HTTP protocol handler class name to be used (defaults to org.apache.coyote.http11.Http11Protocol).
  • httpsProtocol: The HTTPS protocol handler class name to be used (defaults toorg.apache.coyote.http11.Http11Protocol).
  • ajpProtocol: The AJP protocol handler class name to be used (defaults to org.apache.coyote.ajp.AjpProtocol).
  • users: List of users with usernamepassword and roles. Used to configure tomcat with basic authentication with these users.

到这里基本已经可以使用了。当然,如果想要更多的了解深入的配置:https://github.com/bmuschko/gradle-tomcat-plugin

Task properties Furthermore, you can set the following optional task properties:

  • contextPath: The URL context path your web application will be registered under (defaults to WAR name).
  • webDefaultXml: The default web.xml. If it doesn't get defined an instance oforg.apache.catalina.servlets.DefaultServlet and org.apache.jasper.servlet.JspServlet will be set up.
  • additionalRuntimeResources: Defines additional runtime JARs or directories that are not provided by the web application.
  • URIEncoding: Specifies the character encoding used to decode the URI bytes by the HTTP Connector (defaults to UTF-8).
  • daemon: Specifies whether the Tomcat server should run in the background. When true, this task completes as soon as the server has started. When false, this task blocks until the Tomcat server is stopped (defaults to false).
  • configFile: The path to the Tomcat context XML file (defaults to src/main/webapp/META-INF/context.xml for tomcatRun, defaults to META-INF/context.xml within the WAR for tomcatRunWar).
  • outputFile: The file to write Tomcat log messages to. If the file already exists new messages will be appended.
  • reloadable: Forces context scanning if you don't use a context file (defaults to true).
  • keystorePass: The keystore password to use for SSL, if enabled.
  • truststoreFile: The truststore file to use for SSL, if enabled.
  • truststorePass: The truststore password to use for SSL, if enabled.
  • clientAuth: The clientAuth setting to use, values may be: truefalse or want (defaults to false).

Note: keystoreFile and truststoreFile each require an instance of a File object e.g. file("/path/my.file") Example In the following example code, wes declare a custom context file for the task tomcatRun. tomcatRun.configFile = file('context.xml') To configure the Jasper compiler task you can choose to set the following properties within the jasper closure of thetomcat extension:

  • validateXml: Determines whether web.xml should be validated (defaults to null).
  • validateTld: Determines whether web.xml should be validated (defaults to null).
  • uriroot: The web application root directory (defaults to src/main/webapp).
  • webXmlFragment: The generated web XML fragment file to be referenced by your web.xml file.
  • addWebXmlMappings: Automatically add the generated web XML fragment to the web.xml file. Caution: this will modify the web.xml file in the project, not the build directory.
  • outputDir: The output directory the compiled JSPs will end up in (defaults to build/jasper).
  • classdebuginfo: Should the class file be compiled with debugging information (defaults to true).
  • compiler: Which compiler Ant should use to compile JSP pages. See the Ant documentation for more information. If the value is not set, then the default Eclipse JDT Java compiler will be used instead of using Ant. No default value.
  • compilerSourceVM: What JDK version are the source files compatible with (defaults to 1.6).
  • compilerTargetVM: What JDK version are the generated files compatible with (defaults to 1.6).
  • poolingEnabled: Determines whether tag handler pooling is enabled. This is a compilation option. It will not alter the behaviour of JSPs that have already been compiled (defaults to true).
  • errorOnUseBeanInvalidClassAttribute: Should Jasper issue an error when the value of the class attribute in an useBean action is not a valid bean class (defaults to true).
  • genStringAsCharArray: Should text strings be generated as char arrays, to improve performance in some cases (defaults to false).
  • ieClassId: The class-id value to be sent to Internet Explorer when using <jsp:plugin> tags (defaults to clsid:8AD9C840-044E-11D1-B3E9-00805F499D93).
  • javaEncoding: Java file encoding to use for generating java source files (defaults to UTF8).
  • trimSpaces: Should white spaces in template text between actions or directives be trimmed (defaults to false).
  • xpoweredBy: Determines whether X-Powered-By response header is added by generated servlet (defaults to false).

Example tomcat { jasper { validateXml = true webXmlFragment = file("$webAppDir/WEB-INF/generated_web.xml") outputDir = file("$webAppDir/WEB-INF/src") } }

2.4FAQ

编译错误!

org.apache.jasper.JasperException: Unable to compile class for JSP

tomcat7+需要一个jar包来编译,如果没有则添加:

repositories {
     flatDir name: 'localRepository', dirs: 'lib'
}

反正我是没遇到。

Why do I get a java.lang.ClassCastException on javax.servlet.Servlet?

依赖多个版本servlet-api导致了错误:

java.lang.ClassCastException: org.springframework.web.servlet.DispatcherServlet cannot be cast to javax.servlet.Servlet
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1062)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1010)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4935)
        at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5262)
        at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5257)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
        at java.util.concurrent.FutureTask.run(FutureTask.java:138)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:662)

解决:只在编译的时候使用:

providedCompile 'javax.servlet:servlet-api:2.5',
                'javax.servlet:jsp-api:2.0'

2.4 Debug

debug启动需要设置gradle的环境变量,即运行gradle命令的时候插入(fork)一些参数命令。

可以设置环境变量GRADLE_OPTS为:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005

即监听5005端口。这时候运行则会显示:

Listening for transport dt_socket at address: 5005

在idea中监听端口:Run->edit configurations ->+ -> remote, 默认配置就可以了。

什么?不知道怎么设置环境变量?

作为一个java程序员的第一件事就是设置环境变量。当然,我们可以在程序运行的时候添加环境变量,比如在idea中使用自带的gradle插件的时候指定参数,我感觉相当繁琐,不过还是记录下来。

首先,edit configurations  -> + -> gradle -> 

然后,点击运行:

这时候就已经在监听5005端口了,只需要添加remote debug就可以了:

edit configurations -> + -> remote:

debug:

2.5 gradle提供debug:

这种方式还是相当繁琐的。不就是设置环境变量吗,好吧,我确实没去研究怎么设置了,应该是在脚本中添加的,以后再研究吧。下面介绍一个简单的方式:

gradlew tomcatRun -Dorg.gradle.debug=true

没错,这样就可以了。剩下的监听remote同上。命令行结束会等待监听,debug remote就可以了。

github: https://github.com/winsnow/jsp-tag

reference:

https://github.com/bmuschko/gradle-tomcat-plugin/blob/master/README.md   
https://docs.gradle.org/current/userguide/gradle_command_line.html    
https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_properties_and_system_properties

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏技术墨客

Vert.x源码-创建集群 原

在当前的最新版本中,Vert.x官方只实现了利用Hazelcast来创建集群。当然,如果可以的话,也可以通过ClusterManager接口实现或引入需要的集群...

923
来自专栏静默虚空的博客

[Spring]01_环境配置

1.1 Spring jar包下载 (1)进入官网http://repo.spring.io (2)在资源库界面点击Artifacts标签,然后点击libs-...

1789
来自专栏编程心路

SSH框架之旅-hibernate(1)

什么是框架呢?个人觉得在软件设计中,框架可以看作是架构组件。如果把整个程序看作是一个人的话,那么框架可以看出是一个人的骨架,我们要做的的就是在这个框架的基础上进...

603
来自专栏有困难要上,没有困难创造困难也要上!

Python2运行时查看线程信息

3428
来自专栏web编程技术分享

【Java框架型项目从入门到装逼】第七节 - 学生管理系统项目搭建

2587
来自专栏NetCore

AppFuse项目笔记(1)

AppFuse项目笔记(1) 一、Appfuse简介 Appfuse是Matt Raible 开发的一个指导性的入门级J2EE框架,它对如何集成流行的Sprin...

2145
来自专栏WindCoder

SSM笔记(一)框架整合

用了好久了,但都是当初大神配置完后直接粘贴复制过来的,一直没仔细看过相关配置,趁此机会对自己也算是一个复习与深入,也希望对初学者有所帮助。本系列均是基于IDEA...

431
来自专栏非著名程序员

【强势回归,Android开发疑难杂症】Process 和 ProcessBuilder 区别

前段时间在开发Android项目当中,发现需要更改文件权限,所以接触了Linux的一些文件权限问题。 Android系统中,在data/data/包名/ 这个...

1825
来自专栏代码拾遗

Spring Boot 2.0 教程 - 配置详解

Spring Boot 可以通过properties文件,YAML文件,环境变量和命令行参数进行配置。属性值可以通过,@Value注解,Environment...

803
来自专栏CSDN技术头条

快速实战 Spring Boot

解释一下:Spring Boot 可以构建一切。Spring Boot 设计之初就是为了最少的配置,最快的速度来启动和运行 Spring 项目。Spring B...

1005

扫描关注云+社区