In this article, we will learn and implement @FormParam annotation in JAX-RS Restful web service. @FormParam binds the value/s of form parameter sent by the client in the POST request into formal arguments of Java method
JBoss RestEasy is a JAX-RS implementation for developing Restful web service in java. Once developed, it isn’t restricted to deploy only in JBoss Application Server but you can deploy in any other server like Apache Tomcat, Glassfish, Oracle Weblogic, etc
@FormParam v/s @QueryParam
Use @FormParam for POST request when using form and prefer @QueryParam for GET requests
Annotation Used
- @FormParam (javax.ws.rs.FormParam)
- @Path (javax.ws.rs.Path)
- @GET (javax.ws.rs.GET)
Technology Used
- Java 1.7
- Eclipse Luna IDE
- RestEasy-3.0.8.Final
- Apache Maven 3.2.1
- Apache Tomcat 7.0.54
- JBoss Application Server 7.1.1.Final
Mavenize or download required jars
Add RestEasy-3.0.8.Final dependencies to pom.xml
<properties> <resteasy.version>3.0.8.Final</resteasy.version> <resteasy.scope>compile</resteasy.scope> <!-- compile(Tomcat) / provided(JBoss) --> <compileSource>1.7</compileSource> <maven.compiler.target>1.7</maven.compiler.target> <maven.compiler.source>1.7</maven.compiler.source> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- RESTEasy JAX RS Implementation --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>${resteasy.version}</version> <scope>${resteasy.scope}</scope> </dependency> <!-- Resteasy Servlet Container Initializer --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-servlet-initializer</artifactId> <version>${resteasy.version}</version> <scope>${resteasy.scope}</scope> </dependency> <!-- RESTEasy JAX RS Client --> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-client</artifactId> <version>${resteasy.version}</version> <scope>${resteasy.scope}</scope> </dependency> </dependencies>
Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the central repository or maven repository and include them in the classpath
- resteasy-jaxrs
- resteasy-servlet-initializer
- resteasy-client
- jaxrs-api-3.0.8.Final
- jboss-annotations-api_1.1_spec-1.0.1.Final
- jcp-annotations-1.0
- activation-1.1
- async-http-servlet-3.0-3.0.8.Final
- common-codec-1.6
- commons-io-2.1
- commons-logging-1.1.1
- httpcore-4.2.1
- httpclient-4.2.1
Directory Structure
Before moving on, let us understand the directory/package structure once you create project in Eclipse IDE
Maven has to follow certain directory structure
- src/test/java –> test related files, mostly JUnit test cases
- src/main/java –> create java source files under this folder
- src/main/resources –> all configuration files placed here
- src/test/resources –> all test related configuration files placed here
- Maven Dependencies or Referenced Libraries –> includes jars in the classpath
- WEB-INF under webapp –> stores web.xml & other configuration files related to web application
Project Structure (Package Explorer view in Eclipse)
Jars Libraries Used in the Project (Maven Dependencies)
Web application
For any web application, entry point is web.xml which describes how the incoming http requests are served / processed. Further, it describes about the global-context and local-context param (i.e.; <context-param> & <init-param>) for loading files particular to project requirements & contains respective listener
With this introduction, we will understand how we configured web.xml for RestEasy JAX-RS Restful web service
web.xml (the entry point –> under WEB-INF)
This web.xml file describes,
- Like any JEE web framework register org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher with servlet container
- http requests with URL pattern “/resteasy/*” will be sent to the registered servlet called “javax.ws.rs.core.Application” i.e.; HttpServletDispatcher (org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher)
- set resteasy.servlet.mapping.prefix as <context-param>, if your servlet-mapping has a url-pattern anything other than “/*”. In this example, set “/resteasy”
- if not set, then you will end up with 404 not found error
- set resteasy.resources as <param-name> with comma delimited list of fully qualified JAX-RS resource class names you want to register as <param-value> using global <context-param>
- <welcome-file-list> files under this tag is the start-up page
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>RestEasy-FormParam</display-name> <!-- RestEasy resource registering --> <context-param> <param-name>resteasy.resources</param-name> <param-value>com.resteasy.series.formparam.CustomerServiceImpl</param-value> </context-param> <!-- RestEasy Servlet --> <servlet> <servlet-name>javax.ws.rs.core.Application</servlet-name> <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class> </servlet> <servlet-mapping> <servlet-name>javax.ws.rs.core.Application</servlet-name> <url-pattern>/resteasy/*</url-pattern> </servlet-mapping> <!-- this is mandatory, if url-pattern is other than /* --> <context-param> <param-name>resteasy.servlet.mapping.prefix</param-name> <param-value>/resteasy</param-value> </context-param> <!-- welcome file --> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
Let’s see coding in action
URL Pattern
Http url for any common web application is http://<server>:<port>/<root-context>/<from_here_application_specific_path>
In our example, we are going to deploy the war into Tomcat 7.0 server so our server and port are localhost and 8080 respectively. Context root is the project name i.e.; RestEasy-FormParam. Initial path for this application is http://localhost:8080/RestEasy-FormParam
We have configured “/resteasy/*” as url-pattern for the “javax.ws.rs.core.Application” servlet in web.xml and at interface-level (or say class-level) path configured is “/customer” using @Path annotation. Next respective path for each method annotated with @Path (method-level)
Customer Service interface
Using QueryParam, URL query parameter are mapped into Java method
A simple method which takes three-arguments using @FormParam annotation (multiple parameters)
URL: http://localhost:8080/RestEasy-FormParam/resteasy/customer/custinfo
POST request from the form will invokes this method when the relative action (path) is set to “resteasy/customer/custinfo”
NOTE: It’s always a good programming practice to do code-to-interface and have its implementation separately
ICustomerService.java
package com.resteasy.series.formparam; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/customer") public interface ICustomerService { // http://localhost:8080/RestEasy-FormParam/resteasy/customer/custinfo - Tomcat 7.0.x // http://localhost:9090/RestEasy-FormParam/resteasy/customer/custinfo - JBoss AS7 @POST @Path("/custinfo") public Response printCustomerInfo( @FormParam("id") String custId, @FormParam("name") String custName, @FormParam("age") String custAge); }
Customer Service implementation
Implements above interface returning Response object for both methods
CustomerServiceImpl.java
package com.resteasy.series.formparam; import javax.ws.rs.core.Response; public class CustomerServiceImpl implements ICustomerService { public Response printCustomerInfo(String custId, String custName, String custAge) { String customerInfo = "Customer [Id=" + custId + ", Name=" + custName + ", Age=" + custAge + "] added to database successfully"; return Response.status(200).entity(customerInfo).build(); } }
View Technologies
Start up page which has anchor link to “addNewCustomer.html” with value Click here à redirects to addNewCustomer.html page
index.html (\src\main\webapp\index.html)
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>RestEasy-FormParam</title> </head> <body> <b>Welcome to the world of RestEasy - A JAX-RS Restful web service</b> <br /> <br /> <a href="addNewCustomer.html">Click here </a>to add new customer </body> </html>
Simple HTML form with POST action (method) which takes three inputs from the end user to add new customer to the database
addNewCustomer.html (\src\main\webapp\addNewCustomer.html)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>RestEasy - @FormParam</title> </head> <body> <center> <b>Welcome to the JAX-RS Restful web service Learning</b> <h4>An Example on @FormParam Annotation</h4> <form method="post" action="resteasy/customer/custinfo"> <table> <tr> <td>Customer ID:</td> <td><input type="text" name="id" /></td> </tr> <tr> <td>Customer Name:</td> <td><input type="text" name="name" /></td> </tr> <tr> <td>Customer Age:</td> <td><input type="text" name="age" /></td> </tr> <tr> <td colspan="1"><input name="submit" type="submit" value="Add New Customer" /></td> <td colspan="1"><input name="reset" type="reset" value="Reset" /></td> </tr> </table> </form> </center> </body> </html>
Deployment
- Run maven command to build the war: mvn clean install (use command prompt or integrated maven in eclipse IDE
- Copy the war file from the target folder
- Paste it into apache tomcat (webapps folder)
- Start the tomcat server
Test the service !!
Testing
1. Form Testing via Web browser
Access the default URL http://localhost:8080/RestEasy-FormParam which has a anchor link to addNewCustomer.html page
Click on the link, you will be redirected to addNewCustomer.html page which displays fields for entering ID, Name & Age to capture customer information and store it in the database
Or else directly access the URL for the same page
http://localhost:8080/RestEasy-FormParam/addNewCustomer.html –> displays below page
Enter details of customer like
ID : 12345678
Name : Pete Sampras
Age : 44
And click “Add New Customer” button
Clicking “Add New Customer” button will invokes POST method configured in the form tag with action=“resteasy/customer/custinfo”
On successful execution of the request, a success message is returned to the user as shown below
2. Java client (RestEasy)
You can write a Java client for this. Take a look at the below client from JBoss package org.jboss.resteasy.client which has two classes namely ClientRequest and ClientResponse for resteasy service invocation
TestCustomerService.java
package test.resteasy.series.formparam; import javax.ws.rs.HttpMethod; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; public class TestCustomerService { public static void main(String[] args) throws Exception { // setting & invoking first request System.out.println("Executing POST request for @FormParameter"); String url = "http://localhost:8080/RestEasy-FormParam/resteasy/customer/custinfo"; String responseString = testFormParameterForPost(url); System.out.println("Response String for @FormParam : " + responseString); } /** * using ClientRequest and ClientResponse classes from org.jboss.resteasy.client * @param url * @throws Exception */ @SuppressWarnings("deprecation") public static String testFormParameterForPost(String url) throws Exception { // local variables ClientRequest clientRequest = null; ClientResponse<String> clientResponse = null; int responseCode; String responseString = null; MultivaluedMap<String, String> formParameters = null; try{ clientRequest = new ClientRequest(url); clientRequest.setHttpMethod(HttpMethod.GET); clientRequest.accept(MediaType.APPLICATION_FORM_URLENCODED); formParameters = clientRequest.getFormParameters(); formParameters.putSingle("id", "120001"); formParameters.putSingle("age", "25"); formParameters.putSingle("name", "test-user"); clientResponse = clientRequest.post(String.class); responseCode = clientResponse.getResponseStatus().getStatusCode(); System.out.println("Response code: " + responseCode); if(clientResponse.getResponseStatus().getStatusCode() != 200) { throw new RuntimeException("Failed with HTTP error code : " + responseCode); } System.out.println("ResponseMessageFromServer: " + clientResponse.getResponseStatus().getReasonPhrase()); responseString = clientResponse.getEntity(); } catch(Exception ex) { ex.printStackTrace(); } finally{ // release resources, if any clientResponse.close(); clientRequest.clear(); } return responseString; } }
Output in console
Executing POST request for @FormParameter Response code: 200 ResponseMessageFromServer: OK Response String for @FormParam : Customer [Id=120001, Name=test-user, Age=25] added to database successfully
Download project (Tomcat Server 7.0.x)
RestEasy-@FormParam-annotation (Tomcat server) (8kB)
JBoss Deployment
- Update pom.xml with resteasy scope “provided” for dependencies as JBoss AS7 modules already contains these dependent jars
<resteasy.scope>provided</resteasy.scope> <!-- compile(Tomcat) / provided(JBoss) -->
- Update web.xml
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>RestEasy-FormParam</display-name> <!-- RestEasy Servlet --> <servlet-mapping> <servlet-name>javax.ws.rs.core.Application</servlet-name> <url-pattern>/resteasy/*</url-pattern> </servlet-mapping> <!-- welcome file --> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
- Rest remain the same
- Read through this article which explains development & deployment of RestEasy web service with JBoss Application Server in detail
Note: JBoss Application Server 7.1.1.Final comes with default RestEasy distribution with version 2.3.2.Final. So update JBoss AS7 with latest RestEasy version. Look at this article, which explains how to update default version with latest version available in the JBoss community
Download project (JBoss Application Server 7.1.1.Final)
RestEasy-@FormParam-annotation (JBoss server) (8kB)
Conclusion: When the requirement is to send the data from the form, then this approach would be appropriate
Happy Coding !!
Happy Learning !!