Search code examples
netbeansjax-ws

Rest Webservice with netbeans 8.2


I have created a very basic Java Web Application with Netbeans 8.2

Here is the steps i have done:

  • "File" > "New Project" : "Java Web" > "Web Application"
  • I have created a Java Class by right clicking on project name. Then New > Java Classe

Here what i have put in this java class:

package pkg1;

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

public class TestService 
{
    @Path("/test")
    @GET
    @Produces("text/plain")
    public String methode_test() 
    {
        return "Hello test";
    }
}

I have no compilation problem. GlassFish is launched, but i got a 404 error if i try to go to /test url...

Any idea ?

Thanks


Solution

  • I made a couple of small changes to get your code working using NetBeans 8.2, JDK 8 and Glassfish 4.1.1 on Windows 10:

    • Add a @Path annotation on the class as well as methode_test().
    • Add a second class to pkg1 named ApplicationConfig which extends javax.ws.rs.core.Application as shown below.

    This is the revised TestService class:

    package pkg1;
    
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    
    
    @Path("/demo")
    public class TestService
    {
        @Path("/test")
        @GET
        @Produces("text/plain")
        public String methode_test()
        {
            return "Hello test";
        }
    }
    

    This is the additional class you need to add:

    package pkg1;
    
    import javax.ws.rs.core.Application;
    
    @javax.ws.rs.ApplicationPath("sample")
    public class ApplicationConfig extends Application {
    
    }
    

    My project was named DemoService, and therefore had a context root of DemoService, but in your case the URL to use would probably be: http://localhost:8080/TestService/sample/demo/test

    browser

    Notes:

    • See this answer to the SO question What is that Application class lifecycle of a rest service? for more details on why you need to create a class which extends that Application class.
    • For convenience you can set the default path to be used in the browser when testing your project:

      • Open the Properties window of your project from the Projects panel.
      • Select Run and set the values of Context Path and Relative URL as appropriate:

        browserDefaultURL

    • NetBeans 8.2 provides a basic "Hello World" REST application that you can create in just a few seconds using the Project Wizard: File > New Project... > Samples > Web Services > REST: Hello World.