Home  >  Web Services  >  RESTEasy 3

RESTEasy 3 @Form Annotation Example

By Arvind Rai, March 11, 2015
In this page we will learn RESTEasy 3 @Form annotation example. Using @Form annotation, we can bind JAX-RS parameters with entity attributes. The JAX-RS method uses different parameter types like @PathParam, @HeaderParam and @QueryParam etc. If a JAX-RS method uses more than one parameter or same parameters are being used in different methods then to collect all those parameters types in an entity as attributes is better way to maintain. Using RESTEasy @Form annotation, we can do it. Find the example of Entity containing attributes annotated with @PathParam, @HeaderParam and @QueryParam .
EmpForm.java
package com.concretepage;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
public class EmpForm {
	@PathParam("id")
	private Integer id ;
	@HeaderParam("Accept-Language")
	private String lang;
	@QueryParam("name")
	private String name;
	@QueryParam("age")
	private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLang() {
		return lang;
	}
	public void setLang(String lang) {
		this.lang = lang;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
} 
Now we can simply use this entity in our JAX-RS method as below.
public Response saveEmp(@Form EmpForm form) {} 
Find the service class.
EmployeeService.java
package com.concretepage;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.Form;
import org.jboss.resteasy.annotations.providers.jackson.Formatted;
@Path("/manage")
public class EmployeeService {
    @GET
    @Path("/save/{id}")
    @Produces("application/json")
    @Formatted
    public Response saveEmp(@Form EmpForm form) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	map.put("id", form.getId());    	
    	map.put("lang", form.getLang());
    	map.put("name", form.getName());
    	map.put("age", form.getAge());
        return Response.ok(map).build();
    }
} 
To check the output, deploy the code downloading from the link given in bottom and access the URL
http://localhost:8080/resteasyservice-1/employee/manage/save/111?name=Shyam&age=22
We will get response as below.
{
  "name" : "Shyam",
  "id" : 111,
  "lang" : "en-US,en;q=0.5",
  "age" : 22
} 

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us