Create a one jar REST web service in JAVA for less than 5 minutes

More than a decade after its introduction, REST has become one of the most important technologies for Web applications. Its importance is likely to continue growing quickly as all technologies move towards an API orientation. This simple tutorial will help you build in less than 5 minutes a REST web services implementation using JAVA.

Tools that I used:

– Netbeans
– Maven (Contained in Netbeans)
– Spring boot (Auto downloaded by Maven)

Step 1. Create a new project.

Open Netbeans and select New project -> Maven -> Java Application.
Give to your project a decent name, path, package name and hit finish.
This should create for you an empty maven project.
In case you want to skip Netbeans for project creation, navigate to maven and run :
mvn archetype:generate -DgroupId=my.package -DartifactId=myProjectName -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Step 2. Add spring boot.

Spring boot will actually do the whole job here. It will attach to your project Apache Tomcat and do all the dirty work behind the scenes.
The spring boot package that you need is spring-boot-starter-web. You can add it to your project either from NetBeans by right clicking the dependencies folder and then selecting add dependency or just open your pom.xml and add:
<dependencies>

 

        <dependency>

 

            <groupId>org.springframework.boot</groupId>

 

            <artifactId>spring-boot-starter-web</artifactId>

 

            <version>1.1.9.RELEASE</version>

 

        </dependency>

</dependencies>

Note: You don’t have to use the same version (1.1.9.RELEASE). I used this because it was the last one.
After adding spring boot, navigate to it’s website (http://projects.spring.io/spring-boot/) and you will see there a nice sample Java class named SampleController. As you can see the specific Class declares a simple REST web service that listens on port 8080 on localhost/ .
Copy it as it is into your project and modify it writing the following:
import org.springframework.boot.*;

 

import org.springframework.boot.autoconfigure.*;

 

import org.springframework.http.MediaType;

 

import org.springframework.stereotype.*;

 

import org.springframework.web.bind.annotation.*;

 

 

 

@Controller

 

@EnableAutoConfiguration

 

public class SampleController {

 

 

 

    @RequestMapping(value = “/”,

 

            method = RequestMethod.GET,

 

            produces = MediaType.APPLICATION_JSON_VALUE)

 

    @ResponseBody

 

    Person home() {

 

        Person p = new Person();

 

        p.setFirstName(“Agis”);

 

        p.setLastName(“Kefalinos”);

 

        return p;

 

    }

 

   

 

    @RequestMapping(value = “/who”,

 

            method = RequestMethod.POST,

 

            produces = MediaType.TEXT_PLAIN_VALUE,

 

            consumes = MediaType.APPLICATION_JSON_VALUE)

 

    @ResponseBody

 

    String who(@RequestBody Person p, @RequestParam(value = “action”, required = false) String action) {

 

        return action + ” ” + p.getFirstName();

 

    }

 

 

 

    public static void main(String[] args) throws Exception {

 

        SpringApplication.run(SampleController.class, args);

 

    }

 

}
Also Add the following helper Class:
public class Person {

 

   

 

    private String firstName;

 

    private String lastName;

 

 

 

    public String getFirstName() {

 

        return firstName;

 

    }

 

 

 

    public void setFirstName(String firstName) {

 

        this.firstName = firstName;

 

    }

 

 

 

    public String getLastName() {

 

        return lastName;

 

    }

 

 

 

    public void setLastName(String lastName) {

 

        this.lastName = lastName;

 

    }   
}
This will actually add to your project the following:
– A REST GET method that listens at localhost:8080/ and returns a Person POJO as JSON like: {“firstName”:”Agis”,”lastName”:”Kefalinos“}
– A REST POSTmethod that listens at localhost:8080/who that consumes a Person POJO and uses an optional query parameter named action . The response of that WS is the concatenation of the query parameter plus the first name of the POSO Person.
Now that we finished with a typical business logic we can actually run our project and see the results.

Step 3. Create a runnable single Jar.

If we run it inside Netbeans it will run without any problem and do the trick. The problem will come if we try to run it from command like “java –jar myproject.jar”.
Doing so we will have 2 problems:
1) The jar does not know which method is the MAIN and we have to provide it to maven. To do it just add to pom.xml under plugins:
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>my.package.SampleController</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
Note: Replace my.package.SampleController with your main’s full Class name.
2) The second problem is that the spring boot is not at your class path so the jar as it is will not run. An interesting way to bypass this problem is to build your app having all other dependencies included into your jar. Of course that will increase the size of you jar but sometimes this is the way to go. To do it you will need to add to pom.xml under plugins the following:
            <plugin>
                <groupId>org.dstovall</groupId>
                <artifactId>onejar-maven-plugin</artifactId>
                <version>1.4.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>one-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
Also add to your pom.xml under project the following:
    <pluginRepositories>
        <pluginRepository>
            <id>onejar-maven-plugin.googlecode.com</id>
            <url>http://onejar-maven-plugin.googlecode.com/svn/mavenrepo</url>
        </pluginRepository>
    </pluginRepositories>
Rebuild your project and you will notice that apart from your myproject.jar another jar is created named myproject.one-jar.jar. This jar will contain all the needed libraries for your project to run. 
Open your console and hit “java –jar myproject.jar”. Then open your favorite browser and navigate to http://localhost:8080/

That’s it, you are set!

Sample source code here: https://github.com/mdagis/SpringBootTest

Leave a Reply

Your email address will not be published. Required fields are marked *