• 2021-6-4 日报博客


    个人博客

    1.学到的东西

    1. SpringMVC异常处理机制

    1.1 异常处理的思路

    系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试等手段减少运行时异常的发生。

    系统的Dao、Service、Controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理,如下图:

    1551078013501

    1.2 异常处理两种方式

    ① 使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

    ② 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器

    1.3 简单异常处理器SimpleMappingExceptionResolver

    SpringMVC已经定义好了该类型转换器,在使用时可以根据项目情况进行相应异常与视图的映射配置

    <!--配置简单映射异常处理器-->
        <bean class=“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”>    <property name=“defaultErrorView” value=“error”/>   默认错误视图
        <property name=“exceptionMappings”>
            <map>		异常类型		                             错误视图
                <entry key="com.itheima.exception.MyException" value="error"/>
                <entry key="java.lang.ClassCastException" value="error"/>
            </map>
        </property>
    </bean>
    

    1.4 自定义异常处理步骤

    ①创建异常处理器类实现HandlerExceptionResolver

    public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, 
        HttpServletResponse response, Object handler, Exception ex) {
        //处理异常的代码实现
        //创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView(); 
        modelAndView.setViewName("exceptionPage");
        return modelAndView;
        }
    }
    

    ②配置异常处理器

    <bean id="exceptionResolver"        
          class="com.itheima.exception.MyExceptionResolver"/>
    

    ③编写异常页面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    	<title>Title</title>
    </head>
    <body>
    	这是一个最终异常的显示页面
    </body>
    </html>
    

    ④测试异常跳转

    @RequestMapping("/quick22")
    @ResponseBody
    public void quickMethod22() throws IOException, ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
        simpleDateFormat.parse("abcde");
    }
    

    1.5 知识要点

    异常处理方式

    配置简单异常处理器SimpleMappingExceptionResolver
    
    自定义异常处理器
    

    自定义异常处理步骤

    ①创建异常处理器类实现HandlerExceptionResolver
    
    ②配置异常处理器
    
    ③编写异常页面
    
    ④测试异常跳转
    

    2.明日计划

    Spring练习-环境搭建步骤分析

    3.遇到的问题

  • 相关阅读:
    MySQL server has gone away 问题的解决方法
    MySQL批量SQL插入性能优化
    mysql中int、bigint、smallint 和 tinyint的区别详细介绍
    Mac OS使用ll、la、l等ls的别名命令
    Github上的PHP资源汇总大全
    svn代码版本管理总结
    mysql information_schema介绍
    redis 五种数据结构详解(string,list,set,zset,hash)
    git 换行符LF与CRLF转换问题
    php 利用activeMq+stomp实现消息队列
  • 原文地址:https://www.cnblogs.com/gongyunlong-blogs/p/14915849.html
Copyright © 2020-2023  润新知