RESTful Java Web Services with NetBeans, Jersey and Tomcat

restful-area-225x225Although Eclipse is commonly used for Java web service programming, it can be challenging to configure and use for testing. Luckily Eclipse is not the only IDE game in town.

NetBeans provides a rich environment for developing Java web services with Jersey – the reference implementation of JAX-RS RESTful web services. This article will explain how to create a simple RESTful service and test it with the Apache Tomcat Server from the NetBeans IDE.

 

RESTful Web Services

What is REST?

Representational State Transfer or REST refers to a design model for distributed systems that was originally described by Roy Fielding, one of the authors of the HTTP protocol versions 1.0 and 1.1.

REST involves the transfer of resources between clients and servers. Resources are typically documents that convey information about the state of each resource. The contents of these documents are largely up to the system designer(s) while the document formats are usually one or more simple MIME types, commonly text/plain, text/html, application/json, application/xml or application/x-www-form-urlencoded.

There are no hard and fast rules about what resources are exchanged between clients and servers. In this sense RESTful web services can be considered lightweight in comparison to SOAP which has a rigid and complex messaging specification.

HTTP Service Requests

RESTful web services are implemented using one or more of the following four HTTP request types depending on the design of the system. These services loosely map to the so-called CRUD operations: Create, Retrieve, Update and Delete.

  • PUT – Creates a resource on the server. The resource is contained in the body of the POST request. PUT is analogous to an SQL insert statement.
  • GET – Retrieves a resource from the server. The resource is specified with a URL and may include a ? to delineate the request from the request parameters. GET is analogous to an SQL select statement.
  • POST –  Updates a resource on the server. The resource is contained in the body of the POST request. POST is analogous to an SQL update statement.
  • DELETE – Deletes a resource on the server. The resource is specified in the URL only. DELETE is analogous to an SQL delete command.

Note that there is a lack of consensus in the literature about the roles of PUT and POST with regard to REST implementations. This blog – A Beginner’s Guide to HTTP and REST – indicates that PUT can be use to create and update resources and that PUT and POST are more or less interchangeable. Many systems use POST for both creation and update, due in part to the fact that browsers generally do not support PUT requests.

I have generally taken taken this latter route, to overload POST to handle resources creation and update.

Installation

If you don’t already have Tomcat and NetBeans configured to work together, read these sections to learn how to test your web services with a Tomcat server.

Tomcat

  1. Download and install Apache Tomcat version 7.x.  Note the version used in this article is 7.0.32.
  2. Now you need to set up a Tomcat admin user that will have all the privileges to run the Tomcat management system. You will add a user named tomcat with password tomcat to do this. Open the apache-tomcat-7.0.32/conf/tomcat-users.xml file.
  3. Comment out all the lines in the file and replace them the following lines:
<xml version="1.0" encoding="UTF-8">
<tomcat-users>
  <role rolename="tomcat"/>
  <user username="tomcat" password="tomcat" roles="manager-script,manager-gui"/>
</tomcat-users>
  1. You can start and stop your Tomcat server with these commands
apache-tomcat-7.0.32/bin/startup.sh
apache-tomcat-7.0.32/bin/shutdown.sh
  1. Test your Tomcat server by opening http://localhost:8080 in your browser. You should get a screen that looks like this:

tomcat running

NetBeans

  1. Download and install the Java EE version of NetBeans. The version used for this blog was 7.2. Note that for the Mac you’ll get a DMG package and for Linux you’ll get an installation script.
  2. For web application testing, NetBeans uses the Glassfish web server by default. To use Tomcat instead, click on the Services tab.  If you don’t see this tab, select Window > Services to get the tab to appear.
  3. Right click on the Servers item and select Add Server.

Add Server

  1. Select Apache Tomcat in the list of servers.
  2. Set the name of the server to Apache Tomcat 7+ then click Next.

Apache Tomcat

  1. Click on Browse in the Add Server Instance screen to set the server location.

Installation and Login Details blank

  1.  Select the folder where you installed Apache Tomcat then click Open.

Open Tomcat

  1. Set the Tomcat user name to tomcat and the password to tomcat then click on FinishApache Tomcat will now be one of the servers you can select when you test your web service later.  Your Apache Tomcat server settings should looks like this:

Installation and Login Details Tomcat

Create a NetBeans Web Application Project

After configuring the development environment, you first need to build a base web application to which you will add a RESTful services class and methods later.

  1. Select File > Open > New Project…
  2. Select the Java Web category and Web Application project, then click Next

Choose Project

  1. Enter the project name as GetSomeRest and set the directory location of the project, then click Next.

Name and Location

  1. In the Server and Settings screen, select  Apache Tomcat 7+ in the Server field, then click Next.

Server and Settings

  1. We will not add any additional application frameworks, so click Finish in the Frameworks screen (not shown).
  2. You now have a simple web application that will load the index.jsp page and display the message “Hello World!” in your default browser. To run the application, click on the green triangle under the NetBeans menu bar, select Run > Project from the menu bar or press F6.

Create RESTful Web Services

GET Service Handler

Now that we have a basic web application, we will add a RESTful service that responds to an HTTP GET request.

  1. Right click on GetSomeRest in the Projects.
  2. Select New… then select RESTful Web Services from Patterns…

New REST Service

  1. Select the Simple Root Resource in the Select Pattern screen, then click Next.

Select Pattern

  1. Next you will specify the service method and service resource class. In the Specify Resource screen set the name of the Java package that will contain your service class. The name can be anything, but it is usually a domain name in reverse order. In this example we’ll use com.vichargrave.
  2. Set the service Path to service and the service Class name to ServiceResource.
  3. The MIME type refers to the format of the messages that will be sent to and returned by our webservice.  Set this to text/html for the simple GET service. In the next section I’ll explain how to set other MIME types with Jersey annotations.
  4. Click on the Use Jersey specific features then click on Finish. NetBeans will then generate the ServiceResource class that will contain two methods, getHTML() and putHTML() to handle GET and PUT requests respectively.

Specify Resource Class

  1. Although we specified we wanted Jersey features added in the previous step, NetBeans versions prior to 7.3 do not seem to add the Jersey library automatically. To add Jersey explicitly, right click on the Libraries item in your Projects tab and the select Add Library…
  2. Select Jersey 1.8 (JAX-RS RI) then click on Add Library.

Add Library

  1. You will now see a section in your project called RESTful Web Services.  If you open this section you can see the service class with GET and PUT handler methods methods that have been created.  Replace the contents of the getHtml() with the return statement as shown below.  Note that the content type of the return string is specified by the @Produces("text/html") Jersey annotation.
package com.vichargrave;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;

@Path("service")
public class ServiceResource {

    @Context
    private UriInfo context;

    public ServiceResource() {
    }

    @GET
    @Produces("text/html")
    public String getHtml() {
        return "<h1>Get some REST!<\h1>";
    }

    @PUT
    @Consumes("text/html")
    public void putHtml(String content) {
    }
}
  1. Now we need to set the path to the web service so it will be automatically invoked when we test it with the default browser. Right click on the GetSomeRest project then select Properties.
  2. When we test the web service the URL to the GET service will be http://localhost:8080/GetSomeRest/webresources/service. The GetSomeRest part is defined in the path attribute in the context.xml file which you can find in the configuration files of the project. The webresources part is defined in the <url-pattern> field of the web.xml. The service part is defined by the @Path annotation in the ServiceResource class definition. Enter /webresources/service in the Relative URL field then click OK.

Set resource path

  1. To test your web service, click on the green triangle under the NetBeans menu bar, select Run > Project from the menu bar or press F6. You will see the message Get some REST! displayed in your default browser.

POST Service Handler

Most web services have a POST handler so let’s add one now.  The handler will accept urlencoded text from a REST client which is specified with the @Consumes("application/x-www-form-urlencoded") Jersey annotation.  In this case the POST handler will simply return the decoded plain text to the client which is specified with the @Produces("text/plain") Jersey annotation.

  1. Add the following import statement to the list of imports.
import javax.ws.rs.POST;
  1. Add the following code to the ServiceResource class. The @Consumes annotation specifies that the POST handler accepts requests containing URL encoded data. The Content-Type of the POST request much match the @Consumes type or else the POST handler will not get called. The @Produces annotation specifies that the POST handler will return ordinary text.
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("text/plain")
public String postHandler(String content) {
    return content;
}
  1. If your server is still running from previous testing, NetBeans will automatically deploy the service in your test environment and restart Tomcat.  Otherwise run the project again.
  2. You can test the web service by sending it a file from your system with the curl command as follows.
curl http://localhost:8080/GetSomeRest/webresources/service --data "Hello World!"
  1. The POST handler should return Hello World! to curl.

Web Service Deployment

Now that you have a working RESTful web service with GET and POST handlers, you’ll want to deploy the service to your target Tomcat server. NetBeans packages all the web service code into a WAR package.  In the case of this project the package will be called GetSomeRest.war. You can deploy this package to the target Tomcat server as follows:

  1. Open the Tomcat main page in your browser,
  2. Click on the Manager button.  You will most likely have to login with the administrator credentials.
  3. Scroll down to the WAR file to deploy.
  4. Click on the Choose file button.
  5. Navigate to your NetBeansProjects/GetSomeRest/dist directory and select GetSomeRest.war.
  6. Click on Deploy. In the Path column under Applications you should see /GetSomeRest.
  7. Run the curl command from the previous section with the host/IP and port for your target Tomcat to make sure the service is working.

Jersey Web Service Annotations

Jersey provides a set of Java annotations that can be used to define the web service structure. So far we have already used these annotations in the example GET service:

  • @Path – Defines the URL relative path to the given resource. We saw in the previous section that the complete URL to our service was defined by fields in the context.xml and web.xml files plus the @Path field. You can change the relative path of any service by modifying these three fields. For example if you wanted to simplify the GET service URL to be http://localhost:8080/GetSomeRest/service you would set the <url-pattern> field in web.xml to “/*”.
  • @Context – Defines parameters that can be extracted from the request.
  • @GET – Identifes the method in the service class that will handle GET requests.
  • @Produces – Specifies the MIME type of the response that is returned to the client.
  • @Consumes – Specifies the content type that the service will accept as input.

Some other important annotations that you’ll want to know about include:

  • @PUT – Identifies the method that will handle PUT requests.
  • @DELETE – Identifies the method that will handle DELETE requests.
  • @Consumes – Specifies the MIME type that the method immediately following the annotation will accept from the client. It is possible to define multiple MIME types that will each be handled by a separate method. The GET service example does not have any arguments so the @Consumes annotation was not needed. If we wanted to add a string parameter to the GET service the code for the getHTML() method would look something like this:
@GET
@Consumes("text/plain")
@Produces("text/html")
public String getHtml(String message) {
    return "<h1>The browser sent this message "+message+"</h1>";
}
  • @QueryParam – Denotes a field that will be extracted from the URL in a GET request after the ? character. Here is an example taken from the Jersey documentation website. For a URL request of this form:
http://<server>:8080/<path>/smooth?step=<value>&min-m=<value>&...

     The handler method would look like this:

@Path("smooth")
@GET
public Response smooth(
@DefaultValue("2") @QueryParam("step") int step,
@DefaultValue("true") @QueryParam("min-m") boolean hasMin,
@DefaultValue("true") @QueryParam("max-m") boolean hasMax,
@DefaultValue("true") @QueryParam("last-m") boolean hasLast,           
@DefaultValue("blue") @QueryParam("min-color") ColorParam minColor,
@DefaultValue("green") @QueryParam("max-color") ColorParam maxColor,
@DefaultValue("red") @QueryParam("last-color") ColorParam lastColor
) { ... }
  • @DefaultValue – Denotes the value that will be used to fill a variable in a @QueryParam list that is missing.
  • @PathParam – Denotes a field that will be extracted from a field in the URL path. Here is an example taken from the Jersey documentation website:
@GET
@Path("/images/{image}")
@Produces("image/*")
public Response getImage(@PathParam("image") String image) {
  if (!isSafeToOpenFile(image)) {
    throw new IllegalArgumentException("Cannot open the image file.");
  }

  File f = new File(image);

  if (!f.exists()) {
    throw new WebApplicationException(404);
  }

  String mt = new MimetypesFileTypeMap().getContentType(f);
  return Response.ok(f, mt).build();
}

Test the Web Service

You can get the source code for the GetSomeRest project from GitHub – https://github.com/vichargrave/getsomerest. When get the code check out the jersey-1.8 branch, then open the project in Netbeans and run it with Tomcat according to the directions in this blog.

Additional Information

The intent of this blog is to get you started with RESTful web services in NetBeans. To keep things simple I’ve left out some important aspects of web service development not the least of which includes processing POST and PUT request bodies. For more information on writing more complex RESTful web services you can check out these resources:

Author:

Article by Vic Hargrave

Software developer, blogger and family man enjoying life one cup of coffee at a time. I like programming and writing articles on tech topics. And yeah, I like coffee.

92 Comments


  1. Pingback: Sarah's Daily Note
    1. Thank you Carlos for the kind words and visiting my website. I’m also learning more about web services and find writing articles like this helpful in my leraning process.

  2. I am basically not a programmer and I am comparatively new to Java technology , so I was wondering what all topics should be covered up if i have to start java from the start and has any one studied or got any info regarding this 6 week java training online course wiziq.com and should we also have knowledge of C language before we further move on to Advance Java topics??

    1. Hi Sumit. I have no experience with the wiziq.com course so can’t recommend one way or another. I do know that if you are starting out with programming a good formal course on one of the major programming languages – C, C++, Java, Python, PHP, Perl – would help you get started more quickly. Since Java is essentially a C/C++ derived language they share a lot syntactically. If Java is what you want I’d jump right in with that, but at some point you should probably take a C++ course as well.

      I hope this helps. Thanks for visiting and commenting on my site.

  3. thanx…please guide me where i will insert my project source code???…..kindly ans please i will be very thankful to you:)

    1. You place your GET request code in the following method that is produced for you by NetBeans:

      @GET
      @Produces(“text/html”)
      public String getHtml() {
      String htmlString;
      // Place additional code here to build your HTML reply
      return htmlString;
      }

      Likewise for your POST method you will have something like this:

      @POST
      @Consumes(“text/html”)
      public void postHtml(String content) {
      // put your POST code here
      }

      I hope this helps.

  4. i want to insert my project which consist of many classes and database….where i will insert them….kindly guide me….thnx for your help:)

  5. Pingback: TinyCC
  6. Hi ,

    Thanks for the post.
    I have a question:
    Below is the code which I am trying to execute.
    import javax.ws.rs.Consumes;
    import javax.ws.rs.GET;
    import javax.ws.rs.POST;
    import javax.ws.rs.PUT;
    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 javax.ws.rs.QueryParam;
    import com.rest.jersey.webservice.util.JsonUtil;
    import com.rest.jersey.webservice.db.DBConnection;
    import org.codehaus.jettison.json.JSONArray;

    /**
    * This is the web service class which handles the request which contains “/uers” in the URL.
    * Even if you not put “/” after the “user”, it handles the request after the path as well.
    * In @Path(“/user”) or @Path(“/user/”) gives the same result.
    * E.g. – “/status/str” or “/status/resp”.
    * For Tomcat @Path(“/user/*”) is not working.
    * */
    @Path(“/user/”)
    public class UserDefinition {

    @Path(“/add”)
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public String insertDataForPostMethod(){
    String msg = “”;
    try {

    System.out.println(“POST method working fine.”);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally {

    }
    return msg = “Success”;
    }

    }

    URL: http://localhost:8080/RestfulWebService/api/user/add

    But still I am not able to execute it and it shows me 405 error message.

    Can you please help to find out what exactly I am missing here.

    ARM

    1. Just off the top of my head, I think your problem is that you don’t have a @Consumes statement. For POST requests in particular you are going to need one. I’d suggest at least: @Consumes(“application/x-www-form-urlencoded”) so it is compatible with the curl command. But you may need to specify additional content types based on the REST client you are using.

      1. Hi Vic,

        This application is my test application, I am not using any UI for this. Just create a URL and hit it on browser. I have tried all the options i.e @Consume and all but not able to get any success. 🙁
        @Get working fine for me but for the @Post it not working, dont know why..

        1. Your problem is the browser is not sending a POST request because you are not submitting a form. Here’s what you do to be able to get your service to work:

          1. Add @Consumes(“application/x-www-form-urlencoded”) to your POST handler.
          2. Add a string argument to your POST handler method, like this – String insertDataForPostMethod(String request).
          3. Make sure the url-pattern in the servlet-mapping section of your web.xml is set to: /api/*.
          4. Make sure your sure your context.xml path is set to: /RestfulWebService
          5. Start Tomcat then send a request to your server with curl, like this:
          curl http://localhost:8080/RestfulWebService/api/user/add –data-binary@

          That should work. Alternatively you might want to start from scratch by setting up your project according to the blog instructions then modifying it in place.

          I hope this helps.

  7. Hey Vic! Really great tutorial. Thank you so much!
    this is my problem
    HTTP Status 404 – /RestWebService1/webresources/service
    what should I do

  8. An impressive share! I’ve just forwarded this onto a colleague who has been conducting a little research on this. And he in fact bought me lunch simply because I stumbled upon it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanks for spending some time to talk about this issue here on your web page.

  9. Hi Vick ,
    Good Day!

    Its a very nice article. Here i have one question like how to enable the security related aspects in the restfull webservices. Can you please provide some info on this if possible.

    Thnaks in advance……

  10. Is it just my setup, because I get a ‘404’ error and a lot of text.

    If I try to run this as a Tomcat application (where I find it has automatically installed), I get a ‘Hello World’ screen.

    I can’t find the Hello World program either. What is wrong here? How do I test that the setup is correct, as I have tried the tutorial four times, without success?

      1. No it does not.

        I did pull the entire Netbeans project from GitHub, and loaded it as is.
        The result is 404 – The request resource is not available.

        Several attempts at tweaking it led to the same results!

        Netbeans V8, Tomcat V8, Jersey V2.5 on Mac Pro.

        1. I added a branch for Jersey 2.5. Here is how you get it.

          1. Remove the getsomerest directory you have.
          2. git clone git@github.com:vichargrave/getsomerest.git
          3. git checkout jersey-2.5
          4. Open the project in NetBeans 8
          5. Right click on the GetSomeRest project then select Run.

          You should be good to go.

    1. You have to send the URL you indicated in with the curl command like this:

      curl http://localhost:8080/GetSomeRest/webresources/service –data “Hello World!”

      Note this assumes you are running the curl command on the same system as the web service. If you run curl on another system, then substitute the “localhost” with the IP address or host name of the system on which your web service is running.

      I hope this helps.

      1. I’m sorry again. I am impractical
        when you say: send the command curl, what do you mean exactly?

        can I call the service directly in my browser?

        thank you for your help!

      2. RESTful requests cannot be done in a browser unless you write a form for a POST request or structure the query properly. I’m assuming you are using a Linux or MacOS system. If so there should be a command called “curl” that run as I instructed in my blog and in my last reply. Just type the following command to learn more about “curl”:

        man curl

        Basically it is a multipurpose HTTP client that can send any kind of request.

        If you don’t have “curl” then try these commands to try to download and install it:

        On CentOS or Redhat type – yum install curl -y
        On a Debian Linux type – apt-get install curl

        You’ll have to be logged in as “root” to use these commands. BTW, if you have a Mac you’ll already have curl.

  11. Thank you so much. I’ve been trying to follow half a dozen other tutorials for the past few days and this is the only one that worked or I could understand all the way through. Excellent tutorial.

    Very nice!

    One thing: Step 10. closing h1 element should have a forward slash not a backslash.

  12. Hi Vic,

    I have the code like this:

    package com.nizar.rest;

    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;

    @Path(“/hello”)
    public class HelloRest {

    @GET
    @Path(“/get”)
    @Produces(“text/plain”)
    public String getHello()
    {
    return “Hello, Nizar”;
    }
    }

    and my web.xml like this:

    RESTHello

    ServletAdaptor
    com.sun.jersey.spi.container.servlet.ServletContainer

    com.sun.jersey.config.property.packages
    com.nizar.rest

    1

    ServletAdaptor
    /*

    but when i hit from the browser:http://localhost:9999/RESTHello/hello/get

    i got an error, no resource available. Please i really need the solution for this problem. I have work around for 3 days and not found the solution.

  13. Sorry for incorrect type for web.xml, here is the web.xml:

    RESTHello

    ServletAdaptor
    com.sun.jersey.spi.container.servlet.ServletContainer

    com.sun.jersey.config.property.packages
    com.nizar.rest

    1

    ServletAdaptor
    /*

  14. This is a great post. I have been trying to follow a number of netbeans/tomcat tutorials. All I wanted was a simple learning exercise where I could see how/where I specify an URL in my java code and get it to respond via a web browser. Thanks for making it so easy to follow.

  15. Hi, Vic.

    Really nice article.

    I already success to test your code on my laptop, but when i try to deploy this app to server on jelastic i got this message :

    “The requested resource is not available.”

    FYI, when i check lib folder, all jersey reference is empty. Is it cause of problem. If yes, how to include these library when deploy the application’

    Regards
    Moudy

    1. I’m not familiar with how jelastic works. However, to make sure you have loaded the Jersey library do the following:

      1. Click on the Projects tab in NetBeans.
      2. Right click on your web services project.
      3. Select Libraries.
      4. Click on the Add Library button.
      5. Select the Jersey framework in the list of Glbal Libraries.
      6. Click OK.

      That should do it if Jersey is installed on your system.

  16. 403 Access Denied

    You are not authorized to view this page.

    If you have already configured the Manager application to allow access and you have used your browsers back button, used a saved book-mark or similar then you may have triggered the cross-site request forgery (CSRF) protection that has been enabled for the HTML interface of the Manager application. You will need to reset this protection by returning to the main Manager page. Once you return to this page, you will be able to continue using the Manager appliction’s HTML interface normally. If you continue to see this access denied message, check that you have the necessary permissions to access this application.

    If you have not changed any configuration files, please examine the file conf/tomcat-users.xml in your installation. That file must contain the credentials to let you use this webapp.

    For example, to add the manager-gui role to a user named tomcat with a password of s3cret, add the following to the config file listed above.

    Note that for Tomcat 7 onwards, the roles required to use the manager application were changed from the single manager role to the following four roles. You will need to assign the role(s) required for the functionality you wish to access.

    manager-gui – allows access to the HTML GUI and the status pages
    manager-script – allows access to the text interface and the status pages
    manager-jmx – allows access to the JMX proxy and the status pages
    manager-status – allows access to the status pages only
    The HTML interface is protected against CSRF but the text and JMX interfaces are not. To maintain the CSRF protection:

    Users with the manager-gui role should not be granted either the manager-script or manager-jmx roles.
    If the text or jmx interfaces are accessed through a browser (e.g. for testing since these interfaces are intended for tools not humans) then the browser must be closed afterwards to terminate the session.
    For more information – please see the Manager App HOW-TO.

    ..please help idont know what to do.. thanks in advance..:)

    1. You have not modified the tomcat-users.xml according to step 3 in the Tomcat section of the blog. You must replace the contents of this file with the following xml:





      Then restart Tomcat and you’ll be in business.

  17. Excellent!! I just one problem when I try to run the example I get the error
    404
    type Status report
    message /GetSomeRest/webresources/service
    description The requested resource is not available.

    I check twice the path and I have everything as example. I am a newbie with this
    Tomcat run, the class is fine , any cluees ?

    1. Are you using NetBeans 7.4? If so, the project set up is a little different. I’m writing a blog on this, but if you let me know that is the case, I’ll let you know how to fix the problem.

    1. The version used in the blog is NetBeans 7.3. If you download version 7.4, the RESTful service configuration is slightly different due to the fact that 7.4 comes with Jersey 2.x, whereas 7.3 used Jersey 1.x. I’m working on a new blog that addresses this difference.

        1. Unfortunately I have no knowledge of SOAP programming for any platform. I’m purely a REST kind of guy. You should be able to find something ig you do a Google search.

  18. Hi,

    Very nice article. As I noticed above, you mentioned that you will be writing an article related to security aspects in a restful webservice. Can you please provide some info on this if possible?

  19. Hi Vic. Thanks for sharing.
    Just an observation.
    I recently update to netbeans 8.0 and run into troubles creating restul from patern (with the old versione of jersey 1.8 it works perfectly). I create a new restful from pater that produce/consume json. When I run the project an MessageBodyProviderNotFoundException was throw. This becouse in the ApplicationConfig I miss jsonProvide so after adding, all works perfectly. I lost a lot of time finding the solution so I leave this comment for someone that had the same problem.
    The complete code for the ApplicationConfig class.

    import java.util.Set;
    import javax.ws.rs.core.Application;

    @javax.ws.rs.ApplicationPath("webresources")
    public class ApplicationConfig extends Application {

    @Override
    public Set<Class> getClasses() {
    Set<Class> resources = new java.util.HashSet();
    // following code can be used to customize Jersey 2.0 JSON provider:
    try {
    Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
    // Class jsonProvider = Class.forName("org.glassfish.jersey.moxy.json.MoxyJsonFeature");
    // Class jsonProvider = Class.forName("org.glassfish.jersey.jettison.JettisonFeature");
    resources.add(jsonProvider);
    } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    addRestResourceClasses(resources);
    return resources;
    }

    /**
    * Do not modify addRestResourceClasses() method.
    * It is automatically populated with
    * all resources defined in the project.
    * If required, comment out calling this method in getClasses().
    */
    private void addRestResourceClasses(Set<Class> resources) {
    resources.add(resources.CityResource.class);
    resources.add(resources.CountryResource.class);
    }

    }

    I found the solution

    Regards

  20. Interesting that nobody mention so far…

    It seems that author had confused PUT and POST in the article.
    In fact, POST is responsible for adding new resource whereas PUT is for update one.

    Please correct that.

    1. Opinions seem to vary as to what CRUD operation PUT and POST map. This blog – http://code.tutsplus.com/tutorials/a-beginners-guide-to-http-and-rest–net-16340 – indicates the PUT to create or update resources while POST is used for repeated operations on the server. It goes on to point out that PUT and POST are more or less interchangeable and that POST is often used for both create ad update. That is likely because browsers do not support PUT operations.

      At any rate, I’ll update the blog to indicate this ambiguity. Thanks for the comment.

  21. I was pleased to find this because it distills the basics of what a simple REST implementation needs to be.

  22. Thanks Vic, it was super fast to understand RESTful, I needed a simple tutorial and is was great, Thanks!! (in step 10 of “Get Service Handler” section change “\” for “/” :

    Get some REST!

    😉 )

  23. Hi Vic,
    This is good tutorial for a someone like me new to java web service.
    Do you have a tutorial with Netbeans tomcat and a Database.

  24. Sir I followed every step of your example but i am getting 404error,i have cloned ypur project from git and tried with this but again i am getting the same error,dont know what to do now?

    1. For this version of the project you need to get the code from Github then check out the jersey-1.8 branch. Here is what you do:

      1. git clone git@github.com:vichargrave/getsomerest.git
      2. git checkout jersey-1.8

      Then you can load the project and run it.

  25. hey,I want to show my data from databse(mysql) in json format,How can I do it in netbeans.please help me out.thank you 🙂

  26. Hey, I want to take 2 strings input from client side and then concatenate them . HOw can i develop RESTful web Service for this

  27. hey thanx for this valuble tutorial. i want to know how develop client side using restful.
    eg. send regestration details to server
    thank you

Leave a Reply

Your email address will not be published. Required fields are marked *