Chit Khine Chit Khine - 6 months ago 20
Java Question

@Post in Rest Service accepting Json Values

I have been trying to learn @POST to create webservices using Jersey.
I can now fully adapt the @Get and @Post using the normal params.
For example,

@POST
@Path("/{param}")
public Response postMsg(@PathParam("param") String msg) {
String output = "POST:Jersey say : " + msg;
return Response.status(200).entity(output).build();
}


However, I am not sure how I am suppose to accept JSON message and either create or process it through the url.

Any examples would be appreciated.

Answer

Create a Data Transfer Object which will be used to consume JSON send from UI and use it directly. @Consume can be used to configure data type format send from UI It can be JSON or Form submit etc

@POST
@Path("/{param}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response postMsg(UserData userData) {
   ...
}


public class UserData {

    private String userName;
    private String userAddress;
    ... 
    define getter setter 

}


// UI JSON call 

    var url = "rest/employee";
    var type = "POST";
    var data = {
        userName : $("#txtEmpFirstName").val(),
        userAddress : $("#txtEmpLastName").val(),
    };


    $.ajax({
        type : type,
        url : url,
        data : JSON.stringify(data),
        contentType: "application/json",
        success : function(data) {
             alert(data.Success);
             resetEmployee();
             searchEmployee();
        }, error : function(error){ alert(JSON.stringify(error.responseText));}
    });