SpringBoot中Controller参数与返回值的用法总结
作者:水能zai舟
这篇文章主要介绍了SpringBoot中Controller参数与返回值的用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
SpringBoot中Controller参数与返回值的用法
注解
类注解一律使用@RestController,方法注解是实际情况而定。
返回值
SpringBoot在实际后端开发中一般要为前端提供的数据是以json格式返回,其返回值类型我们大多采用以下方式
public Map<String, Object> function() { Map<String, Object> modelMap = new HashMap<>(); //...我们将从数据中中获取的值放入value modelMap.put("key", value); return modelMap; }
接收参数
普通参数
普通参数可以使用RESTful风格返回值,路由中注明{param},注意@PathVariable注解的使用
@RequestMapping("/route/{param}") public Map<String, Object> queryAreaById(@PathVariable("param") Integer param) { Map<String, Object> modelMap = new HashMap<>(); //...do something with param, save data in value modelMap.put("key", value); return modelMap; }
接收前端对象类型参数(json格式),对参数使用@RequestBody注解
@RequestMapping(value = "/route", method = RequestMethod.POST) public Map<String, Object> updateArea(@RequestBody XObject xObject) { Map<String, Object> modelMap = new HashMap<>(); //...do something with xObject, save data in value modelMap.put("key", value); return modelMap; }
springboot controller统一的接口返回值和异常处理
返回结果模型
@ApiModel("返回结果模型") public class JsonResult<T> implements Serializable { @ApiModelProperty("返回结果提示") private String msg = null; @ApiModelProperty("返回结果状态") private String status = null; @ApiModelProperty("返回结果数据") private T result = null; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public T getResult() { return result; } public void setResult(T result) { this.result = result; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public JsonResult(){ } public JsonResult(String status, String msg, T result){ this.status = status; this.msg = msg; this.result = result; } public JsonResult(String status, String msg){ this.status = status; this.msg = msg; } public JsonResult(ResultEnum resultEnum){ this.status = resultEnum.getStatus(); this.msg = resultEnum.getMsg(); } public JsonResult(ResultEnum resultEnum, T result){ this.status = resultEnum.getStatus(); this.msg = resultEnum.getMsg(); this.result = result; } }
返回编码枚举类模型
/** * @author code * @version 1.0 * @Date 2021/8/9 13:55 * @Description ${DESCRIPTION} */ public enum ResultEnum { SUCCESS("ok","调用成功"), ERROR("error","调用失败"); private String status; private String msg; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } ResultEnum(String status,String msg){ this.status = status; this.msg = msg; } }
返回结果工具类
/** * @author code * @version 1.0 * @Date 2021/7/22 15:50 * @Description ${DESCRIPTION} */ @Data @AllArgsConstructor @NoArgsConstructor @ApiModel("数据返回结果") public class ResultUtil<T> { public static JsonResult success(){ return new JsonResult(ResultEnum.SUCCESS); } public static JsonResult success(String msg){ return new JsonResult(ResultEnum.SUCCESS.getStatus(),msg); } public static <T> JsonResult<T> success(T result){ return new JsonResult<T>(ResultEnum.SUCCESS, result); } public static JsonResult error(){ return new JsonResult(ResultEnum.ERROR); } public static JsonResult error(String msg){ return new JsonResult(ResultEnum.ERROR.getStatus(),msg); } public static <T> JsonResult error(T result){ return new JsonResult<T>(ResultEnum.ERROR, result); } }
controller统一处理返回值
/** * @author code * @version 1.0 * @Date 2021/8/9 15:30 * @Description ${统一返回值} */ @RestControllerAdvice public class ControllerHandleAdvice implements ResponseBodyAdvice<Object> { private final static Logger logger = LoggerFactory.getLogger(ControllerHandleAdvice.class); @Override public boolean supports(MethodParameter methodParameter, Class<?extends HttpMessageConverter<?>> converterType){ return true; } @Override public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<?extends HttpMessageConverter<?>> converterType, ServerHttpRequest request, ServerHttpResponse response){ if(body instanceof String){ String msg = (String) body; return ResultUtil.success(msg); } else if(null == body) { } return body; } }
controller统一异常处理
/** * @author code * @version 1.0 * @Date 2021/8/9 10:56 * @Description ${统一异常返回值} */ @RestControllerAdvice public class ControllerExceptionHandleAdvice { private final static Logger logger = LoggerFactory.getLogger(ControllerExceptionHandleAdvice.class); @ExceptionHandler public JsonResult handler(HttpServletRequest request, HttpServletResponse response,Exception e){ logger.info("restful请求异常"); JsonResult jsonResult = new JsonResult(); if(e instanceof NullPointerException){ logger.error("空指针异常"); jsonResult.setStatus("error"); jsonResult.setResult("空指针异常"); }else if(e instanceof IllegalArgumentException){ logger.error("请求参数类型不匹配"); jsonResult.setStatus("error"); jsonResult.setResult("请求参数类型不匹配"); }else if(e instanceof SQLException){ logger.error("数据库访问异常"); jsonResult.setStatus("error"); jsonResult.setResult("数据库访问异常"); }else { logger.error("访问异常"+e.getMessage()); jsonResult.setStatus("error"); jsonResult.setResult("服务访问异常"+e.getMessage()); } return jsonResult; } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。