SSM-SpringMVC-23:SpringMVC中初探异常解析器

释放双眼,带上耳机,听听看~!

 

 

————吾亦无他,唯手熟尔,谦卑若愚,好学若饥————-

 

 

本篇博客要讲的是异常解析器,SimpleMappingExceptionResolver简单映射异常解析器

可以处理系统的异常

 

如果出现系统异常,跳转到某个页面的时候,就可以使用它

 

案例如下:

一,创建俩个jsp页面:

success.jsp(处理方法想要跳转的页面,但是抱歉,中途插入了异常)


1
2
3
4
5
6
7
8
1<%@ page language="java" pageEncoding="utf-8" isELIgnored="false" %>
2<html>
3<body>
4<%--<img src="image/1.jpg">--%>
5<h2>Success!</h2>
6</body>
7</html>
8

error.jsp(一会出现异常跳转的页面)


1
2
3
4
5
6
7
8
9
10
11
12
1<%@ page  pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"  %>
2<html>
3<head>
4    <title>Title</title>
5</head>
6<body>
7<h2>ERROR</h2>
8<p>${ex.message}</p>
9服务器被猴子砍了,攻城狮在抢修中,还杀了个程序猿祭天
10</body>
11</html>
12

 

二,准备处理器和处理方法(我在里面模拟了个算数异常,除零)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1package cn.dawn.day15exception;
2
3import org.springframework.stereotype.Controller;
4import org.springframework.web.bind.annotation.RequestMapping;
5
6/**
7 * Created by Dawn on 2018/3/28.
8 */
9@Controller
10public class SysExceptionController {
11    @RequestMapping("/sysExceptionbyzero")
12    public String sysExceptionbyzero(){
13        int a=5/0;
14        return "success";
15    }
16}
17

 

三,在自己定义的xml中配置一道(SImpleMappingExceptionResolver)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
1<?xml version="1.0" encoding="UTF-8"?>
2<beans xmlns="http://www.springframework.org/schema/beans"
3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4       xmlns:mvc="http://www.springframework.org/schema/mvc"
5       xmlns:context="http://www.springframework.org/schema/context"
6       xsi:schemaLocation="http://www.springframework.org/schema/beans
7        http://www.springframework.org/schema/beans/spring-beans.xsd
8        http://www.springframework.org/schema/mvc
9        http://www.springframework.org/schema/mvc/spring-mvc.xsd
10         http://www.springframework.org/schema/context
11         http://www.springframework.org/schema/context/spring-context.xsd">
12
13    <!--包扫描器-->
14    <context:component-scan base-package="cn.dawn.day15exception"></context:component-scan>
15    <!--视图解析器-->
16    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
17        <property name="prefix" value="/day15/"></property>
18        <property name="suffix" value=".jsp"></property>
19    </bean>
20
21    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
22        <!--默认出现异常跳转的页面-->
23        <property name="defaultErrorView" value="error"></property>
24        <!--这个可以注入异常对象,就像catch参数里的(Exception ex)一样-->
25        <property name="exceptionAttribute" value="ex"></property>
26    </bean>
27
28</beans>
29

 

四,web.xml中央调度器修改上下文配置位置为上面那个xml的位置

 

五,启动tomcat,拉出来跑一下

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++ lambda表达式

2022-1-11 12:36:11

安全经验

fastjson 1.2.42 版本发布,Bug 修复和安全加固

2017-12-16 11:12:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索