如何在Spring MVC或Spring-Boot中返回不同类型的ResponseEntity

我使用Spring MVC 4(或Spring-Boot)编写了简单的rest应用程序。 在控制器中我返回ResponseEntity 。 但在某些情况下,我想给JSON成功,如果有validation错误,我想给出错误JSON。 目前成功和错误响应完全不同,所以我创建了2个错误和成功的类。 在控制器中,如果内部逻辑正常,我想返回ResponseEntity 。 否则我想返回ResponseEntity 。 有没有办法做到这一点。

SuccessError是我用来表示成功和错误响应的2个类。

您可以通过以下方式实现,以在同一请求映射方法上返回SuccessError

 public ResponseEntity method() { boolean b = // some logic if (b) return new ResponseEntity(HttpStatus.OK); else return new ResponseEntity(HttpStatus.CONFLICT); //appropriate error code } 

我建议使用Spring的@ControllerAdvice来处理validation错误。 阅读本指南以获得一个很好的介绍,从名为“Spring Boot Error Handling”的部分开始。 有关深入讨论,Spring.io博客中有一篇文章于2018年4月更新。

关于其工作原理的简要总结:

  • 您的控制器方法应该只返回ResponseEntity 。 它不负责返回错误或exception响应。
  • 您将实现一个处理所有控制器exception的类。 该类将使用@ControllerAdvice进行注释
  • 此控制器建议类将包含使用@ExceptionHandler注释的方法
  • 每个exception处理程序方法都将配置为处理一个或多个exception类型。 您可以在这些方法中指定错误的响应类型
  • 对于您的示例,您将声明(在控制器通知类中)validation错误的exception处理程序方法。 返回类型是ResponseEntity

使用此方法,您只需要在API中的所有端点的一个位置实现控制器exception处理。 它还使您的API可以轻松地在所有端点上具有统一的exception响应结构。 这简化了客户的exception处理。

可以在不使用generics的情况下返回ResponseEntity ,如下所示,

 public ResponseEntity method() { boolean isValid = // some logic if (isValid){ return new ResponseEntity(new Success(), HttpStatus.OK); } else{ return new ResponseEntity(new Error(), HttpStatus.BAD_REQUEST); } } 

我不确定但是,我认为你可以使用@ResponseEntity@ResponseBody并发送2个不同的是成功,第二个是错误消息,如:

 @RequestMapping(value ="/book2", produces =MediaType.APPLICATION_JSON_VALUE ) @ResponseBody Book bookInfo2() { Book book = new Book(); book.setBookName("Ramcharitmanas"); book.setWriter("TulasiDas"); return book; } @RequestMapping(value ="/book3", produces =MediaType.APPLICATION_JSON_VALUE ) public ResponseEntity bookInfo3() { Book book = new Book(); book.setBookName("Ramayan"); book.setWriter("Valmiki"); return ResponseEntity.accepted().body(book); } 

有关详细信息,请参阅: http : //www.concretepage.com/spring-4/spring-4-mvc-jsonp-example-with-rest-responsebody-responseentity

这是我会这样做的方式:

 public ResponseEntity < ? extends BaseResponse > message(@PathVariable String player) { //REST Endpoint. try { Integer.parseInt(player); return new ResponseEntity < ErrorResponse > (new ErrorResponse("111", "player is not found"), HttpStatus.BAD_REQUEST); } catch (Exception e) { } Message msg = new Message(player, "Hello " + player); return new ResponseEntity < Message > (msg, HttpStatus.OK); } @RequestMapping(value = "/getAll/{player}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity < List < ? extends BaseResponse >> messageAll(@PathVariable String player) { //REST Endpoint. try { Integer.parseInt(player); List < ErrorResponse > errs = new ArrayList < ErrorResponse > (); errs.add(new ErrorResponse("111", "player is not found")); return new ResponseEntity < List < ? extends BaseResponse >> (errs, HttpStatus.BAD_REQUEST); } catch (Exception e) { } Message msg = new Message(player, "Hello " + player); List < Message > msgList = new ArrayList < Message > (); msgList.add(msg); return new ResponseEntity < List < ? extends BaseResponse >> (msgList, HttpStatus.OK); } 

我过去经常使用这样的课程。 当消息中设置了错误消息时出现错误,将设置statusCode 。 数据在适当时存储在Map或List中。

 /** * */ package com.test.presentation.response; import java.util.Collection; import java.util.Map; /** * A simple POJO to send JSON response to ajax requests. This POJO enables us to * send messages and error codes with the actual objects in the application. * * */ @SuppressWarnings("rawtypes") public class GenericResponse { /** * An array that contains the actual objects */ private Collection rows; /** * An Map that contains the actual objects */ private Map mapData; /** * A String containing error code. Set to 1 if there is an error */ private int statusCode = 0; /** * A String containing error message. */ private String message; /** * An array that contains the actual objects * * @return the rows */ public Collection getRows() { return rows; } /** * An array that contains the actual objects * * @param rows * the rows to set */ public void setRows(Collection rows) { this.rows = rows; } /** * An Map that contains the actual objects * * @return the mapData */ public Map getMapData() { return mapData; } /** * An Map that contains the actual objects * * @param mapData * the mapData to set */ public void setMapData(Map mapData) { this.mapData = mapData; } /** * A String containing error code. * * @return the errorCode */ public int getStatusCode() { return statusCode; } /** * A String containing error code. * * @param errorCode * the errorCode to set */ public void setStatusCode(int errorCode) { this.statusCode = errorCode; } /** * A String containing error message. * * @return the errorMessage */ public String getMessage() { return message; } /** * A String containing error message. * * @param errorMessage * the errorMessage to set */ public void setMessage(String errorMessage) { this.message = errorMessage; } 

}

希望这可以帮助。

您也可以像这样实现在同一个请求映射方法上返回Success和Error,使用Object类(java中每个类的Parent类): –

 public ResponseEntity< Object> method() { boolean b = // logic here if (b) return new ResponseEntity< Object>(HttpStatus.OK); else return new ResponseEntity< Object>(HttpStatus.CONFLICT); //appropriate error code } 

您可以使用带有对象或字符串的地图,如下图所示:

 @RequestMapping(value = "/path", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity> getData(){ Map response = new HashMap(); boolean isValid = // some logic if (isValid){ response.put("ok", "success saving data"); return ResponseEntity.accepted().body(response); } else{ response.put("error", "an error expected on processing file"); return ResponseEntity.badRequest().body(response); } }