Create the project
I'm using Mars 2 distribution of Eclipse. To create the project, select New→Dynamic Web Project under Web.
I'm using Apache Tomcat server v8.0. Click Next and set the build class location and click Next. Make sure to Generate web.xml and click Finish.
Add Jersey to the project
Create the class
Now it's time to add the class to set the messages. Let's add a package named hello to src (Note: this value will be used in web.xml) and create a class in it as follows:
package hello; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("hello") public class Hello { @GET @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello Jersey"; } }
Configure web.xml
Update the web.xml file as follows. This will register Jersey to handle requests.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Hello World REST example</display-name> <servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>hello</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
Run the service
You can run the service by right clicking on the project and choosing Run as →Run on server to run the service. Go to http://localhost:8080/HelloWorldREST/rest/hello to view the results.
0 comments:
Post a Comment