Go Gradle ! Servlets with Gradle

Gradle is build automation tool which is collection of all good things of ANT and Maven.For more reading on it follow https://gradle.org/

Today I am posting one sample Gradle Servlet project. Gradle easily supports Java web applications through the “war” and “jetty” plugins. My steps will show you how to quickly make a simple Java Servlet web application ( I am using here STS IDE).

Steps :
(1) Add Gradle plugin (easiest way to do it, goto STS dashborad, search and
add gradle plugin).you need to install Gradle and provide the path of its bin in PATH in case you want to run project from command prompt.
(2) Create a project folder “GradleServlet”
(3) create a file “build.gradle”
(4) content of file “build.gradle”

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

repositories {
  mavenCentral()
}

dependencies {
  providedCompile 'javax.servlet:servlet-api:2.5'
  runtime 'javax.servlet:jstl:1.1.2'
}

(5) lets create the servlet at GradleServlet\src\main\java\com\HelloWorldServlet.java

package com;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet
{

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        resp.getOutputStream().write("Gradle is build automation tool which is collection of all good things of  ANT and Maven.".getBytes());
    }
}

(6) Finally let’s put web.xml at GradleServlet\src\main\webapp\WEB-INF\web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 <servlet>
 <display-name>HelloWorldServlet</display-name>
 <servlet-name>HelloWorldServlet</servlet-name>
 <servlet-class>com.HelloWorldServlet</servlet-class>
 </servlet>

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

</web-app>

(6) our Project is ready now, lets build and run it. Lets use commands

to build use —> gradle build
to crate .war of Application use —> gradle war
to run it by Jetty ( a light weight container ) use —-> gradle jettyrunwar
you should see similar lines on screen :

C:\sts_workspace\GradleServlet>gradle jettyrunwar
:compileJava
:processResources UP-TO-DATE
:classes
:war
> Building 80% > :jettyRunWar > Running at http://localhost:8080/GradleServlet

You can get the source code from https://github.com/SkilledMinds/easyNuts