SpringMVC(十)系统异常处理器

系统异常处理器  SimpleMappingExceptionResolver

案例:一个处理器方法中出项异常,想让他跳转到一个自定义的错误页面

package demo12Exception;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by mycom on 2018/3/28.
 */
@Controller
public class SysExceptionController {

    @RequestMapping("/first")
    public String doFour(Model model){
        int num=5/0;
        return "success";
    }
}

在配置文件中需要一个异常处理器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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="demo12Exception"></context:component-scan>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--异常处理器-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error"></property>
        <property name="exceptionAttribute" value="ex"></property>
    </bean>
    <!--注解驱动--><!--<mvc:annotation-driven/>-->



</beans>

错误页面

<%--
  Created by IntelliJ IDEA.
  User: mycom
  Date: 2018/3/26
  Time: 11:57
  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>
<h2>出错了!!!!</h2>
${ex.message}
</body>
</html>
原文地址:https://www.cnblogs.com/my-123/p/8671578.html