Tuesday, May 23, 2017

JavaEE: Restful Web Service in 5 minutes on TomEE

Let's create a simple REST service with TomEE and Eclipse
- Setup
(You may not need to download TomEE if you use a TomEE Maven plugin as shown here)


1.  Download TomEE.  To create a REST service, download TomEE Plus
     http://tomee.apache.org/downloads.html

2.  Include the TomEE server to Eclipse.  TomEE 7 uses a tomcat v8.5 server. On the Eclipse 'Servers' view, right click --> New --> Server.

Then, click the Finish.

3.  On Eclipse, create a Maven project. File --> New --> Other --> Maven Project.

Check 'Create a simple project'.  Specify a group id and artifact id.  Then, click a Finish button. (I assume you already have a maven Eclipse plugin)

4.   On the pom.xml, we need to add a javaee jar file.  This is the basic contents in the pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.jihwan.jee</groupId>
   <artifactId>demo</artifactId>
   <version>0.1-SNAPSHOT</version>
   <packaging>war</packaging>
   <name>JEE_Work</name>
   <description>work on JEE</description>
 
   <properties>
      <failOnMissingWebXml>false</failOnMissingWebXml>
     <maven.compiler.target>1.8</maven.compiler.target>
     <maven.compiler.source>1.8</maven.compiler.source>
   </properties>
 
   <dependencies>
      <!-- https://mvnrepository.com/artifact/org.apache.tomee/javaee-api -->
      <dependency>
         <groupId>org.apache.tomee</groupId>
         <artifactId>javaee-api</artifactId>
         <scope>provided</scope>
         <version>7.0-1</version>
      </dependency>
   </dependencies>
</project>

- Writing RESTful service

RESTful web services are loosely coupled, lightweight web services that are particularly well suited for creating APIs for clients spread out across the internet.  In the REST architectural style, data and functionality are considered resources and are accessed using URIs
Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path.  This class is a simplest RESTful web service.

package work.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/hello")
public class HelloService {
    @GET
    public String message() {
        return "Hello RESTful world!";
    }
}

- Running the service

Run TomEE server after adding the 'demo' resource via Eclipse.
Open http://localhost:8080/demo/hello
You will see a "Hello REST world!" message.


No comments:

Post a Comment

Java 9: Flow - Reactive Programming

Programming world has always been changed fast enough and many programming / design paradigms have been introduced such as object oriented p...