Welcome to Restful Web Services Tutorial in Java. REST is the acronym for REpresentational State Transfer. REST is an architectural style for developing applications that can be accessed over the network. REST architectural style was brought in light by Roy Fielding in his doctoral thesis in 2000.
Restful Web Services is a stateless client-server architecture where web services are resources and can be identified by their URIs. REST Client applications can use HTTP GET/POST methods to invoke Restful web services. REST doesn’t specify any specific protocol to use, but in almost all cases it’s used over HTTP/HTTPS. When compared to SOAP web services, these are lightweight and doesn’t follow any standard. We can use XML, JSON, text or any other type of data for request and response.
Java API for RESTful Web Services (JAX-RS) is the Java API for creating REST web services. JAX-RS uses annotations to simplify the development and deployment of web services. JAX-RS is part of JDK, so you don’t need to include anything to use it’s annotations.
Some of the important JAX-RS annotations are:
@Path
: used to specify the relative path of class and methods. We can get the URI of a webservice by scanning the Path annotation value.@GET
, @PUT
, @POST
, @DELETE
and @HEAD
: used to specify the HTTP request type for a method.@Produces
, @Consumes
: used to specify the request and response types.@PathParam
: used to bind the method parameter to path value by parsing it.There are two major implementations of JAX-RS API.
Let’s see how easy to create Restful web service using Jersey and then RESTEasy. We will be exposing following methods over HTTP and use Chrome Postman extension to test these.
URI | HTTP Method | Description |
---|---|---|
/person/{id}/getDummy | GET | Returns a dummy person object |
/person/add | POST | Adds a person |
/person/{id}/delete | GET | Delete the person with ‘id’ in the URI |
/person/getAll | GET | Get all persons |
/person/{id}/get | GET | Get the person with ‘id’ in the URI |
Create a dynamic web project and then convert it to Maven to get the skeleton of your web services project. Below image shows the project structure of the final project. Let’s look at the Jersey dependencies we have in pom.xml file.
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JAXRS-Example</groupId>
<artifactId>JAXRS-Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
We are not required to add jersey-client dependencies but if you are writing java program to invoke a REST web service using Jersey then it’s required. Now let’s look at the deployment descriptor to learn how to configure Jersey to create our web application.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>JAXRS-Example</display-name>
<!-- Jersey Servlet configurations -->
<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.journaldev</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<!-- Jersey Servlet configurations -->
</web-app>
That’s all is required to plugin Jersey into our web application, in our java code we will be using JAX-RS annotations. Notice the value of init parameter com.sun.jersey.config.property.packages
to provide package that will be scanned for web service resources and methods.
First of all we will create two model beans - Person
for our application data and Response
for sending response to client systems. Since we will be sending XML response, the beans should be annotated with @XmlRootElement
, hence we have this class.
package com.journaldev.jaxrs.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement (name="person")
public class Person {
private String name;
private int age;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString(){
return id+"::"+name+"::"+age;
}
}
package com.journaldev.jaxrs.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Response {
private boolean status;
private String message;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Based on our URI structure, below is the service interface and it’s implementation code.
package com.journaldev.jaxrs.service;
import com.journaldev.jaxrs.model.Person;
import com.journaldev.jaxrs.model.Response;
public interface PersonService {
public Response addPerson(Person p);
public Response deletePerson(int id);
public Person getPerson(int id);
public Person[] getAllPersons();
}
package com.journaldev.jaxrs.service;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
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 com.journaldev.jaxrs.model.Person;
import com.journaldev.jaxrs.model.Response;
@Path("/person")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public class PersonServiceImpl implements PersonService {
private static Map<Integer,Person> persons = new HashMap<Integer,Person>();
@Override
@POST
@Path("/add")
public Response addPerson(Person p) {
Response response = new Response();
if(persons.get(p.getId()) != null){
response.setStatus(false);
response.setMessage("Person Already Exists");
return response;
}
persons.put(p.getId(), p);
response.setStatus(true);
response.setMessage("Person created successfully");
return response;
}
@Override
@GET
@Path("/{id}/delete")
public Response deletePerson(@PathParam("id") int id) {
Response response = new Response();
if(persons.get(id) == null){
response.setStatus(false);
response.setMessage("Person Doesn't Exists");
return response;
}
persons.remove(id);
response.setStatus(true);
response.setMessage("Person deleted successfully");
return response;
}
@Override
@GET
@Path("/{id}/get")
public Person getPerson(@PathParam("id") int id) {
return persons.get(id);
}
@GET
@Path("/{id}/getDummy")
public Person getDummyPerson(@PathParam("id") int id) {
Person p = new Person();
p.setAge(99);
p.setName("Dummy");
p.setId(id);
return p;
}
@Override
@GET
@Path("/getAll")
public Person[] getAllPersons() {
Set<Integer> ids = persons.keySet();
Person[] p = new Person[ids.size()];
int i=0;
for(Integer id : ids){
p[i] = persons.get(id);
i++;
}
return p;
}
}
Most of the code is self explanatory, spend some time to familiarize yourself with JAX-RS annotations @Path
, @PathParam
, @POST
, @GET
, @Consumes
and @Produces
.
That’s it. Our web service is ready, just export it as WAR file and put it inside Tomcat webapps directory or deploy into any other container of your choice. Below are some of the tests performed using Postman chrome extension for this web service. Note that we have to provide Accept and Content-Type values as “application/xml” in request header as shown in below image.
That’s all for creating web services using Jersey JAX-RS implementation. As you can see that most of the code is using JAX-RS annotations and Jersey is plugged in through deployment descriptor and dependencies.
We will use all the business logic developed in Jersey project, but rather than making changes to the same project, I have created a new project. Create a dynamic web project and convert it to Maven project. Then copy all the java classes - Person, Response, PersonService and PersonServiceImpl. Below is the final project after we are done with all the changes. Add below RESTEasy dependencies in pom.xml file.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>3.0.13.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>3.0.13.Final</version>
</dependency>
Below is the web.xml file where we are configuring Resteasy servlet.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>JAXRS-Example-RestEasy</display-name>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.journaldev.jaxrs.resteasy.app.MyApp</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Notice the init-param where are providing MyApp
class as value, here we are extending javax.ws.rs.core.Application
class as shown below.
package com.journaldev.jaxrs.resteasy.app;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.journaldev.jaxrs.service.PersonServiceImpl;
public class MyApp extends Application {
private Set<Object> singletons = new HashSet<Object>();
public MyApp() {
singletons.add(new PersonServiceImpl());
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
}
That’s it. Our web service is ready with RESTEasy JAX-RS implementation. Below are some of the output from Postman chrome extension test.
That’s all for Restful Web Services Tutorial, I hope you learned about JAX-RS annotations and understood the benefits of having standard API that helped us in reusing code and moving from Jersey to RESTEasy so easy.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Hello Pankaj, Could you please provide link to download source code? I don’t see it on this page. Please help. Regards, Savani
- Savani Fu
This is because most of the code is given and it’s simple. I would say create yourself for better learning.
- Pankaj
Hi your post method is NOT very clear to me , could you explain to me how will I invoke Add method I see it is a Http post But how will I invoke this path CANNOT be in browser , do you I need to create a separate Client with Main method ?
- S COULIBALY
Great article
- Houssamel-din
Great Article . Well Explained !!!
- Aparna
Hi Pankaj, Thanks for the great tutorial. I have one question. Am I right in thinking that, if there was an updatePesrson method, then the code would become non-thread safe. So in that case is it suggested to use ConcurrentHaspMap to store the data? What are your thoughts? Thank You.
- cs
Yes, but in most of the cases you will store data into Database where you can set auto commit false and use transaction management.
- Pankaj
Hi, I’m having problem with Maven, while creating maven project getting an error for pom.xml file like ( Cannot read lifecycle mapping metadata for artifact org.apache.maven.plugins:maven-clean-plugin:maven-plugin:2.5:runtime Cause: error in opening zip file pom.xml ) but in my system i have done proper installation for maven. I tried many ways to clear this error still no use please suggest me how can I clear this.
- Tejaswini K
Check your internet connection as Maven needs to download artifacts. Also, make sure your settings.xml is correct.
- Sunil
I pasted war file in webapps directory and restarted server, but i get 404. Plz suggest pankaj sir
- Tejas Gowda
What is the WAR file name and the unzipped directory created? Usually in Tomcat that is the context of the webapp. So if WAR file name is “abc.war” and folder got created is “abc” then try to access the webapp at
localhost:8080/abc
for homepage.- Pankaj
I am also having the same problem. Still getting 404 error.
- Krishnam Raju
I faced the same issue and I was able to get it working you may not be able to access through browser using webApp name as contextRoot, mostly I believe due to no welcome servlet defined. However you provide the webApp(war file name) in postman requests instead of display name in web.xml postman request should look like below to work for you https://localhost:8080/abc/person/add (assuming your war file is abc, it does not work with the defined in web.xml) hope this helps
- Krishna
https://stackoverflow.com/questions/46863773/jersey-client-maintain-state-cookies-sends-get-post-set-cookiesget-2nd 0 down vote favorite In Jersey Client, I want to maintain Cookies and using Cookies want to send GET requests second time, to fetch JSON data. Why is Set-cookies used? Do I need to maintain State or cookies? import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; public class ExampleRestAPIClient { public static void main(String[] args) { Client client = ClientBuilder.newClient(); WebTarget baseTarget = client.target(“https://shoaibapi.erpnext.com/api/method/login”); MultivaluedMap formData = new MultivaluedHashMap(); formData.add(“usr”, “shoaibshaikh1516@gmail.com”); f ormData.add(“pwd”, “qweqwe”); Response response = baseTarget.request().post(Entity.form(formData)); System.out.println(“\n postResponse which is send\n”); System.out.println(response); if (response.getStatus() != 201) { System.out.println(“Error”); } String createdMessage = response.readEntity(String.class); System.out.println(createdMessage); System.out.println(“\n\n”); System.out.println(response.getCookies()); } }
- myjaysan myjaysan
To delete resource, use @DELETE annotation, but here @GET annoatation is used. Please explain.
- Supriya
You can use @DELETE also, ideally you should.
- Pankaj
Hi, I have some trouble understanding how client-server applications work with REST. Have I understood it correctly that this example is the server side code? How would the client side code look? Is it just code for making a GET request and parsing the response (doing whatever you want done with it)? I would be very thankful for a response, I am a bit confused by how I would develop a client-server application with REST and any clarifications would be really appreciated!
- Charlotte
Yes, you are right. Client will make HTTP calls to server (GET, POST etc.) and receive response. It can be plain HTML, XML, JSON etc. Client is free to do whatever with it.
- Pankaj
Hi. I am having problem with this error in EasyRest. “java.lang.ClassNotFoundException: org.jboss.resteasy.plugins.server.servlet.HttpServletDistpatcher from [Module “deployment.JAXRS-Example-RestEasy-0.0.1-SNAPSHOT.war:main” from Service Module Loader]”. Can you help me?. Thanks.
- Daniel
I am unable to run the application.
- Krishnam Raju
in case of add where to put value for name,id,age i m getting nyll pointer exception
- Randhir
Hello Pankaj ! Your website is great . Thanks for the amazing work you have put in. For REST though I think having verbs in the @Path is not a good programming practice. For e.g. here - /person/add . The POST/PUT/GET/DELETE are the verbs that tell you what has to be done. They should not be part of the URI. I think adding a tutorial on best practices for REST will clarify & fix these naive mistakes ! Thanks
- Rupam Singh
Yes, I agree with your point, when I wrote the tutorial my aim was to create REST web services with least complexities so that a new user can easily understand and get started with it. I will write a tutorial on best practices for REST in a while.
- Pankaj
How come on getAll request we get …? I don’t get from where it comes?
- Next
Hi, I just started my first software developer position and i’ve got to tell you - this tutorial really cleared up some ambiguity around a current project that was assigned to me . I had never seen or touched any kind of web services in Java. Reading this simple yet effective tutorial helped me better understand the structure of REST services using Java. - Carlos Herrera
- Carlos Herrera
Thank you for writing this tutorial. Its very easy to understand.
- Kamalakar
What changes to make for getting JSON instead of XML in this project
- Raashid
Nice article, presize ,brief,overview of rest. Best for my kind of people who would first need to know overall flow,not like Spaghetti code and give up.
- Navin
While deploying the same application into Tomcat, I am getting the below error in server console. Kindly help me. Dec 13, 2018 9:12:40 AM org.apache.catalina.core.ContainerBase startInternal SEVERE: A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/RestfulWebService]] at java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.util.concurrent.FutureTask.get(FutureTask.java:192) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748)
- Srikant Das
Hello Pankaj, Could you pease suggest the solution for above issue. I am using java 8 and and tomcat 8 to run the application. Thanks, Srikant
- Srikant Das
I am not sure of the issue you are facing, it doesn’t seem to be related to the app. How are you generating the WAR file? Please generate using maven build and deploy it explicitly.
- Pankaj
u have to use tomcat 9 for java8
- pavani
Hi. I am having problem with this error in EasyRest. “java.lang.ClassNotFoundException: org.jboss.resteasy.plugins.server.servlet.HttpServletDistpatcher from [Module “deployment.JAXRS-Example-RestEasy-0.0.1-SNAPSHOT.war:main” from Service Module Loader]”. Can you help me?. Thanks.
- Daniel
I am unable to run the application.
- Krishnam Raju
in case of add where to put value for name,id,age i m getting nyll pointer exception
- Randhir
Hello Pankaj ! Your website is great . Thanks for the amazing work you have put in. For REST though I think having verbs in the @Path is not a good programming practice. For e.g. here - /person/add . The POST/PUT/GET/DELETE are the verbs that tell you what has to be done. They should not be part of the URI. I think adding a tutorial on best practices for REST will clarify & fix these naive mistakes ! Thanks
- Rupam Singh
Yes, I agree with your point, when I wrote the tutorial my aim was to create REST web services with least complexities so that a new user can easily understand and get started with it. I will write a tutorial on best practices for REST in a while.
- Pankaj
How come on getAll request we get …? I don’t get from where it comes?
- Next
Hi, I just started my first software developer position and i’ve got to tell you - this tutorial really cleared up some ambiguity around a current project that was assigned to me . I had never seen or touched any kind of web services in Java. Reading this simple yet effective tutorial helped me better understand the structure of REST services using Java. - Carlos Herrera
- Carlos Herrera
Thank you for writing this tutorial. Its very easy to understand.
- Kamalakar
What changes to make for getting JSON instead of XML in this project
- Raashid
Nice article, presize ,brief,overview of rest. Best for my kind of people who would first need to know overall flow,not like Spaghetti code and give up.
- Navin
While deploying the same application into Tomcat, I am getting the below error in server console. Kindly help me. Dec 13, 2018 9:12:40 AM org.apache.catalina.core.ContainerBase startInternal SEVERE: A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/RestfulWebService]] at java.util.concurrent.FutureTask.report(FutureTask.java:122) at java.util.concurrent.FutureTask.get(FutureTask.java:192) at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:943) at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:871) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748)
- Srikant Das
Hello Pankaj, Could you pease suggest the solution for above issue. I am using java 8 and and tomcat 8 to run the application. Thanks, Srikant
- Srikant Das
I am not sure of the issue you are facing, it doesn’t seem to be related to the app. How are you generating the WAR file? Please generate using maven build and deploy it explicitly.
- Pankaj
u have to use tomcat 9 for java8
- pavani
Hi Pankaj , Thanks for the tutorial very well explained . I have one question , when we hit getAll resource , then in response we are getting the collection of Person , but from where the root element is coming ?
- Indranil Goswami
Even I have same doubt… Where is the root element people coming from???
- Gayatri
I think the root element comes as default from the REST API, how i found out is i changed the @XmlRootElement (name=“person”) of person class to @XmlRootElement (name=“Employee”). Still we get the root element of this Employee element as (collection of person objects) only.
- Raviraj
People root element
- Raviraj
Thank you for the tutorial. Initially I got an error related to permissions on Tomcat folder. Providing write permissions solved it
- anupama
I’m new to rest full and weblogic server. Can you please guide me how to deploy in weblogic 11gR1. I’m getting error 404,
- Ramakrishna
I copied your files as it is, however I am getting below error when I am trying to start server. I am using Tomcat 8.5 and Java 11. . . . INFO: Scanning for root resource and provider classes in the packages: com.journaldev Jul 23, 2019 3:39:02 PM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable java.lang.IllegalArgumentException at jersey.repackaged.org.objectweb.asm.ClassReader.(ClassReader.java:170) at jersey.repackaged.org.objectweb.asm.ClassReader.(ClassReader.java:153) at jersey.repackaged.org.objectweb.asm.ClassReader.(ClassReader.java:424) at com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess(AnnotationScannerListener.java:138) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner$1.f(FileSchemeScanner.java:86) at com.sun.jersey.core.util.Closing.f(Closing.java:71) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:83) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:80) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:80) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scan(FileSchemeScanner.java:71) at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(PackageNamesScanner.java:226) at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(PackageNamesScanner.java:142) at com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:80) at com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104) at com.sun.jersey.api.core.PackagesResourceConfig.(PackagesResourceConfig.java:78) at com.sun.jersey.api.core.PackagesResourceConfig.(PackagesResourceConfig.java:89) at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:696) at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:674) at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:205) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1132) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1079) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:973) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4885) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5199) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) Jul 23, 2019 3:39:02 PM org.apache.catalina.core.StandardContext loadOnStartup SEVERE: Servlet [Jersey REST Service] in web application [/JournaldevWebservice] threw load() exception java.lang.IllegalArgumentException at jersey.repackaged.org.objectweb.asm.ClassReader.(ClassReader.java:170) at jersey.repackaged.org.objectweb.asm.ClassReader.(ClassReader.java:153) at jersey.repackaged.org.objectweb.asm.ClassReader.(ClassReader.java:424) at com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess(AnnotationScannerListener.java:138) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner$1.f(FileSchemeScanner.java:86) at com.sun.jersey.core.util.Closing.f(Closing.java:71) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:83) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:80) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scanDirectory(FileSchemeScanner.java:80) at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner.scan(FileSchemeScanner.java:71) at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(PackageNamesScanner.java:226) at com.sun.jersey.core.spi.scanning.PackageNamesScanner.scan(PackageNamesScanner.java:142) at com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:80) at com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104) at com.sun.jersey.api.core.PackagesResourceConfig.(PackagesResourceConfig.java:78) at com.sun.jersey.api.core.PackagesResourceConfig.(PackagesResourceConfig.java:89) at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:696) at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:674) at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:205) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:394) at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:577) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1132) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1079) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:973) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4885) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5199) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) Any idea, what is wrong here?
- Subhash
Great article. One correction. In Response class, we need to add the following to avoid error. @Produces (MediaType.APPLICATION_XML) @XmlRootElement (name = “response”)
- Venky
Excellent example, much appreciated.
- Dallas Jones
RESTFUL with XML as response?
- dannegm
How to run this project in eclipse?
- XAA
HI Pankaj, I am getting 400-Bad Request Error with the same request that you have made. Please help!
- harshwardhan sharma
We need add: javax.xml.bind jaxb-api 2.3.1 No? If no, @XmlRootElement has error. I ask.
- Javier Benito
Hello Pankaj Sir…Please tell me how to implement rest web services in netbeans and test in postmen tool?
- SUSHMITA MHATRE
Hello Pankaj, I tried to test your code unfortunately I received the error 500 as below. i am using netbeans somewhere i read that the date i jar was not loaded can you tell me what to do thanks in advance HTTP Status 500 - Internal Server Error type Exception report messageInternal Server Error descriptionThe server encountered an internal error that prevented it from fulfilling this request. exception java.lang.AbstractMethodError: javax.ws.rs.core.Response$ResponseBuilder.status(ILjava/lang/String;)Ljavax/ws/rs/core/Response$ResponseBuilder; note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 5.1.0 logs. GlassFish Server Open Source Edition 5.1.0
- Heni