参考:https://guides.gradle.org/building-java-web-applications
1.运行和调试
IDEA创建gradle项目,项目结构如下
各个文件:
build.gradle
// https://guides.gradle.org/building-java-web-applicationsplugins { id 'java' id 'war' id 'org.akhikhl.gretty' version '1.4.2'}group 'ServletDemo'version '1.0-SNAPSHOT'sourceCompatibility = 1.8repositories { mavenCentral()}dependencies { // https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0' testCompile group: 'junit', name: 'junit', version: '4.12'}
HelloServlet.java
package servlets;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet(name = "HelloServlet", urlPatterns = {"hello"}, loadOnStartup = 1)public class HelloServlet extends HttpServlet { int i = 0; // Servlet "persistence" protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.getWriter().print("Hello, World! " + i++); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); if (name == null) name = "World"; request.setAttribute("user", name); request.getRequestDispatcher("response.jsp").forward(request, response); }} ///:~
index.html
Servlet Demo Say Hello
response.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>Hello Page Hello, ${user}!
然后点击左侧的Gradle面板,选择任务gretty.appRun就可以启动app,通过localhost:8080访问
如果要 调试,那么在Gradle面板中选择任务gretty.appRunDebug,启动该任务后,选择Run->Edit Configurations 然后添加一个Remote Run/Debug,如下图,名为DebugServletDemo,根据gretty官方文档,默认debug port是5005,所以这里填好host和port
然后在Gradle面板中启动任务gretty.appRunDebug,如下图Run选项卡中所示,在5005端口等待Debugger的连接
接下来再启动Run->Debug->DebugServletDemo,如下图Debug选项卡中所示,Debugger已连接上5005端口
此时再次查看Run选项卡,会发现其中内容如下,点击该http链接开始调试
2.部署到tomcat
2.1. 打包war只需要Gradle面板中选择build.build任务即可,然后把war包放到tomcat安装目录的webapps/目录下,这里我的war包名为ServletDemo-1.0-SNAPSHOT.war
2.2. 修改tomcat安装目录下的conf/tomcat-users.xml,如下内容,从而可以使用tomcat的管理权限
2.3. 启动tomcat,访问localhost:8080,如下:
2.4. 点击"Manager App"按钮,进入如下页面,然后start ServletDemo-1.0-SNAPSHOT即可访问
2.4.1. 这里我发现war包的app不能启动,在tomcat的logs/manager.2018.xx.xx.log中发现报错Invalid <url-pattern> [hello] in servlet mapping,去HelloServlet.java中把urlPatterns="hello"改为urlPatterns="/hello"即可}改为