I've been in the world of software development for 14+ years working with most mainstream programming languages at some point. Chad is a DZone MVB and is not an employee of DZone and has posted 38 posts at DZone. You can read more from them at their website. View Full User Profile

Building a simple REST service using NetBeans IDE 7, a Java Servlet, and JAXB

11.10.2011
| 24181 views |
  • submit to reddit

There are plenty of good Java based REST frameworks out there to build applications with. Restlet, RESTEasy, Jersey, etc. come to mind just to name a few. You don’t need a REST framework to build a simple REST service (although using a REST framework is definitely a great idea and my personal preference as well). Just for fun and learning though today I’ll show you how to build a simple REST service that returns some XML. I’ll just use a simple Java servlet and JAXB.

Note: I’m using NetBeans IDE 7 to build this project.

I created a new Maven Web Application called: RESTfullySimple

Once the project has been created add a new Java class called: User

Here is the code for the User.java file:

package com.giantflyingsaucer;
 
import javax.xml.bind.annotation.XmlType;
 
@XmlType
public class User {
    private String firstname;
    private String lastname;
    private int age;
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getFirstname() {
        return firstname;
    }
 
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
 
    public String getLastname() {
        return lastname;
    }
 
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

Add another class to the project called: UserList

This class will create some new users via the constructor and store them in a list. Here is the code:

package com.giantflyingsaucer;
 
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement(name="userlist")
public class UserList {
 
    private List<User> users;
 
    public List<User> getUsers() {
        return users;
    }
 
    public void setUsers(List<User> users) {
        this.users = users;
    }
 
    public UserList() {
        User user1 = new User();
        user1.setAge(25);
        user1.setFirstname("George");
        user1.setLastname("Watkins");
 
        User user2 = new User();
        user2.setAge(30);
        user2.setFirstname("Julie");
        user2.setLastname("Joelle");
 
        User user3 = new User();
        user3.setAge(58);
        user3.setFirstname("Max");
        user3.setLastname("Kutter");
 
        this.users = new ArrayList<User>();
        this.users.add(user1);
        this.users.add(user2);
        this.users.add(user3);
    }
}

In each class you will notice I used a couple annotations to help JAXB out: XmlType and XmlRootElement

Add a servlet to the project called: RESTfullySimpleServlet

Below is the code for the new servlet (since I’m using Servlet 3 there is no need to create a web.xml file for this project and you can delete any default jsp files that Maven created).

Note: See my previous article on Servlet 3 annotations if you are not familiar with them.

package com.giantflyingsaucer;
 
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
 
@WebServlet(name = "RESTfullySimpleServlet", urlPatterns = {"/Users"})
public class RESTfullySimpleServlet extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        response.setContentType("text/xml");
 
        try {
            TransformerFactory.newInstance().newTransformer().transform(
                    GetXML(new UserList()), new StreamResult(response.getOutputStream()));
        }
        catch(Exception ex) {
            throw new ServletException(ex);
        }
    }
 
    private Source GetXML(UserList userList) throws ServletException {
 
        Document document = null;
 
        try {
            Marshaller marshaller = JAXBContext.newInstance(UserList.class).createMarshaller();
            document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            marshaller.marshal(userList, document);
        }
        catch(JAXBException jaxbex) {
            throw new ServletException(jaxbex);
        }
        catch(ParserConfigurationException parseex) {
            throw new ServletException(parseex);
        }
 
        return new DOMSource(document);
    }
 
    @Override
    public String getServletInfo() {
        return "RESTfully Simply Servlet";
    }
}

Here is the project structure:

In NetBeans IDE, issue the Maven Build and Clean command for the project and then deploy the resulting WAR file. I deployed mine to Tomcat 7.

The path for my REST service is: http://localhost:8080/RESTfullySimple-1.0-SNAPSHOT/Users

Note: Your path may differ depending how you set it up and deployed it.

 

From http://www.giantflyingsaucer.com/blog/?p=3339

AttachmentSize
contextMenu.png42.74 KB
Published at DZone with permission of Chad Lung, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

John Wine replied on Thu, 2011/11/10 - 9:58pm

you've got a 403 Permission Denied for the embeded images on this page.

Almir Campos replied on Tue, 2011/11/15 - 2:20pm

I can't see any images above. The below message is showed when clicking on an image: 403 Permission Denied You do not have permission for this request /blog/wp-content/uploads/2011/10/Screen-Shot-2011-10-25-at-9.27.45-PM.png ------- Would you help me? Thanks in advance. Almir Campos. Sao Paulo, Brazil.

Aniceto Garcia replied on Thu, 2012/01/26 - 4:37am

you have written a very good article on Building a simple REST service using NetBeans IDE 7, a Java Servlet, and JAXB. However, I am looking for something step by step to create this in netbeans 7.1.

Also what would be other configurations and deployment descriptor for the above.

Java Collection

Lazaro Wolf replied on Fri, 2012/07/06 - 4:20pm

Excellent tutorial. Chad, thanks! Unfortunately, pieces of code are displayed as images, but the links are broken. Could you resolve it please? Many thanks!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.