Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring optional parameter int

Tags:

java

spring

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?

like image 484
user3853858 Avatar asked Aug 12 '14 21:08

user3853858


1 Answers

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.

like image 123
JB Nizet Avatar answered Oct 21 '22 03:10

JB Nizet