RESTful Web Services @FormParam Example using JAX-RS and Jersey

@FormParam Example

In this example we are going to develop a simple RESTful web service using JAX-RS and Jersey to extract form parameters submitted by a form using @FormParam annotation.

Our RESTful web service will have three endpoints. This first endpoint, allows us to add books into our datastore using form parameters that have been submitted by the form using POST method. The second endpoint allows us to extract all of the form elements using MultivaluedMap which creates a map with key/value pairs. The last endpoint, allows us to view all of the books available to us in the datastore.

@FormParam can be used only on the following Java types:

  • All primitive types except char
  • All wrapper classes of primitive types except Character
  • Any class with a constructor that accepts a single Stringargument
  • Any class with the static method named valueOf(String) that accepts a single Stringargument
  • Any class with a constructor that takes a single String as a parameter

Getting Started

In order to run this tutorial yourself, you will need the following:

  • Java JDK 1.6 or greater
  • Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
  • Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS
  • Jersey JAX-RS
  • log4J (for logging purposes)

Required Libraries

Copy all of the following jars to WebContent->WEB-INF->lib folder.

asm-3.1.jar
jersey-client-1.18.jar
jersey-core-1.18.jar
jersey-json-1.18.jar
jersey-server-1.18.jar
jersey-servlet-1.18.jar
jsr311-api-1.1.1.jar
log4j-1.2.17.jar

Complete Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

jax-rs formparam proj

RESTful Web Service End Points

#URIMethodDescription
1/rest/books/addPOSTAdds a book to our datastore by passing in all of the parameters in the request as form parameters
2/rest/books/mapPOSTUses MultivaluedMap to map all the fields into a Map collection to store key/value pairs of field elements from the form
3/rest/books/listGETDisplays all of the books in our List datastore.

Using the @FormParam in JAX-RS API

Using MultivaluedMap Interface

In this example we show you how to extract all of the form elements using MultivaluedMap.

@POST
@Path("/map")
@Produces(MediaType.TEXT_HTML)
public Response viewMap(MultivaluedMap<String, String> formFields) {

  StringBuffer msg = new StringBuffer(" View all Form Fields:<br/><br/>");
  for (String field : formFields.keySet()) {
    msg.append(field);
    msg.append(" : ");
    msg.append(formFields.get(field));
    msg.append("<br/>");
  }

  return Response.status(200).entity(msg.toString()).build();
}

Complete Program using @FormParam

package com.avaldes;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;

import com.avaldes.model.Book;

@Path("/books")
public class RestfulFormParamExample {
  static Logger logger = Logger.getLogger(RestfulFormParamExample.class);
  static List<Book> bookList = new ArrayList<Book>(); 
  
  @POST
  @Path("/add")
  @Produces(MediaType.TEXT_HTML)
  public Response addBook(@FormParam("isbn") String ISBN, 
                @FormParam("name") String name,
                @FormParam("author") String author,
                @FormParam("publisher") String publisher,
                @FormParam("stock_qty") int stockQty,
                @FormParam("price") double price) {

    Book b = new Book();
    b.setISBN(ISBN);
    b.setName(name);
    b.setAuthor(author);
    b.setPublisher(publisher);
    b.setStockQty(stockQty);
    b.setPrice(price);
    
    bookList.add(b);
    
    String msg = "addBook: " + b.toString();
    logger.info(msg);
    
    return Response.ok(msg).entity(msg).build();
  }
  
  @POST
  @Path("/map")
  @Produces(MediaType.TEXT_HTML)
  public Response viewMap(MultivaluedMap<String, String> formFields) {

    StringBuffer msg = new StringBuffer(" View all Form Fields:<br/><br/>");
    for (String field : formFields.keySet()) {
      msg.append(field);
      msg.append(" : ");
      msg.append(formFields.get(field));
      msg.append("<br/>");
    }

    return Response.status(200).entity(msg.toString()).build();
  }
  
  @GET
  @Path("/list")
  public Response getBooks() {
    
    String msg = "getBooks: " + bookList;
    logger.info(msg);
    
    return Response.ok(msg).entity(msg).build();
  } 
}

Model Class (Book.java)

Next we create a model class called Book.java which will hold all of the values coming from the users entry from our HTML forms.

package com.avaldes.model;

public class Book { 
  private String ISBN;
  private String name;
  private String author;
  private String publisher;
  private int stockQty;
  private double price;
  
  public Book() {}
  
  public Book(String ISBN, String name, String author, String publisher, int qty, double price) {
    this.ISBN = ISBN;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.stockQty = qty;
    this.price = price;
  }
  
  public String getISBN() {
    return ISBN;
  }
  
  public void setISBN(String ISBN) {
    this.ISBN = ISBN;
  }
  
  public String getName() {
    return name;
  }
  
  public void setName(String name) {
    this.name = name;
  }
  
  public String getAuthor() {
    return author;
  }
  
  public void setAuthor(String author) {
    this.author = author;
  }
  
  public String getPublisher() {
    return publisher;
  }
  
  public void setPublisher(String publisher) {
    this.publisher = publisher;
  }
  
  public int getStockQty() {
    return stockQty;
  }

  public void setStockQty(int stockQty) {
    this.stockQty = stockQty;
  }

  public double getPrice() {
    return price;
  }

  public void setPrice(double price) {
    this.price = price;
  }

  @Override
  public String toString() {
    return "Book [ISBN=" + ISBN + ", name=" + name + ", author=" + author
        + ", publisher=" + publisher + ", stockQty=" + stockQty 
        + ", price=" + price + "]";
  } 
}

Web Deployment Descriptor (web.xml)

This is a pretty straight forward deployment descriptor file – only thing you need to add is the location of you java package in the Jersey ServletContainer entry as init-param. Please ensure you add it to the web.xml file as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>com.omega.rest</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
 
   <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.avaldes</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

Testing out the Web Services

In this example, we will add two books to our internal datastore using the @FormParam parameters. When we use the imageMap.html page we will post our form contents to the /rest/books/map end point which prints out each of the form elements as key/value pairs. For the last example, we simply use the /rest/books/list end point to print out all of the books that have been added to our datastore.

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java jaxrs formparam

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

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