Close

JAX-RS - @FormParam Examples

JAX-RS JAVA EE 

The annotation @FormParam is used to capture a 'form parameter' contained within a request body. The request verb should typically be @POST. The consume/content type has to be 'application/x-www-form-urlencoded'.

import com.logicbig.example.Customer;
import com.logicbig.example.CustomerDataService;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

@Path("customers")
public class CustomerRestService {
private CustomerDataService dataService = CustomerDataService.getInstance();

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Customer> getCustomers() {
return dataService.getCustomerList();
}


@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
public String createCustomer(@FormParam("name") String name,
@FormParam("address") String address,
@FormParam("phone-number") String phoneNumber) {
return dataService.addCustomer(name, address, phoneNumber);
}

@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getCustomer(@PathParam("id") String id) {
Customer customer = dataService.getCustomerById(id);
if (customer == null) {
return Response.status(Response.Status.NOT_FOUND)
.build();
} else {
return Response.ok()
.entity(customer)
.build();
}


}
}
Original Post




import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;

@Path("/customers")
public class CustomerResource {

@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String createCustomer(@NotNull @FormParam("name") String name,
@NotNull @FormParam("address") String address,
@NotNull @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}")
@FormParam("phone-number") String phoneNumber) {
System.out.println("-- in createCustomer() method --");
return String.format("created dummy customer name: %s, address: %s, phoneNumber:%s%n"
, name, address, phoneNumber);

}
}
Original Post




See Also