SpringBoot整合WEB开发--(四)@ControllerAdvice,
分享于 点击 43272 次 点评:219
SpringBoot整合WEB开发--(四)@ControllerAdvice,
1.全局异常处理:
@ControllerAdvice处理全局数据,一般搭配@ExceptionHandler,@ModelAttribute以及@InitBinder使用。
@ControllerAdvice public class CustomExceptionHandler { @ExceptionHandler(MaxUploadSizeExceededException.class) public ModelAndView uploadException(MaxUploadSizeExceededException e) throws IOException { ModelAndView mv = new ModelAndView(); mv.addObject("msg", "上传文件大小超出限制!"); mv.setViewName("error"); return mv; } @ExceptionHandler(Exception.class) public void myexce(Exception e) { System.out.println("myexce>>>"+e.getMessage()); } }
2.添加全局数据:
@ModelAttribute配置全局数据,如下:key="info",value="map",
@ControllerAdvice public class GlobalConfig { @ModelAttribute(value = "info") public Map<String,String> userInfo() { HashMap<String, String> map = new HashMap<>(); map.put("username", "罗贯中"); map.put("gender", "男"); return map; } }
controller:
@GetMapping("/hello") @ResponseBody public void hello(Model model) { Map<String, Object> map = model.asMap(); //获取到全局数据key="info",value="map" Set<String> keySet = map.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); Object value = map.get(key); System.out.println(key + ">>>>>" + value); } }
http://localhost:8080/hello
3.请求参数预处理:
@ControllerAdvice结合@InitBinder可以实现请求参数预处理,即将表单中的数据绑定到实体类上时进行一些额外的处理。
问题:两个实体类,属性名字一致,传递参数时参数无法指定具体的一个,如下,两个实体类都有name属性,url拼接时出现问题。
demo:
实体类:
public class Author { private String name; private int age; 。。。。。。。。 } public class Book { private String name; private String author; 。。。。。。。。。。 }
@ControllerAdvice public class GlobalConfig {
@InitBinder("b")
public void init(WebDataBinder binder) {
binder.setFieldDefaultPrefix("b."); //处理@ModelAttribute("b")的参数
}
@InitBinder("a")
public void init2(WebDataBinder binder) {
binder.setFieldDefaultPrefix("a."); //处理@ModelAttribute("a")的参数
}
}
controller:
@GetMapping("/book") @ResponseBody public String book(@ModelAttribute("b") Book book, @ModelAttribute("a") Author author) { return book.toString() + ">>>" + author.toString(); }
相关文章
- 暂无相关文章
用户点评