user3853858
user3853858

Reputation: 245

Spring optional parameter int

I have a method in Spring controller like this;

@RequestMapping(value = "/contact", method = RequestMethod.GET)
public final ModelAndView contact(@RequestParam(value = "id", required = false) int i)  {..}

I pass in the parameter i to another method. In that method, I want to check if there is a value in int i. If the parameter was not set (this is optional), I want to set it to a certain value. How do I check this in Spring?

Upvotes: 10

Views: 7386

Answers (1)

JB Nizet
JB Nizet

Reputation: 691755

Use Integer instead of int. If it's not set, it will be null.

If, for example, 0 is not a valid ID value, you can also leave the type as int and use

@RequestParam(value = "id", defaultValue = "0")

The parameter will than be equal to 0 if not passed.

Upvotes: 16

Related Questions