2019年2月28日 星期四

[JAVA] RESTful Webservice using eclipse and TomEE 1.75

1. Download TomEE that supports JAX-RS (In this example, I choose TomEE jaxrs 1.75)

Comparison matrix: http://tomee.apache.org/comparison.html

Download: http://tomee.apache.org/download-ng.html

2. Download Eclipse: https://www.eclipse.org/downloads/

3. Unzip TomEE package

4. Open Eclipse

> Create New Server
> Set name = TomEE 1.75
> Choose Apache Tomcat 7.0
> Browse
> Select the TomEE path (e.g. D:\Documents\java\apache-tomee-jaxrs-1.7.5)

We choose Apache Tomcat 7.0 because this version of TomEE is created base on it.

5. Create a "Dynamic Web Project"

> Project name = HelloRest
> Select Dynamic Web Module 3.0
> Target RunTime = TomEE 1.75
> Finish

6. Add a java class called "HelloService.java"

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

@Path("/")
public class HelloService {

@Path("/")
@GET
@Produces(MediaType.TEXT_HTML)
public String index() {
return "index";
}

@Path("/hello/{name}")
@GET
@Produces(MediaType.TEXT_HTML)
public String getContact(
            @PathParam("name") String name) {
        return "My name is "+name+".";
    }
}

7. Right click project "HelloRest" > Run As > Run On Server

http://localhost:8080/HelloRest/

(Display "index")


http://localhost:8080/HelloRest/hello/Peter

(Display "My name is Peter.")

Good luck

沒有留言:

張貼留言