DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Building a simple REST service using NetBeans IDE 7, a Java Servlet, and JAXB

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

Chad Lung user avatar by
Chad Lung
·
Nov. 10, 11 · Interview
Like (0)
Save
Tweet
Share
29.61K Views

Join the DZone community and get the full member experience.

Join For Free

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

REST Web Protocols Integrated development environment Java (programming language) NetBeans

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Build a Spring Boot GraalVM Image
  • Unlocking the Power of Elasticsearch: A Comprehensive Guide to Complex Search Use Cases
  • 5 Steps for Getting Started in Deep Learning
  • Best CI/CD Tools for DevOps: A Review of the Top 10

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: