Hello World Example

A REST resource is simply a Java class annotated with {@link oajr.annotation.Rest}. The most common case is a class that extends {@link oajr.RestServlet}, which itself is simply an extension of {@link javax.servlet.http.HttpServlet} which allows it to be deployed as a servlet.

In this example, we define a resource called HelloWorldResource. This example is located in the juneau-examples-rest project. It's assumed the reader is familiar with defining servlets in web applications.

Like any servlet, we could define our resource in the web.xml file of the web application like so...

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.3"> <servlet> <servlet-name>HelloWorldResource</servlet-name> <servlet-class>com.foo.sample.HelloWorldResource</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldResource</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>

Our servlet code is shown below:

// Sample REST resource that prints out a simple "Hello world!" message. @Rest( path="/helloWorld", title="Hello World", description="An example of the simplest-possible resource" ) @HtmlDoc( navlinks={ "up: request:/..", "options: servlet:/?method=OPTIONS" }, aside={ "<div style='max-width:400px' class='text'>", " <p>This page shows a resource that simply response with a 'Hello world!' message</p>", " <p>The POJO serialized is a simple String.</p>", "</div>" } ) public class HelloWorldResource extends BasicUniversalRest { @RestMethod(name=GET, path="/*", summary="Responds with \"Hello world!\"") public String sayHello() { return "Hello world!"; } }

This is what it looks like in a browser:

http://localhost:10000/helloWorld

It doesn't much simpler than that. In this case, we're simply returning a string that will be converted to any of the supported languages (e.g. JSON, XML, HTML, ...). However, we could have returned any POJO consisting of beans, maps, collections, etc...

The {@link oajr.BasicRestServlet} class that we're using here is a subclass of {@link oajr.RestServlet} that provides default support for a variety of content types. Implementers can choose to use this class, or create their own subclass of {@link oajr.RestServlet} with their own specialized serializers and parsers.