package com.boot.springmvc.advice;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice //1
public class ExceptionHandlerAdvice {
@ExceptionHandler(value = Exception.class)//2
public ModelAndView exception(Exception exception, WebRequest request) {
ModelAndView modelAndView = new ModelAndView("error");// error页面
modelAndView.addObject("errorMessage", exception.getMessage());
return modelAndView;
}
@ModelAttribute //3
public void addAttributes(Model model) {
model.addAttribute("msg", "额外信息"); //3
}
@InitBinder //4
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.setDisallowedFields("id"); //5
}
}
一:ExceptionHandlerAdvice类
4.通过@InitBinder注解定制WebDataBinder。(5.这里表示过滤掉id)
二:抛出异常演示
package com.boot.springmvc.web.ch2;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.boot.springmvc.domain.DemoObj;
@Controller
public class AdviceController {
@RequestMapping("/advice")
public String getSomething(@ModelAttribute("msg") String msg,DemoObj obj){//1
System.out.println("//演示@ModelAttribute");
throw new IllegalArgumentException("非常抱歉,参数有误/"+"来自@ModelAttribute:"+ msg);
}
}
三:异常页面展示
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
@ControllerAdvice Demo
${errorMessage}
结果:
全局的@ModelAttribute,@RequestMapping都可以获取
webDataBinder.setDisallowedFields("id"); //过滤id属性