一、Controller跨域jsonp格式返回
/**
* JSONP支持
*/
@ControllerAdvice(basePackages = "com.kugou.fanxing.romantic.controller")
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice{
public JsonpAdvice() {
super("jsonCallBack","jsonpcallback");
}
}
二、Controller全局异常统一拦截
/**
* 统一异常拦截
*/
@ControllerAdvice(assignableTypes = {AController.class})
public class MobileExceptionHandler {
@ExceptionHandler(value = BizException.class)
@ResponseBody
public Result jsonErrorHandler(HttpServletRequest req, BizException e) {
return Response.failed(e);
}
@ExceptionHandler(value = {Exception.class})
@ResponseBody
public Result jsonErrorHandler(HttpServletRequest req, Exception e) {
return Response.failed(ErrCode.UNKNOWN_ERROR);
}
}
三、Controller全局共享数据
@ControllerAdvice
public class GlobalShareDataHandler{
/**
* 全局数据绑定,所有controller都可以通过Model对象拿到这个map
* Map<String,Object> map = model.asMap();
* System.out.println(map);
* @return
*/
@ModelAttribute(name = "md")
public Map<String,Object> mydata() {
HashMap<String, Object> map = new HashMap<>();
map.put("age", 99);
map.put("gender", "男");
return map;
}
}
四、Controller全局输入参数预处理(加一个前缀,避免参数重名)
/**
* 输入参数b的每一个字段名前加上前缀b.
*/
@ControllerAdvice
public class GlobalBinderHandler{
@InitBinder("b")
public void b(WebDataBinder binder) {
binder.setFieldDefaultPrefix("b.");
}
}
@RestController
public class Hello {
@PostMapping("/book")
public void addBook(@ModelAttribute("b") Book book, @ModelAttribute("a") Author author) {
System.out.println(book);
System.out.println(author);
}
}