Spring MVC:如何在ResponseEntity体中返回不同的类型
在我的请求处理程序中,我想做一些validation,并根据validation检查的结果,我将返回不同的响应(成功/错误)。 因此,我为响应对象创建了一个抽象类,并为失败案例和成功案例创建了2个子类。 代码看起来像这样,但它不编译,抱怨errorResponse和successResponse无法转换为AbstractResponse。
我是Java Generic和Spring MVC的新手,所以我不知道解决这个问题的简单方法。
@ResponseBody ResponseEntity 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); }
这里有两个问题:
- 您的返回类型必须更改为匹配两个响应子类
ResponseEntity extends AbstractResponse>
ResponseEntity extends AbstractResponse>
-
当您实例化ResponseEntity时,您不能使用简化的<>语法来指定您将使用哪个响应类
new ResponseEntity
(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
(errResponse, HTTPStatus.BAD_REQUEST); } createUser(); CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse(); // populate with more info return new ResponseEntity (successResponse, HTTPSatus.OK); }
另一种方法是使用error handling程序
@ResponseBody ResponseEntity createUser(@RequestBody String requestBody) throws UserCreationException { if(!valid(requestBody) { throw new UserCreationException(/* ... */) } createUser(); CreateUserSuccessResponse successResponse = new CreateUserSuccessResponse(); // populate with more info return new ResponseEntity (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; }
这种方法可以返回任何类型的对象,因此不再需要成功案例和错误案例(甚至案例)的抽象超类。