springmvc(五)---全局异常处理器

来源:互联网 发布:新浪微博名人个性域名 编辑:程序博客网 时间:2024/06/05 03:46

一、全局异常处理器

1、异常如何来?

系统遇到异常,在程序中手动抛出,dao抛给service、service给controller、controller抛给前端控制器,前端控制器调用全局异常处理器。

2、处理思路?

解析出异常类型,如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示;如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误“)

二、配置全局异常处理器的小实例

1、自定义异常

package top.einino.exception;

public class UserException extends Exception {
//异常信息
public String message;
 public UserException(String message){
        super(message);
        this.message = message;
    }
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}

}

2、全局异常处理器

package top.einino.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class UserExceptionHandler implements HandlerExceptionResolver{

@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
        UserException userException = null;
        if(ex instanceof UserException){
            userException = (UserException)ex;
        }else{
            userException = new UserException("未知错误");
        }

        String message = userException.getMessage();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", message);
        modelAndView.setViewName("error");
        return modelAndView;
}

}

3、springmvc.xml配置全局异常处理器

<!-- 配置全局异常处理器,只要实现HandlerExceptionResolver -->
<bean class="top.einino.exception.UserExceptionHandler"></bean>

4、controller层抛出异常

@RequestMapping("/editUser.action")
public String editUser(int id) throws UserException{
User user = null;
        //error.jsp显示未知错误
        //int i = 10/0;
if(user == null){
    //error.jsp显示个性的用户不存在
            throw new UserException("修改的用户不存在");
}

return "user/editUser";
}

5、错误显示界面


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>错误提示</title>
</head>
<body>
${message }
</body>
</html>

三、小结

本博文介绍了springmvc的全局异常处理器,其实质是要实现HandlerExceptionResolver,在实现方法中将错误信息提取出来并显示到error.jsp中,提示用户。

如果有疑问或者对本博文有何看法或建议或有问题的,欢迎评论,恳请指正!

0 0
原创粉丝点击