zoukankan      html  css  js  c++  java
  • SpringMVC异常

    创建控制器类

    package com.byzore.controller;
    
    import com.byzore.exception.AgeException;
    import com.byzore.exception.NameException;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    
    /**
     * 控制器
     */
    @Controller
    @RequestMapping("/first")
    public class FirstController {
        @RequestMapping("/firstRequest")
        public String firstRequest(){
            //模拟异常
            int result=5/0;
            return "index";
        }
        @RequestMapping("/secondRequest")
        public String secondRequest(String userName,Integer userAge) throws NameException, AgeException {
            if (!userName.equals("admin")){
                //手动创建一个Name异常
                throw new NameException("名称错误!!!");
            }
            if (userAge>80){
                //手动创建一个Age异常
                throw new AgeException("年龄太大,不符合要求");
            }
            return "index";
        }
    }

    一、系统异常处理

      1、配置applicationContext.xml文件

     <!--系统异常处理-->
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="defaultErrorView" value="error"/>
            <property name="exceptionAttribute" value="ex"/>
        </bean>

      2、创建NameException异常类

    package com.byzore.exception;
    
    public class NameException extends Exception{
        public NameException() {
        }
    
        public NameException(String message) {
            super(message);
        }
    }

      3、创建AgeException异常类

    package com.byzore.exception;
    
    /**
     * 一个类变为异常类
     */
    public class AgeException extends Exception{
        public AgeException() {
        }
    
        public AgeException(String message) {
            super(message);
        }
    }

      4、创建主页面index

    <%@ page contentType="text/html; charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <body>
    <h2>Hello World!</h2>
    </body>
    </html>

      5、创建登录页面login

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <head>
        <title>登录页面</title>
    </head>
    <body>
    <form action="/conter/conteRequest" method="post">
        姓名:<input type="text" name="userName">
        年龄:<input type="text" name="userAge">
        <input type="submit" value="提交">
    </form>
    </body>
    </html>

      6、创建ageError.jsp页面

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <head>
        <title>错误页面</title>
    </head>
    <body>
        ${ex.message}
        年龄不符合要求
    </body>
    </html>

      7、创建nameError.jsp页面

    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <head>
        <title>错误页面</title>
    </head>
    <body>
        ${ex.message}
        用户名错误!!
    </body>
    </html>

    二、局部异常处理

      1、控制器类

    /**
     * 控制器
     */
    @Controller
    @RequestMapping("/first")
    public class FirstController {
        /**
         * 局部注解处理
         */
        @ExceptionHandler
        public ModelAndView exceptionHandler(Exception ex){
            ModelAndView mv=new ModelAndView();
            //如果发生异常,我们就给他一个默认的异常处理页面
            mv.setViewName("error");
            mv.addObject("ex",ex);
    
            //如果发生Name异常,则跳转到Nam异常页面
            if (ex instanceof NameException){
                mv.setViewName("nameError");
            }
            if (ex instanceof AgeException){
                mv.setViewName("ageError");
            }
            return mv;
        }
    }

    三、自定义异常处理器

      1、定义自定义异常类

    package com.byzore.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 MyHandlerException implements HandlerExceptionResolver {
        @Override
        public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
            ModelAndView mv=new ModelAndView();
            //如果发生异常,我们就给他一个默认的异常处理页面
            mv.setViewName("error");
            mv.addObject("ex",ex);
    
            //如果发生Name异常,则跳转到Nam异常页面
            if (ex instanceof NameException){
                mv.setViewName("nameError");
            }
            if (ex instanceof AgeException){
                mv.setViewName("ageError");
            }
            return mv;
        }
    }

      2、配置applicationContext.xml文件

    <?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:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--将Controller注入到容器当中   id就是浏览器请求地址-->
        <!--<bean id="/firstController" class="com.springmvc.controller.FirstController"></bean>-->
    
        <!--配置包扫描器-->
        <context:component-scan base-package="com.byzore"/>
        <!--Spring支持SpringMVC-->
        <mvc:annotation-driven/>
    
        <!--配置视图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
        <!--利用DefaultServlet放行资源-->
        <mvc:default-servlet-handler/>
    
        <!--从Spring3.0.4版本提供资源放行的方式-->
        <!--<mvc:resources mapping="/**" location="/img"/>-->
    
        <!--系统异常处理-->
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="defaultErrorView" value="error"/>
            <property name="exceptionAttribute" value="ex"/>
            <!--定制异常-->
            <property name="exceptionMappings">
                <props>
                    <prop key="com.byzore.exception.NameException">nameError</prop>
                    <prop key="com.byzore.exception.AgeException">ageError</prop>
                </props>
            </property>
        </bean>
    </beans>

    四、全局异常处理

      1、创建全局异常处理类

    package com.byzore.exception;
    
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;
    
    /**
     * 处理所有的异常类
     */
    @ControllerAdvice
    public class MyControllerAdvice {
        @ExceptionHandler
        public ModelAndView exceptionHandler(Exception ex){
            ModelAndView mv=new ModelAndView();
            //如果发生异常,我们就给他一个默认的异常处理页面
            mv.setViewName("error");
            mv.addObject("ex",ex);
    
            //如果发生Name异常,则跳转到Nam异常页面
            if (ex instanceof NameException){
                mv.setViewName("nameError");
            }
            if (ex instanceof AgeException){
                mv.setViewName("ageError");
            }
            return mv;
        }
    }

      2、配置applicationContext.xml文件

    <?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:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--将Controller注入到容器当中   id就是浏览器请求地址-->
        <!--<bean id="/firstController" class="com.springmvc.controller.FirstController"></bean>-->
    
        <!--配置包扫描器-->
        <context:component-scan base-package="com.byzore"/>
        <!--Spring支持SpringMVC-->
        <mvc:annotation-driven/>
    
        <!--配置视图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
        <!--利用DefaultServlet放行资源-->
        <mvc:default-servlet-handler/>
    
        <!--从Spring3.0.4版本提供资源放行的方式-->
        <!--<mvc:resources mapping="/**" location="/img"/>-->
    
        <!--系统异常处理-->
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="defaultErrorView" value="error"/>
            <property name="exceptionAttribute" value="ex"/>
        </bean>
    
        <!--注入自定义异常处理器-->
        <bean class="com.byzore.exception.MyHandlerException"></bean>
    </beans>
  • 相关阅读:
    css: 组合选择器
    css: 基础选择器
    javascript设计模式:工厂模式
    wx: 小程序公共机制
    vue: 脚手架创建项目
    nodejs: express sequelize-cli
    css:flex和float margin布局
    自定义标签之inclusion_tag
    Django模型之Meta选项详解
    Django内置Admin
  • 原文地址:https://www.cnblogs.com/tinghao/p/11837041.html
Copyright © 2011-2022 走看看