Shahzeb Khan
Shahzeb Khan

Reputation: 3642

Spring MVC : empty value for form field of type long results in 400 bad request

I am trying to submit a form having following fields.

private String type;
private long minPrice;
private long maxPrice;

when one of the two fields of type long is empty, for submission results in 400 Bad request (works fine in case of non empty fields).

Here is an error I get:

default message [minPrice]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'long' for property 'minPrice'; nested exception is java.lang.NumberFormatException: For input string: ""

As far as I understand that it tries to parse an empty string to type long or I am wrong?.

Now what should I do so that I can be able to submit this form even if values for fields of type long are null?

(I am using Spring 4.0)

Upvotes: 2

Views: 2180

Answers (3)

dobrivoje
dobrivoje

Reputation: 992

I had a different situation, here is a code excerpt :

@Consumes(MediaType.MULTIPART_FORM_DATA)
@PermitAll
@Path("uploadSiteDocument")
void uploadSiteDocument(@FormDataParam("siteId") Long siteId,
                        @FormDataParam("fileTypeId") Long fileTypeId,
                        @FormDataParam("description") String description,
                        @FormDataParam("file") InputStream uploadedInputStream,
                        @FormDataParam("file") FormDataContentDisposition fileDetail,
                        @FormDataParam("file") FormDataBodyPart body,
                        @FormDataParam("primaryConnection") Long pcId,
                        @FormDataParam("internalSolution") Long isId)
        throws IOException, RepositoryException;

Through Postman this service works ONLY if two last parameters are empty, not with NULL values but empty.

The only two solutions are :

  1. to check on the front-end side if those values are null, and to set them as empty string
  2. or, to declare those two Long as String types, and the parse them on the back-end side

Solution 2:

...@FormDataParam("primaryConnection") **String** pcId,
   @FormDataParam("internalSolution") **String** isId)

Upvotes: 0

Athanor
Athanor

Reputation: 955

Use class Long instead of primitive type long, you'll be able to check for null values so you can process them and avoid the bad request error

@RequestMapping(value="/your_path", method = RequestMethod.GET)
public String myControllerFunction(
        @RequestParam("minPrice") Long min,
        @RequestParam("minPrice") Long max,
        @RequestParam("type") String type) {

    // your controller code
}

Upvotes: 2

pdem
pdem

Reputation: 4077

You should use Class "Long" instead of type "long" since primitive type can't have empty values.

Upvotes: 3

Related Questions