You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JHipster无效值未检测:布尔值转字符串未触发参数校验

JHipster自动生成API的请求校验异常问题

我用JHipster自动生成的代码开发API时碰到了请求校验问题:定义的Movie Schema里明确要求title是字符串类型,但测试时传入布尔值true,系统不仅没检测到类型不匹配,还自动把布尔值转成了字符串"true",导致测试用例失败。奇怪的是,把title设为null时能正常触发必填项校验错误。

Movie Schema定义

movie:
      type: object
      properties:
        title:
          type: string
        director:
          type: string
        description:
          type: string
        rating:
          type: number
          maximum: 5
          minimum: 0
      example:
        title: The Dark Knight
        director: Christopher Nolan
        description: |
          When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice. 
        rating: 4.5
      required:
        - title
        - director
        - description
        - rating

测试请求体

{
    "director":"director",
    "title":true,
    "description":"description",
    "rating":4.5
}

调试发现的问题

调试后发现JHipster默认的ObjectMapper把布尔值解析成了字符串类型,而非触发类型不匹配的校验。我没修改过JHipster自动生成的代码,这只是个原型开发用的简单API,对应的委托类代码如下:

@Service
@Slf4j
@RequiredArgsConstructor
public class Api implements DefaultApiDelegate {
    static ObjectMapper mapper = new ObjectMapper();
    private final NativeWebRequest nativeWebRequest = null;
    static List<Movie> movies = null;
    private final ApplicationProperties applicationProperties = new ApplicationProperties();

    @Value("${jhipster.clientApp.name}") 
    private String applicationName;
 
    @Override
    public Optional<NativeWebRequest> getRequest() {
        return Optional.ofNullable(nativeWebRequest);
    }

    @Override
    public ResponseEntity<List<Movie>> allMovieGet() {
        getMovies();
        System.out.println("GET request");
        ResponseEntity<List<Movie>> res = new ResponseEntity<List<Movie>>(movies.subList(0, 24), HttpStatus.OK);;
        
        return res;
    }
    
    @Override   
    public ResponseEntity<Movie> addMoviePost(Movie movie){
        getMovies();
        System.out.println(movie.toString());
        System.out.println(movie.getTitle().getClass());
        movies.add(movie);
        ResponseEntity<Movie> res = new ResponseEntity<Movie>(movies.get(movies.size()-1), HttpStatus.CREATED);
        return res;
    }

    public void getMovies(){
        try {
            movies = mapper.readValue(new File("src/main/resources/movies.json"), new TypeReference<List<Movie>>(){});
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

解决办法

1. 配置ObjectMapper禁用自动类型转换

JHipster默认的ObjectMapper开启了自动类型转换,需要修改配置强制严格类型校验:

在配置类中添加ObjectMapper的自定义配置:

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    // 禁用非字符串类型自动转为字符串的逻辑
    mapper.configure(DeserializationFeature.ACCEPT_STRING_FOR_NUMBERS, false);
    mapper.configure(DeserializationFeature.ACCEPT_BOOLEAN_AS_STRING, false);
    // 开启未知属性、无效子类型的校验失败机制
    mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.enable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
    return mapper;
}

2. 为Movie实体添加JSR-380校验注解

确保实体类上添加严格的类型与必填校验注解:

public class Movie {
    @NotBlank(message = "title必须为非空字符串")
    private String title;

    @NotBlank(message = "director必须为非空字符串")
    private String director;

    @NotBlank(message = "description必须为非空字符串")
    private String description;

    @NotNull(message = "rating不能为空")
    @DecimalMin(value = "0.0", message = "rating取值范围为0-5")
    @DecimalMax(value = "5.0", message = "rating取值范围为0-5")
    private BigDecimal rating;

    // getter、setter、toString方法
}

3. 在API方法参数前添加@Valid触发校验

修改addMoviePost方法,在参数前加上@Valid注解,强制触发Bean Validation校验:

@Override   
public ResponseEntity<Movie> addMoviePost(@Valid Movie movie){
    // 原有业务逻辑
}

完成以上配置后,当传入布尔值true作为title时,系统会直接抛出类型不匹配的异常并返回错误信息,不再自动转换类型。

内容的提问来源于stack exchange,提问作者user20881192

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 18:25:48