美文网首页
SpringBoot @ControllerAdvice介绍

SpringBoot @ControllerAdvice介绍

作者: Fintecher | 来源:发表于2019-03-22 18:52 被阅读0次

    @ControllerAdvice可以全局扩展Controller的功能,里面有三个注解
    @ExceptionHandler、@InitBinder、@ModelAttribute,这三个注解都或被作用到@RequestMapping注解的方法上。

    @ExceptionHandler 全局异常处理

    @ControllerAdvice
    public class MyControllerAdvice {
        /**
         * 把值绑定到Model中,使全局@RequestMapping可以获取到该值
         * @param model
         */
        @ModelAttribute
        public void addAttributes(Model model) {
            model.addAttribute("author", "Magical Sam");
        }
    
        /**
         * 全局异常捕捉处理
         * @param ex
         * @return
         */
        @ResponseBody
        @ExceptionHandler(value = Exception.class)
        public Map errorHandler(Exception ex) {
            Map map = new HashMap();
            map.put("code", 100);
            map.put("msg", ex.getMessage());
            return map;
        }
    
    }
    

    @InitBinder 数据绑定,

    比如类型转换,

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
             binder.registerCustomEditor(Date.class, new MyDateEditor());
            binder.registerCustomEditor(Double.class, new DoubleEditor()); 
            binder.registerCustomEditor(Integer.class, new IntegerEditor());
        }
    private class MyDateEditor extends PropertyEditorSupport {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = null;
                try {
                    date = format.parse(text);
                } catch (ParseException e) {
                    format = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        date = format.parse(text);
                    } catch (ParseException e1) {
                    }
                }
                setValue(date);
            }
        }
        
        public class DoubleEditor extends PropertiesEditor  {    
            @Override    
            public void setAsText(String text) throws IllegalArgumentException {    
                if (text == null || text.equals("")) {    
                    text = "0";    
                }    
                setValue(Double.parseDouble(text));    
            }    
            
            @Override    
            public String getAsText() {    
                return getValue().toString();    
            }    
        }  
        
        public class IntegerEditor extends PropertiesEditor {    
            @Override    
            public void setAsText(String text) throws IllegalArgumentException {    
                if (text == null || text.equals("")) {    
                    text = "0";    
                }    
                setValue(Integer.parseInt(text));    
            }    
            
            @Override    
            public String getAsText() {    
                return getValue().toString();    
            }    
        } 
    

    映射对象

    @Controller  
    @RequestMapping("/test")  
    public class TestController {  
    
    @InitBinder  
    private void initBinder(WebDataBinder binder){  
        //由表单到JavaBean赋值过程中哪一个值不进行赋值  
        binder.setDisallowedFields("lastName");  
    } 
    
    // 绑定变量名字和属性,参数封装进类  
        @InitBinder("user")  
        public void initBinderUser(WebDataBinder binder) {  
            binder.setFieldDefaultPrefix("user.");  
        }  
        // 绑定变量名字和属性,参数封装进类  
        @InitBinder("addr")  
        public void initBinderAddr(WebDataBinder binder) {  
            binder.setFieldDefaultPrefix("addr.");  
        }  
          
          
        @RequestMapping("/test")  
        @ResponseBody  
        public Map<String,Object> test(HttpServletRequest request,@ModelAttribute("user") User user,@ModelAttribute("addr") Addr addr){  
            Map<String,Object> map=new HashMap<String,Object>();  
            map.put("user", user);  
            map.put("addr", addr);  
            return map;  
        } 
    

    @ModelAttribute 数据模型处理

    //或者 通过@ModelAttribute获取
    
    @RequestMapping("/home")
    public String home(@ModelAttribute("author") String author) {
        System.out.println(author);
    }
    

    参看:https://blog.csdn.net/hehe520347/article/details/80090916

    相关文章

      网友评论

          本文标题:SpringBoot @ControllerAdvice介绍

          本文链接:https://www.haomeiwen.com/subject/hxarvqtx.html