Spring MVC:如何在响应实体主体中返回不同类型的

2022-09-02 23:51:21

在我的请求处理程序中,我想做一些验证,根据验证检查的结果,我将返回不同的响应(成功/错误)。因此,我为响应对象创建了一个抽象类,并为失败案例和成功案例创建了2个子类。代码看起来像这样,但它没有编译,抱怨错误Response和succesresponse无法转换为AbstractResponse。

我对Java Generic和Spring MVC很陌生,所以我不知道有一个简单的方法来解决这个问题。

@ResponseBody ResponseEntity<AbstractResponse> createUser(@RequestBody String requestBody) {
    if(!valid(requestBody) {
        ErrorResponse errResponse = new ErrorResponse();
        //populate with error information
        return new ResponseEntity<> (errResponse, HTTPStatus.BAD_REQUEST);
    }
    createUser();
    CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
    // populate with more info
    return new ResponseEntity<> (successResponse, HTTPSatus.OK);
}

答案 1

这里有两个问题:

  • 必须更改返回类型以匹配两个响应子类ResponseEntity<? extends AbstractResponse>

  • 实例化响应实体时,不能使用必须指定要使用的响应类的简化语法<>new ResponseEntity<ErrorResponse> (errResponse, HTTPStatus.BAD_REQUEST);

     @ResponseBody ResponseEntity<? extends AbstractResponse> createUser(@RequestBody String requestBody) {
         if(!valid(requestBody) {
             ErrorResponse errResponse = new ErrorResponse();
             //populate with error information
             return new ResponseEntity<ErrorResponse> (errResponse, HTTPStatus.BAD_REQUEST);
         }
         createUser();
         CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
         // populate with more info
         return new ResponseEntity<CreateUserSuccessResponse> (successResponse, HTTPStatus.OK);
     }
    

答案 2

另一种方法是使用错误处理程序

@ResponseBody ResponseEntity<CreateUserSuccessResponse> createUser(@RequestBody String requestBody) throws UserCreationException {
    if(!valid(requestBody) {
        throw new UserCreationException(/* ... */)
    }
    createUser();
    CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse();
    // populate with more info
    return new ResponseEntity<CreateUserSuccessResponse> (successResponse, HTTPSatus.OK);
}

public static class UserCreationException extends Exception {
    // define error information here
}

@ExceptionHandler(UserCreationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse handle(UserCreationException e) {
    ErrorResponse errResponse = new ErrorResponse();
    //populate with error information from the exception
    return errResponse;
}

这种方法允许返回任何类型的对象的可能性,因此不再需要成功案例和错误案例(甚至案例)的抽象超类。


推荐