异常的处理
1.自定义一个异常类MyException,将所有异常都统一捕获,变成唯一的异常,交给小总管
2.自定义一个异常处理类(处理异常 做转发 响应)
3.需要做一个配置,告知Spring帮我们将自定义的异常处理类管理起来
MyException
package exception;
/**
* 他是一个普通自定义异常
*/
public class MyException extends RuntimeException {
private String message;
public MyException(){}
public MyException(String message){
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
ExceptionResolver
package exception;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 这是一个自定义的异常处理类
* 原来的小总管不会帮我们处理
* 我们自己写类 自己定义处理规则
* 将这个类交个Spring管理
*/
@Component()
public class ExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
if(e instanceof MyException){
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("errorMessage",e.getMessage());
modelAndView.setViewName("error.jsp");
return modelAndView;
}
return null;
}
}
TestController
package controller;
import exception.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import service.UserService;
/**
* 分析现在有了框架之后的控制层
*
* 原来 现在
* 继承HttpServlet 没有继承关系
* 重写方法service/doXXX 方法随便写
* 方法内有两个参数 req resp 参数随便 普通变量 String int 对象变量 User 集合Map(RequestParam) 原生 req resp
* 方法还有两个异常 IO Servlet 没有异常抛出
* 方法返回值void 自己给响应 方法返回值void String(转发/重定向) 对象domain Map List(@ResponseBody)
*
* 耦合度几乎没有啦
* 所以在服务端想要带走一些数据 也不用原来的方式
* request.setAttribute 框架提供好的对象ModelAndView
* 普通的Map(接收参数--@RequestParam 带走信息--@ResponseBody)
* Model
* ModelMap
* ModelAndView
*/
@SessionAttributes("username")
@Controller
public class TestController {
@RequestMapping("testException.do")
public String testException(){
try{
String s=null;
s.length();
}catch (Exception e){
throw new MyException("出异常了!我自己弄出来测试的!");
}
return "welcome.jsp";
}
}