REST @FormParam is null

2019-06-04 05:50发布

问题:

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?

回答1:

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>


回答2:

Have you defined the Requestmapping like this:

@POST
@Path("/submitclient") // your request mapping for 'subUrl'
public Object persistResetPasswordLogs(@FormParam("clientName") String clientName)

and html:

<form action="submitclient" method="post">
    ...
</form>

Also look at your json object. I believe you should send something like this:

var loginData = {
    clientName: "dit" // get it from input
};

?