public class ResponseEntityFactory { private enum ResponseStatus { SUCCESS, FAIL, ERROR } public static ResponseEntity success (String message, Object data) { return getResponseEntity(HttpStatus.OK, ResponseStatus.SUCCESS, message, data, null); } /* ADDITIONAL SUCCESS, FAIL, ERROR FACTORY METHODS */ private static ResponseEntity getResponseEntity(HttpStatus httpStatus, ResponseStatus responseStatus, String message, Object data, HttpHeaders headers) { if (httpStatus == null) throw new IllegalArgumentException("HttpStatus cannot be null"); if (responseStatus == null) throw new IllegalArgumentException("ResponseStatus cannot be null"); JsonResponse jsonResponse = new JsonResponse(responseStatus, message, data); return new ResponseEntity(jsonResponse, headers, httpStatus); } private static class JsonResponse { private ResponseStatus status; private String message; private Object data; public JsonResponse(ResponseStatus status, String message, Object data) { if (status == null) throw new IllegalArgumentException("ResponseStatus cannot be null"); this.status = status; this.message = message; this.data = data; } public ResponseStatus getStatus() { return status; } public void setStatus(ResponseStatus status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } }
示例控制器。java
@Controller
@RequestMapping(value = "/example")
public class ExampleController {
@Autowire
private UserService userService;
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUsers() {
List<User> users = userService.getAllUsers();
return AjaxResponseFactory.success("Found users", userList);
}
@RequestMapping(value = "/active/{id}" method = RequestMethod.GET)
public ResponseEntity isUserActive(long userId) {
boolean = userService.isUserActive(userId);
return AjaxResponseFactory.success(null, boolean);
}
}
标签:status,Http,包装,ResponseStatus,ResponseEntity,message,null,data,public
From: https://www.cnblogs.com/yhc-love-cl/p/17188266.html