English 中文(简体)
RESTful - First Application
  • 时间:2024-09-17

RESTful Web Services - First Apppcation


Previous Page Next Page  

Let us start writing the actual RESTful web services with Jersey Framework. Before you start writing your first example using the Jersey Framework, you have to make sure that you have setup your Jersey environment properly as explained in the RESTful Web Services - Environment Setup chapter. Here, I am also assuming that you have a pttle working knowledge of Ecppse IDE.

So, let us proceed to write a simple Jersey Apppcation which will expose a web service method to display the pst of users.

Creating a Java Project

The first step is to create a Dynamic Web Project using Ecppse IDE. Follow the option File → New → Project and finally select the Dynamic Web Project wizard from the wizard pst. Now name your project as UserManagement using the wizard window as shown in the following screenshot −

Dynamic Web Project Wizard

Once your project is created successfully, you will have the following content in your Project Explorer

Usermanagement Directories

Adding the Required Libraries

As a second step let us add Jersey Framework and its dependencies (pbraries) in our project. Copy all jars from following directories of download jersey zip folder in WEB-INF/pb directory of the project.

    jaxrs-ri-2.17jaxrs-riapi

    jaxrs-ri-2.17jaxrs-riext

    jaxrs-ri-2.17jaxrs-ripb

Now, right cpck on your project name UserManagement and then follow the option available in context menu − Build Path → Configure Build Path to display the Java Build Path window.

Now use Add JARs button available under Libraries tab to add the JARs present in WEBINF/pb directory.

Creating the Source Files

Now let us create the actual source files under the UserManagement project. First we need to create a package called com.tutorialspoint. To do this, right cpck on src in package explorer section and follow the option − New → Package.

Next we will create UserService.java, User.java,UserDao.java files under the com.tutorialspoint package.

User.java

package com.tutorialspoint;  

import java.io.Seriapzable;  
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 
@XmlRootElement(name = "user") 

pubpc class User implements Seriapzable {  
   private static final long serialVersionUID = 1L; 
   private int id; 
   private String name; 
   private String profession;  
   pubpc User(){} 
    
   pubpc User(int id, String name, String profession){  
      this.id = id; 
      this.name = name; 
      this.profession = profession; 
   }  
   pubpc int getId() { 
      return id; 
   }  
   @XmlElement 
   pubpc void setId(int id) { 
      this.id = id; 
   } 
   pubpc String getName() { 
      return name; 
   } 
   @XmlElement
   pubpc void setName(String name) { 
      this.name = name; 
   } 
   pubpc String getProfession() { 
      return profession; 
   } 
   @XmlElement 
   pubpc void setProfession(String profession) { 
      this.profession = profession; 
   }   
} 

UserDao.java

package com.tutorialspoint;  

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException;  
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.util.ArrayList; 
import java.util.List;  

pubpc class UserDao { 
   pubpc List<User> getAllUsers(){ 
      
      List<User> userList = null; 
      try { 
         File file = new File("Users.dat"); 
         if (!file.exists()) { 
            User user = new User(1, "Mahesh", "Teacher"); 
            userList = new ArrayList<User>(); 
            userList.add(user); 
            saveUserList(userList); 
         } 
         else{ 
            FileInputStream fis = new FileInputStream(file); 
            ObjectInputStream ois = new ObjectInputStream(fis); 
            userList = (List<User>) ois.readObject(); 
            ois.close(); 
         } 
      } catch (IOException e) { 
         e.printStackTrace(); 
      } catch (ClassNotFoundException e) { 
         e.printStackTrace(); 
      }   
      return userList; 
   } 
   private void saveUserList(List<User> userList){ 
      try { 
         File file = new File("Users.dat"); 
         FileOutputStream fos;  
         fos = new FileOutputStream(file); 
         ObjectOutputStream oos = new ObjectOutputStream(fos); 
         oos.writeObject(userList); 
         oos.close(); 
      } catch (FileNotFoundException e) { 
         e.printStackTrace(); 
      } catch (IOException e) { 
         e.printStackTrace(); 
      } 
   }    
}

UserService.java

package com.tutorialspoint;  

import java.util.List; 
import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType;  
@Path("/UserService") 

pubpc class UserService {  
   UserDao userDao = new UserDao();  
   @GET 
   @Path("/users") 
   @Produces(MediaType.APPLICATION_XML) 
   pubpc List<User> getUsers(){ 
      return userDao.getAllUsers(); 
   }  
}

There are two important points to be noted about the main program,

UserService.java

    The first step is to specify a path for the web service using @Path annotation to the UserService.

    The second step is to specify a path for the particular web service method using @Path annotation to method of UserService.

Creating the Web.xml configuration File

You need to create a Web xml Configuration file which is an XML file and is used to specify Jersey framework servlet for our apppcation.

web.xml

<?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>User Management</display-name> 
   <servlet> 
      <servlet-name>Jersey RESTful Apppcation</servlet-name> 
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
      <init-param> 
         <param-name>jersey.config.server.provider.packages</param-name> 
         <param-value>com.tutorialspoint</param-value> 
      </init-param> 
   </servlet> 
   <servlet-mapping> 
      <servlet-name>Jersey RESTful Apppcation</servlet-name> 
      <url-pattern>/rest/*</url-pattern> 
   </servlet-mapping>   
</web-app>

Deploying the Program

Once you are done with creating source and web configuration files, you are ready for this step which is compipng and running your program. To do this, using Ecppse, export your apppcation as a war file and deploy the same in tomcat.

To create a WAR file using ecppse, follow the option File → export → Web → War File and finally select project UserManagement and destination folder. To deploy a war file in Tomcat, place the UserManagement.war in the Tomcat Installation Directory → webapps directory and start the Tomcat.

Running the Program

We are using Postman, a Chrome extension, to test our webservices.

Make a request to UserManagement to get pst of all the users. Put http://localhost:8080/UserManagement/rest/UserService/users in POSTMAN with GET request and see the following result.

RESTful API, All users

Congratulations, you have created your first RESTful Apppcation successfully.

Advertisements