Over a million developers have joined DZone.

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

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}