Search code examples
javarestjerseyjax-rsform-parameter

REST @FormParam is null


I have the following being passed from browser to server

Status Code:204 No Content
Request Method:POST
Content-Type:application/x-www-form-urlencoded
Form Data
  json:{"clientName":"PACK","status":"success","message":"successful!"}

and in jsp code

var loginData = {
    clientName: cList,
    status: "success",
    message: "successful!"
};

$.ajax({
        url: subUrl,
        type: 'POST',
        contentType : "application/x-www-form-urlencoded",
        data: {
            json: JSON.stringify(loginData)
        },
        success: function (data) {
            handleLoginResult(data);
        }
    });

And in Java code I have

@POST
public Object persistResetPasswordLogs(@FormParam("clientName")
    String clientName) {

    try {

        log.info("in rest method ??? "+clientName);
        .......
        .......

In server I am getting clientName as null.

What could be the reason for this and how can I resolve this?


Solution

  • AFAIK, there is no Jersey (JAX-RS) mechanism to parse JSON into form data. Form data should be in the form of something like

    firstName=Stack&lastName=Overflow (or in your case clientName=someName)
    

    where firstName and lastName are generally then name attribute value in the form input elements. You can use jQuery to easily serialize the field values, with a single serialize() method.

    So you might have something that looks more along the lines of something like

    <form id="post-form" action="/path/to/resource">
        Client Name: <input type="text" name="clientName"/>
    </form>
    <input id="submit" type="button" value="Submit"/>
    <script>
        $("#submit").click(function(e) {
            $.ajax({
                url: $("form").attr("action"),
                data: $("form").serialize(),
                type: "post",
                success: processResponse,
                contentType: "application/x-www-form-urlencoded"
            });
        });
        function processResponse(data) {
            alert(data);
        }
    </script>