Spring 启动非必需的 requestParams 默认为 null 而不是空字符串

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

我正在使用 Spring Boot 作为搜索工具,但在将值从前端传递到后端时遇到问题。 因此,我有一个用于此搜索工具的 select 字段,它用于搜索。它有 3 个值(PRIVATE、PUBLIC 和 ALL)。 PRIVATE 选项的值为 PRIVATE,PUBLIC 选项的值为 PUBLIC,ALL 的值为空字符串 ''。 当我尝试使用空字符串传递搜索 api 时,后端没有得到空字符串,但由于某种原因他将其拦截为 null。 这是我的前端代码 HTML / Vue.js

      <div class="col-sm-4 col-12">
    <label for="statut" class="form-label">Statut</label>
    <select name="statut" class="form-select" id="statut" v-model="selectedVisibility">
      <option value="PRIVATE">PRIVATE</option>
      <option value="PUBLIC">PUBLIC</option>
      <option value="">ALL</option>
    </select>
  </div>

这是我的 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 })

}
  },

当我传递空字符串 '' 的 ALL 值时,Spring Boot 默认将其设为 null 而不是保留该值。我可能会在 ( if value is null ) value = ''; 中添加一个条件,但是这会花费太多时间,因为我有很多搜索工具,所以,有没有另一种方法可以让它取空字符串的值而不是 null? 这是后端代码:

     @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);
    }

findByAtLeastOne 只是一种进行搜索的方法,但在到达该部分之前,该值已经变为 null

如果您的 statutString.

,您可以像在 @RequestParam(value = "status", required = false, defaultValue = "") 中那样使用 defaultValue 参数

但是从你的代码看来它是一个 enum (EStatus) 并且 enums defaultValue 必须包含一个可以传递给的常量表达式Enum.valueOf()。如果是这种情况,即使您指定 defaultValue = "",该值仍将是 null。 (显然,如果您有默认的 enum 值(如“ALL”)并使用 defaultValue = "ALL",它会起作用)。

否则,您将不得不在控制器或存储库方法中手动处理 null 值。