[英]Combine two methods into one
What's the best method for converting these two methods into one? 将这两种方法转换为一种的最佳方法是什么?
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> dbStatus() {
return statusService.isDbAlive() ? RESPONSE_DB_UP : RESPONSE_DB_DOWN;
}
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> appStatus() throws IOException {
return statusService.isAppAlive() ? RESPONSE_APP_UP : RESPONSE_APP_DOWN;
}
Could I return a List
of ResponseEntity<String>
? 我可以返回一个
List
的ResponseEntity<String>
?
You would have to return something like JSON showing the result of both checks. 您将必须返回类似JSON的内容,以显示两次检查的结果。 For example
例如
{"isAppAlive" : true, "isDbAlive": false}
You can build this JSON string yourself 您可以自己构建此JSON字符串
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<String> getStatus() throws IOException {
String json = "{\"isAppAlive\":" + statusService.isAppAlive() + ",\"isDbAlive\""+ statusService.isDbAlive() +"}";
return new ResponseEntity<String>(json, HttpStatus.OK);
}
Or build a class like 或建立一个像
public class Status {
// use private and getters/setters
public boolean isAppAlive;
public boolean isDbAlive;
}
and let Spring serialize the Status
object you create 让Spring序列化您创建的
Status
对象
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Status> getStatus() throws IOException {
Status status = new Status();
status.isAppAlive = statusService.isAppAlive();
status.isDbAlive = statusService.isDbAlive();
return new ResponseEntity<Status>(status, HttpStatus.OK);
}
You can always make statusService
have a method getStatus()
that returns a Status
object that already has its fields set already. 您始终可以使
statusService
具有方法getStatus()
,该方法返回已设置其字段的Status
对象。
Your client can then parse the JSON and check each status. 然后,您的客户端可以解析JSON并检查每个状态。
@RequestMapping(value = "/testurl",
method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView dbStatus() {
List<String> status = new ArrayList<String>();
status.add (statusService.isDbAlive() );
status.add (statusService.isAppAlive() );
ModelMap modelMap = new ModelMap();
modelMap.put("status ", status );
return new ModelAndView("statuspage.jsp", modelMap);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.