SpringMVC(十二)自定义异常处理器 HandlerExceptionResolver(接口)

自定义异常处理器和系统异常处理器的提升版可以实现相同的功能,但是使用的方法不同,自定义异常处理器可以不用在配置文件中配置name多东西,只需要一个异常处理器就可以,有需要的话也可以配置一个视图解析器,但是包扫描器是必须的

先定义一个类让他实现 HandlerExceptionResolver 接口

package demo14SelfException;

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

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

/**
 * Created by mycom on 2018/3/30.
 */
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
    /**
     * 解析异常
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param ex
     * @return
     */
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        ModelAndView mv=new ModelAndView();
        mv.addObject("ex",ex);//保存的数据,在页面上用EL表达式展示错误信息
        //如果不满足下面两个条件,就走这个默认的页面
        mv.setViewName("error");
        //判断异常类型  是用户名异常就到用户名异常类中是年龄异常就到年龄异常类中
        if(ex instanceof NameException){
            //指定特定的异常页面
            mv.setViewName("nameException");
        }
        if(ex instanceof AgeException){
            mv.setViewName("ageException");
        }
        //最后返回ModelAndView
        return mv;
    }
}

在这个类中需要两个异常类NameException和AgeException

package demo14SelfException;

/**
 * Created by mycom on 2018/3/30.
 */
public class NameException extends Exception {
    public NameException() {
        super();
    }

    public NameException(String message) {
        super(message);
    }
}
package demo14SelfException;

/**
 * Created by mycom on 2018/3/30.
 */
public class AgeException extends Exception {
    public AgeException() {
        super();
    }

    public AgeException(String message) {
        super(message);
    }
}

在异常控制器中

package demo14SelfException;

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

/**
 * Created by mycom on 2018/3/30.
 */
@Controller
public class ExceptionController {

    @RequestMapping("/first")
    public String doFirst(String name,int age) throws Exception {
        //根据异常的不同返回不同的页面
        if(!name.equals("admin")){
            //如果用户名输入不正确,走姓名异常这个类
            throw new NameException("用户名异常");
        }
        if(age>60){
            throw new AgeException("年龄不符合");
        }
        //最后成功的话就走成功的页面
        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="demo14SelfException"></context:component-scan>

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

    <!--异常处理器  自己定义的类-->
    <bean class="demo14SelfException.MyHandlerExceptionResolver"></bean>



</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>
<form action="${pageContext.request.contextPath}/first" method="post">
    用户名:<input type="text" name="name" value="${name}"/>
    年龄:<input type="text" name="age" value="${age}"/>
    出生日期:<input type="text" name="birthday"/>
    <input type="submit" value="提交">
</form>
</body>
</html>

普通错误页面

<%--
  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>

成功页面

<%--
  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>
  ${username}登录成功!
</body>
</html>

姓名错误

<%--
  Created by IntelliJ IDEA.
  User: mycom
  Date: 2018/3/30
  Time: 12:35
  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>
姓名不符合 ${ex.message}
</body>
</html>

年龄错误

<%--
  Created by IntelliJ IDEA.
  User: mycom
  Date: 2018/3/30
  Time: 12:35
  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>
年龄不符合 ${ex.message}
</body>
</html>
原文地址:https://www.cnblogs.com/my-123/p/8681132.html