Previously we have learnt about @PathParam, @QueryParam, @Context, @MatrixParam annotations, In this article we will learn how to get the values from the Form which is getting submitted using @FormParam annotation.
Folder Structure
- Create a Dynamic Web Project RESTful_Example and create a package for our src files “com.javainterviewpoint“
- Place the required jar files under WEB-INF/Lib
jersey-bundle-1.18.jar
asm-3.1.jar - Create the Java classes FormParamExample.java under com.javainterviewpoint folder.
- Place the index.jsp inside the WebContent directory.
- Place the web.xml under the WEB-INF directory
@FormParam Example
package com.javainterviewpoint; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Response; @Path("/form") public class FormParamExample { @Path("/createUser") @POST public Response createUser( @FormParam("firstName") String firstName, @FormParam("lastName") String lastName) { return Response. status(200). entity("New User Created,Welcome "+firstName). build(); } }
Index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!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"> </head> <body> <form action="rest/form/createUser" method="post"> First Name : <input type="text" name="firstName" /><br> Last Name : <input type="text" name="lastName" /><br> <input type="submit" value="Create User" /> </form> </body> </html>
web.xml
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Restful Web Application</display-name> <servlet> <servlet-name>jersey-serlvet</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.javainterviewpoint</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
We register our jersey container “com.sun.jersey.spi.container.servlet.ServletContainer” in the servlet-class of our web.xml and we will mention the source files location as the value to the init param “com.sun.jersey.config.property.packages” so that the container will scan for annotations of the class files within that package.
Hit on the URI :
http://localhost:8080/RESTful_Example
Output
Fill in the form and submit
Leave a Reply