spring3.2中新增了 @ControllerAdvice (等同于 @RestControllerAdvice + @ResponseBody 注解)
@ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类。
@ControllerAdvice 可以指定扫描范围。
@ControllerAdvice 约定了几种可行的返回类型。返回 String,表示跳到某个 view;返回 modelAndView;如果是直接返回 model 类的话,需要使用 @ResponseBody 进行 json 转换。
组合 @ExceptionHandler、@ModelAttribute 应用于被 @RequestMapping 注解的方法之上。
一、@RestControllerAdvice + @ExceptionHandler 捕获异常
package com.demo.handler;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
@RestControllerAdvice
public class GlobalDefaultExceptionHandler {
/**
* 捕获全局异常
* */
@ExceptionHandler(value = Exception.class)
public Map<String,Object> defaultExceptionHandler(){
Map<String,Object> map = new HashMap<String,Object>();
map.put("status",500);
map.put("message","系统异常");
return map;
}
}
package com.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/error")
public class ErrorController {
//http://localhost:8080/error/test
@RequestMapping("/test")
public String test(){
int i = 1/0;//抛出异常
return "success";
}
}
访问:http://localhost:8080/error/test
结果:
二、@ControllerAdvice + @ModelAttribute 把值绑定到Model中,使全局@RequestMapping可以获取到该值
package com.demo.handler;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalDefaultExceptionHandler {
/**
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值
* */
@ModelAttribute
public void addAttributes(Model model){
model.addAttribute("code","1010");
}
}
package com.demo.controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
/**
* http://localhost:8080/test/addAttribute
*
* 通过 @ModelAttribute 获取 @ControllerAdvice + @ModelAttribute 设置的值
* */
@RequestMapping("/addAttribute")
public String addAttribute(@ModelAttribute("code") String code){
return code;
}
}
访问:http://localhost:8080/test/addAttribute
结果: