A Jersey POJOMapping Example in Mapping Form Parameters

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:

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,

<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>

Back-End service,

@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.

html-form-post

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

jQuery-post

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s