相当于oracle的异常问题提示。当接收到异常提示后,就不会再继续下一步。
@ExceptionHandler是一个全局异常控制器,更人性化的将异常输出给用户。
相关注解方法:@ExceptionHandler是一个全局异常控制器用于方法上
@InitBinder // 4 注解定webDataBinder用来绑定前台请求参数到Model上去
@InitBinder // 4 注解定webDataBinder
public voidinitBinder(WebDataBinder webDataBinder) {
webDataBinder.setDisallowedFields("id"); //5
}
@ModelAttribute //3 绑定键值到Model里,此处是让全局的@RequestMapping都能获取这键值对
public void addAttribute(Model model) {
model.addAttribute("msg","额外信息");//3
model.addAttribute("MathError","算法错误!");//3
model.addAttribute("other","其他错误信息");//3
}
展示代码如下:做一个对int数据的判断,分别给出对应的异常
package com.example.Spring.Boot1.ControllerAdvice;
import javax.servlet.http.HttpServletRequest;
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.servlet.ModelAndView;
@ControllerAdvice //1 这是一个控制器建言
public class ExceptionHandleAdvice {
//public static final String DEFAULT_ERROR_VIEW = "error";
@ExceptionHandler(value=Exception.class) //2 在此处定义一个全局处理,通过@ExceptionHandler的value属性可以过滤拦截的条件,这里是拦截所有的exception
public ModelAndView exception(Exception exception,HttpServletRequest request) {
ModelAndView andView=new ModelAndView();
andView.addObject("exception", exception);
System.out.println(exception);
andView.addObject("url", request.getRequestURL());
//andView.setViewName(DEFAULT_ERROR_VIEW); //传递到界面上,这是界面的名字
andView.setViewName("error"); //html的名字
return andView;
}
@ModelAttribute //3 将键值对添加到全局,所有的注解RequestMapping的方法可以获取这键值
public void addAttribute(Model model) {
model.addAttribute("msg", "额外信息");//3
model.addAttribute("MathError", "算法错误!");//3
model.addAttribute("other", "其他错误信息");//3
}
@InitBinder // 4 注解定webDataBinder
public void initBinder(WebDataBinder webDataBinder) {
//webDataBinder.setDisallowedFields("id"); //5
}
}
类2:具体操作,返回异常
package com.example.Spring.Boot1.ControllerAdvice;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class adviceController {
int a =3;
@RequestMapping("/hello")
public String hello(@ModelAttribute("msg") String msg, @ModelAttribute("MathError") String MathError,
@ModelAttribute("other") String other) throws Exception {
if (a == 1) {
throw new Exception(msg + "非常抱歉,参数有误/" + "来自@ModelAttribute:");
} else if (a == 2) {
throw new Exception(MathError + ": a不等于2");
}
else{
throw new Exception( " a等于3");
}
}
}
HTML代码:
统一异常处理
Error Handler
地址栏http://localhost:8011/hello
地址栏最后界面出现的结果是: