SpringMVC:异常处理

SpringMVC中的异常

系统中异常包括两类:预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息, 后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。 系统的 dao、service、controller 出现都通过 throws Exception 向上抛出,最后由 springmvc 前端 控制器交由异常处理器进行异常处理,
如下图:
在这里插入图片描述
异常处理举例:
自定义异常类SysException

package ypy.exception;

public class SysException extends Exception {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SysException(String message) {
        this.message = message;
    }

    public String toString() {
        return "SysException{" +
                "message='" + message + '\'' +
                '}';
    }
}

错误页面error.jsp

<%--
  Created by IntelliJ IDEA.
  User: ypy
  Date: 2020/3/25
  Time: 9:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>
        ${errorMsg}
    </h3>
</body>
</html>

自定义异常处理器SysExceptionResolver:

package ypy.exception;

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

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

public class SysExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        SysException e = null;
        //判断SysException是否是ex的实例化对象
        if(ex instanceof  SysException){
            e = (SysException)ex;
        }else {
            e = new SysException("系统正在维护。");
        }
        ModelAndView mv = new ModelAndView();
        //从处理函数testException中获得 throw new SysException("运算出错!"); 并使用e.getMessage()接收。
        mv.addObject("errorMsg",e.getMessage());
        //将接收的信息传递到error页面
        mv.setViewName("error");

        return mv;
    }
}

触发异常的链接处理函数testException:

package ypy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import ypy.domain.User;
import ypy.exception.SysException;

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/testString")
    public String testString(Model model){
        System.out.println("执行了 testString");
        User user = new User();
        user.setUsername("ypy");
        user.setPassword("123456");
        user.setAge(29);
        model.addAttribute("user",user);
        return "success";
    }

    @RequestMapping("/testException")
    public String testException()throws SysException{
        System.out.println("执行了 testException");
        try{
            int i = 1/0;
        }catch(Exception e){
            e.printStackTrace();
            throw new SysException("运算出错!");
        }
        return "success";
    }
}

xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 开启注解扫描 -->
    <context:component-scan base-package="ypy" />

    <!-- 配置视图解析器 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 前端控制器:哪些静态资源不拦截 -->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>

    <!-- 配置异常处理器 -->
    <bean id ="sysExceptionResolver" class = "ypy.exception.SysExceptionResolver" />

    <!-- 开启SpringMVC框架注解的支持 -->
    <mvc:annotation-driven />
</beans>

index页面:

<%--
  Created by IntelliJ IDEA.
  User: ypy
  Date: 2020/3/24
  Time: 9:38
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>

    <title>Title</title>

</head>
<body>
    <h2>Index页面</h2>
    <a href="user/testString">testString</a>
    <br>---------------------------------------<br>
    <a href="user/testException">自定义异常类</a>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值