Jersey JAXB with Rest Client Example

1 Flares 1 Flares ×

Jersey framework is a JAX-RS Reference Implementation to develop Restful Web services. Jersey simplifies Restful service and client development.Here we will see Jersey with JAXB  example.

Before Read our post about Simple Restful Web Services using MySQL.

Jersey JAXB 

I have used following jar files.

jersey-client-1.17.1.jar,jersey-core-1.17.1.jar,jersey-json-1.17.1.jar,jersey-server-1.17.1.jar,jersey-servlet-1.17.1.jarasm-3.3.1.jar ,asm-attrs.jar.

Project Structure.

Project Structure

Step 1 : Create Dynamic Web Project in Eclipse.And Create web.xml like below


<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <servlet>
 <servlet-name>ServletAdaptor</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.jersey.demo.rest</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>ServletAdaptor</servlet-name>
 <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>

</web-app>

Step 2: To Integrate JAXB with Jersey we need jersey-server-1.17.1.jar file.Create User Class and Annotate a object with JAXB Annotation(XmlRootElement).

Note: When a top level class or an enum type is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.

You can also use @XMLElement and @XMLAttribute if you want.

@XmlAttribute
@XmlAttribute

package com.jersey.demo.pojo;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class User {

private int userid;

public int getUserid() {
 return userid;
 }

public void setUserid(int userid) {
 this.userid = userid;
 }

public String getUsername() {
 return username;
 }

public void setUsername(String username) {
 this.username = username;
 }

public String getPassword() {
 return password;
 }

public void setPassword(String password) {
 this.password = password;
 }

public String getRole() {
 return role;
 }

public void setRole(String role) {
 this.role = role;
 }

private String username;

private String password;

private String role;

}

Step 3 : Create UserService Class which will handle your rest services. Java methods inside the classes are annotated with @Produces,@Consumes.

The @Produces annotation is used to specify the MIME media types of representations a resource can produce and send back to the client.The @Consumes annotation is used to specify the MIME media types of representations that can be consumed by a resource.Here I have used MediaType as APPLICATION_XML.


package com.jersey.demo.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.jersey.demo.pojo.User;

@Path("/user")
public class UserService {

@GET
 @Path("/{id}")
 @Produces(MediaType.APPLICATION_XML)
 public User getUserById(@PathParam("id") int id) {

User user = new User();
 user.setUsername("mohan");
 user.setPassword("mohan");
 user.setRole("admin");
 user.setUserid(id);

return user;
 }

@POST
 @Path("/{createuserid}")
 @Consumes(MediaType.APPLICATION_XML)
 public Response createUser(@PathParam("createuserid") int createuserid,
 User createuser) {

System.out.println("Create User" + createuser.getUsername());

String result = "User = "+createuser.getUsername()+" Created Successfully";

 return Response.status(200).entity(result).build();

}

}

How to Test Your Implementation

You can write rest client java program to test your implementation or try Advanced Rest Client like Chrome Extension.

Sample RestClient for Post Request


package com.jersey.demo.rest;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.jersey.demo.pojo.User;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class RestClient {

public static void main(String[] args) {

User user = new User();
 user.setUsername("mohan");
 user.setPassword("mohan");
 user.setRole("admin");
 user.setUserid(123);

ClientConfig config = new DefaultClientConfig();
 Client client = Client.create(config);
 WebResource service = client.resource(getBaseURI());

ClientResponse response = service.path("rest").path("user").path("123")
 .type(MediaType.APPLICATION_XML)
 .post(ClientResponse.class, user);
 System.out.println(response.getStatus());
 if (response.getStatus() == 200) {
 System.out.println("Create User Success");
 } else {
 System.out.println("Create User Failed");
 }
 }

private static URI getBaseURI() {
 return UriBuilder.fromUri("http://localhost:8080/JERSEY-JAXB/").build();
 }
}

Or

Using Advanced Rest Client like Chrome Extension.

Jersey Post Request

Jersey Get Request

About admin

This is Mohan Jayapalan author of TechPages Blog.I am a part time blogger and Currently working for private Software Concern.

  • kumar shorav

    I have a JAX-RS Restful webservice. This resource/webservice is asset
    for us. I am exposing this service url to third party client that would
    call this service resource. I want to protect this service from another
    authorised client/vendors.

    Thus my question is -

    How to protect this.

    I thought to include an API key and the API key should be matched
    with a perticuler client API Key. And I also need to match the client
    url address means from whcih url the request is coming.

    How to do this. How to get the URL that is calling the our rest service. I am deploying my rest in Tomcat 7.0.

1 Flares Twitter 1 Facebook 0 Google+ 0 StumbleUpon 0 1 Flares ×