全局异常处理类的作用: 当controller发生异常,则有全局异常类来处理并执行相应的处理方法。
[1] 创建一个异常类: @ControllerAdvice注解package com.lrb.handler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class Handler1 {
//当发生RuntimeException就会触发该方法
@ExceptionHandler(value =RuntimeException.class)
public String error(){
return "error.jsp";
}
//当发生Exception就会触发该方法
@ExceptionHandler(value = Exception.class)
public String error2(){
return "error2.jsp";
}
//如果是ajax请求返回的应该是一个json数据。
@ExceptionHandler(value = RuntimeException.class)
@ResponseBody
public Map error3(){
Map map = new HashMap();
map.put("555","444");
map.put("5555","错误");
return map;
}
}
[2] 保证springmvc能够扫描到该类。



