0

The following URL queries the DB and returns all values correctly using requestParam as below:

    http://localhost:8080/app/locateUser/search?firstname=John&lastname=Clay&id=2

    @RequestParam(value = "firstname") String firstname,
    @RequestParam(value = "lastname") String lastname,
    @RequestParam(value = "id" ) int id

Now I want to make lastname optional(remove from URL) in like this:

http://localhost:8080/app/locateUser/search?firstname=John&id=2

or

http://localhost:8080/app/locateUser/search?firstname=John&lastname=&id=2

How do I make the url optional? I want to be able to query the DB without lastname in the URL string.

This is what I have:

    @RequestParam(value = "firstname") String firstname,
    @RequestParam(value = "lastname" defaultValue = "lname") String lastname,
    @RequestParam(value = "id" ) int id

I've also tried

   @RequestParam(value = "lastname" required=false) String lastname,

Neither seems to work. What am I missing?

Sunny
  • 145
  • 1
  • 3
  • 14
  • It should work with `required = false`, show us your complete method signature and the error you are having, it may help to understand your problem – Alexandre Jacob Sep 28 '15 at 13:24
  • What isn't working... When `required=false` then you get an empty string not null, you will of course have to do something further down the line to ignore empty params in the query... – M. Deinum Sep 28 '15 at 13:24
  • This may help http://stackoverflow.com/questions/17647214/form-values-to-be-null-instead-of-in-spring – Bilal BBB Sep 28 '15 at 13:27
  • i think this question is already done by http://stackoverflow.com/questions/22373696/requestparam-in-spring-mvc-handling-optional-parameters – fabien t Sep 28 '15 at 13:28

2 Answers2

0

In spring Request parameters are required=true by default. Also you should give other Request parameters required situations to specify.

You should make sure, did you deployed your latest war file. And also It seems you have a typo after value parameter you need to separate them with a comma.

İlker Korkut
  • 3,129
  • 3
  • 30
  • 51
0

Update

Turns out that the value/values with defaultValue must be last in the Param URL like this. Everything works fine after that. URL works if lastname is not present. Thanks.

@RequestParam(value = "firstname") String firstname,
@RequestParam(value = "id" ) int id,
@RequestParam(value = "lastname" defaultValue = "lname") String lastname
Sunny
  • 145
  • 1
  • 3
  • 14