no

How to enable Jersey REST api in a maven web project

This tutorial assumes that you already know how to create a maven project in eclipse. Steps: 1.) Create a new maven web project. (this assu...

This tutorial assumes that you already know how to create a maven project in eclipse. Steps: 1.) Create a new maven web project. (this assumes that you have maven plugin installed in your eclipse). 2.) In your META-INF/web.xml file make sure that you have the ff code:
<servlet>
 <servlet-name>Jersey REST Service</servlet-name>
 <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
 <init-param>
  <param-name>com.sun.jersey.config.property.packages</param-name>
  <param-value>com.ipiel.xxx</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
 <servlet-name>Jersey REST Service</servlet-name>
 <url-pattern>/api/*</url-pattern>
</servlet-mapping>
3.) Note the value of com.sun.jersey.config.property.packages, this tells us that it will examine the classes inside com.ipiel.xxx for REST enabled web services.
@Path("/hello")
public class Hello {
 @GET
 @Path("/world")
 public Response sayHello() {
  String hello = "Hello World!";
  return Response.status(200).entity(hello).build();
 }
}
4.) Make sure that you have the ff definition in your pom.xml
<dependency>
 <groupId>com.sun.jersey.contribs</groupId>
 <artifactId>jersey-spring</artifactId>
 <version>${jersey.version}</version>
 <exclusions>
  <exclusion>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
  </exclusion>
  <exclusion>
   <groupId>org.springframework</groupId>
   <artifactId>spring</artifactId>
  </exclusion>
  <exclusion>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
  </exclusion>
  <exclusion>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
  </exclusion>
  <exclusion>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
  </exclusion>
  <exclusion>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
  </exclusion>
 </exclusions>
</dependency>
5.) Compile and deploy the war/ear in a container (jboss, glassfish, etc). 6.) Now you can access the web app in your localhost: http://localhost:port/appname/api/hello/world And it should output "Hello World!". Note: In case you want to add parameter to your web service, this is how you will code it:
@Path("/reverse")
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces({ MediaType.APPLICATION_JSON })
public Response reverse(@FormParam("orderId") long orderId) {
}

Related

java 5258039465226263364

Post a Comment

item