1

I have the following which works well in receiving a non-empty Array,

$.ajax({
  url: "ajaxController",
  dataType: "json",
  type: "get",
  data: {
       'term': request.term,
       'exclude': ["45","66"]
  },

Controller (note the [] in RequestParam Value -- the result goes in a String[]):

public List<KeyValueBean> getChoices(String term, 
                                     @RequestParam(value = "exclude[]") 
                                        String[] exclude)  {
}                               

But if I pass an empty array in the same code, which sometimes happens, it breaks:

'exclude': []

or alternatively

'exclude': JSON.stringify([])

Error:

org.springframework.web.bind.MissingServletRequestParameterException: Required 
String[] parameter 'exclude[]' is not present

2 Answers 2

2

If you pay attention to the error, it says your request parameter exclude can not be null. If you need to can send empty array sometimes, you can mark your parameter as optional(not required) in this way:

@RequestParam(required = false, value = "exclude[]")
Sign up to request clarification or add additional context in comments.

3 Comments

Yes this was the closest solution. But you have one error: You can't use value="exclude" Spring requires brackets: value="exclude[]". Once I fixed that, both cases (empty & non-empty) started working. But my question still is, I'm not passing a NULL, I'm passing an empty array. Why is Spring receiving a NULL? That's not what I want to send. If I meant a NULL, I would pass 'exclude': null.
This type of error is related to validation. In terms of arrays validation, null and empty array have same concept. I means, there is not any difference if you send null array or empty array! In both cases, you are violating validation rule.
But the question is why Spring bound [] to a NULL. There is a difference in what I passed. I didn't pass null I passed a []. Spring could have done the String[] binding (Array of Length 0), which is what I was expecting. It's my own decision whether [] is valid while NULL is not, they should get separate binding.
0

The problem is probably because you passed your @RequestParam with value="exclude[]" while you are passing the object named as "exclude".

So, it actually should be:

public List<KeyValueBean> getChoices(String term, 
                                 @RequestParam(value = "exclude") 
                                    String[] exclude)  {
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.