Close

JAX-RS - @POST with HTML Form Example

[Updated: May 30, 2017, Created: Jan 30, 2016]

An HTML form by default sends data with content type application/x-www-form-urlencoded.

<form action="api/customers" method="post" >
           Name  <input type="text" name="name" />
         Address <input type="text" name="address" />
    Phone Number <input type="text" name="phone-number" />
                         <input type="submit" value="Submit" />
</form>

JAX-RS service method handles such request using @FormParam

@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);
    }

We can submit the form request from JAX-RS client as well, instead of an HTML form.

Form form = new Form();
       form.param("name", "Alyssa William")
           .param("address", "1021 Hweitt Street")
           .param("phone-number", "343-343-3433");

Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://www.example.com/api/customers");
Future<String> response = target.
            request(MediaType.APPLICATION_FORM_URLENCODED)
           .accept(MediaType.TEXT_PLAIN)
           .buildPost(Entity.form(form)).submit(String.class);

Example Project

Dependencies and Technologies Used:

  • jersey-core-server 2.22.1: Jersey core server implementation.
  • jersey-container-servlet 2.22.1: Jersey core Servlet 3.x implementation.
  • jersey-media-moxy 2.22.1: Jersey JSON entity providers support module based on EclipseLink MOXy.
  • jersey-test-framework-provider-jdk-http 2.22.1: Jersey Test Framework - JDK HTTP container.
  • JDK 1.8
  • Maven 3.0.4

Jxrs Html Form Post Select All Download
  • jaxrs-html-form-post
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • api
        • webapp
      • test
        • java
          • com
            • logicbig
              • example

To run the application either run the JUnit test CustomerRestServiceTest or run the embedded tomcat server: d:\jaxrs-html-form-post>mvn tomcat7:run -DskipTests and then use the following link to submit the HTML form:

http://localhost:8080/jaxrs-html-form-post/form.html

You will see the response as newly created customer id. You can use the id to access the newly created resource:

http://localhost:8080/jaxrs-html-form-post/api/customers/1

The server will respond back with JSON data.

Create more customers using the form link.

To see all customer use the resource link:

http://localhost:8080/jaxrs-html-form-post/api/customers

See Also