Home > Enterprise >  Spring Boot non-required requestParams default to null instead of empty string
Spring Boot non-required requestParams default to null instead of empty string

Time:05-08

I'm using Spring Boot for a search tool and I'm having an issue while passing the values from the front-end to the back-end. So, I have a select field that I'm using for this search tool, it's used for a search. It has 3 values (PRIVATE,PUBLIC, and ALL). PRIVATE option has the value PRIVATE, PUBLIC option has the value PUBLIC and ALL has the value empty string '' . When I try to pass in the search api with the empty string, the backend doesn't get the empty string but he intercepts it as null for some reason. Here is my code for the front-end HTML / Vue.js

      <div >
    <label for="statut" >Statut</label>
    <select name="statut"  id="statut" v-model="selectedVisibility">
      <option value="PRIVATE">PRIVATE</option>
      <option value="PUBLIC">PUBLIC</option>
      <option value="">ALL</option>
    </select>
  </div>

Here is my JS:

      async searchBy(){
{
fetch(`http://localhost:100/api/v1/questions/search?statut=${this.selectedVisibility}`, 
   {headers : authHeader()})
  .then(response => response.json())
  .then(data =>
 {  console.log(data);
   this.questions = data })

}
  },

When I pass the ALL value which is an empty String '', Spring Boot defaults it to null instead of keeping that value. I could probably add a conditional inside ( if value is null ) value = ''; but that would take too much time since I have many search tools, so, is there another way to make it take the value of the empty string instead of null? Here is the backend code :

     @GetMapping("/questions/search")
    @CrossOrigin(origins = "http://localhost:8081")
    public ResponseEntity<List<Question>> getQuestionByAtLeastOne
           (
            @RequestParam(value="statut",required=false) EStatus statut)
            throws ResourceNotFoundException
    {
        List<Question> question= questionRepository.findByAtLeastOne(statut);
        return ResponseEntity.ok().body(question);
    }

The findByAtLeastOne is just a method that does the search but before even getting to that part the value has already been turned to null

CodePudding user response:

You could use the defaultValue parameter as in @RequestParam(value = "status", required = false, defaultValue = "") if your statut was a String.

But from your code it looks like it's an enum (EStatus) and with enums defaultValue has to contain a constant expression that could be passed to Enum.valueOf(). If that's the case even if you specify defaultValue = "" the value will still be null. (Obviously it would work if you had a default enum value like "ALL" and used defaultValue = "ALL").

Otherwise you'll have to handle the null value manually either in the controller or in your repository method.

  • Related