/ #Java #Jersey 

A Jersey POJOMapping Example in Mapping Form Parameters

Jersey, RESTful Web Services in Java.

In Java Servlet circumstance, we usually harvest the form parameters by using request.getParameter(“FORM_FIELD_NAME”) syntax. Now we can do it more elegant while enabling Jsersey’s POJOMapping features. The following example demonstrates the account registration scenario. Here we have a Account class, i.e., Account.java:

public class Account {
    private String email;
 
    @JsonProperty("email")
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
}

Make sure you have turned on the POJOMapping feature in web.xml,

...
<servlet>
    <servlet-name>Jersey REST Service</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>ROOT_RESOURCE_AND_PROVIDER_CLASSES_IN_THE_PACKAGES</param-value>
    </init-param>
    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
...

Account registration service with http POST method in AccountResource.java:

@Path("/account")
public class AccountResource {
 
    @POST
    @Path("/register")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response Register(InputStream is){
        Response response = null;
        try {
            Account acct = new ObjectMapper().readValue(is, Account.class);         
            System.out.println(acct.getEmail());
        } catch (IOException e) {
            response = Response.serverError().build();
        }   
                     
        if(response == null)
            response = Response.ok().build();
         
        return response;                
    }
}

As shown in above code, we can read value from input steam into custom class (i.e., Account class) then continue doing the following business logic. However, you may encounter the Unsupported Media Type status code (415) while using the static HTML form post method. This is because we identify the service-consume-type is JSON.

Unsupported Media Type

So we get correct response and mapping object while the corresponding way. Note that the differences in Content-Type and Request Payload parts.

Request Payload