@ControllerAdviece是一个全局组数据处理组件,主要用来处理全局数据。一般搭配@ExceptionHandler、@ModelAttribute以及@InitBinder使用
处理全局异常
搭配@ExceptionHandler注解使用
@ControllerAdvice //当系统启动时,该类就会被扫描到容器中
public class CustomExceptionHandler {
@ExceptionHandler (MaxUploadSizeExceededException.class) //其中定义的MaxUploadSizeExceededException.class表明该方法用来处理所有类型的异常/如果想让该方法处理所有类型的异常,只需将MaxUploadSizeExceededException 改为Exception即可
public void uploadException(MaxUploadSizeExceededException e, HttpServletResponse resp)throws IOException{
resp.setContentType("text/html;charset=utf-8");
PrintWriter out =resp.getWriter();
out.write("上传文件大小超出限制");
out.flush();
out.close();
}
}
添加全局数据
搭配@ModelAttribute 注解使用
@ControllerAdvice
public class Gloadbal {
@ModelAttribute(value="abc") //value 时返回数据的key
public String ha(){
return "hahaha"; //返回数据的value是返回方法的值
}
}
在任意的控制器中都能根据Model属性访问上面定义的数据
@GetMapping("/globaldata")
public String jfos(Model model){
System.out.println(model);
Map a=model.asMap();
System.out.println(a.get("abc"));
return "haa";
}