Yihsi

使用 Gretty 在 IDEA 中运行 Spring Web 项目

由于 IDEA Community 版本不支持配置 Tomcat、Jetty 之类的 Web Server,所以使用此版本的 IDEA 要借助插件来进行 Spring Web MVC 应用的开发。之前有使用过 tomcat7-maven-plugin,所以在使用 Gradle 和 Jetty 的时候就去搜索是否有类似的插件,然后就找到了 Gretty 。

下面就是我整理的 Gretty 插件的配置文件 gretty.plugin ,支持 Debug:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Enable debugging of gretty started webapp in IDEA
// For debuging a gradle task, IDEA creates a gradle init script (in /tmp/ijinit#.gradle), that sets JVM arguments
// to enable remote debugging.
// Unfortunately by default that only works for gradle tasks that implement JavaForkOptions - which gretty doesn't do.
// So parse the JVM args that IDEA uses from that init script and set them as JVM args to be used by gretty:
def debugArgs = []
if (gradle.startParameter.initScripts) {
def line = file(gradle.startParameter.initScripts[0]).readLines().findAll({x -> x ==~ /.*-agentlib:jdwp=.*/ })[0]
if (line) {
debugArgs = ((line =~ /.*'(.*)'.*/)[0][1] as String).split(' ')
}
}
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'org.gretty:gretty:2.2.0'
}
}
repositories {
jcenter()
}
apply plugin: 'org.gretty'
gretty {
httpPort = 8080
contextPath = "/"
servletContainer = 'jetty9'
jvmArgs = ['-Dorg.eclipse.jetty.annotations.maxWait=300', *debugArgs]
}

然后在你的 web 应用的 build.gradle 中添加如下内容:

1
2
3
4
plugins {
...
id "org.gretty" version "2.2.0"
}
1
2
apply plugin: 'war'
apply from: '/path/to/gretty.plugin'

现在你就可以使用 gradle appRunWar 来运行 Web 应用了。如果在 IDEA 中配置了 Tasks 为 appRunWar 的 Run Configurations ,那么直接点击 IDEA 中的 debug 按钮就可以进行 debug 了。

参考

1、http://akhikhl.github.io/gretty-doc/Getting-started.html
2、https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000186970-How-to-Debug-webb-app-started-with-gradle-gretty