java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringMVC的异常处理机制

关于SpringMVC的异常处理机制详细解读

作者:bfhonor

这篇文章主要介绍了关于SpringMVC的异常处理机制详细解读,SpringMVC是目前主流的Web MVC框架之一,本文将分析SpringMVC的异常处理内容,需要的朋友可以参考下

SpringMVC异常处理机制

(一)项目前准备

在这里插入图片描述

package com.itheima.service;
import com.itheima.exception.MyException;
import java.io.FileNotFoundException;
public interface DemoService {
    void show1();
    void show2();
    void show3() throws FileNotFoundException;
    void show4();
    void show5() throws MyException;
}
package com.itheima.service;
import com.itheima.exception.MyException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class DemoServiceImpl implements DemoService{
    public void show1(){
        System.out.println("抛出类型转换异常...");
        Object str = "zhangsan";
        Integer num = (Integer) str;
    }
    public void show2(){
        System.out.println("抛出除零异常...");
        int i = 1/0;
    }
    public void show3() throws FileNotFoundException {
        System.out.println("文件找不到异常...");
        FileInputStream in = new FileInputStream("D:/xxx/xxx/xxx.txt");
    }
    public void show4(){
        System.out.println("空指针异常......");
        String str = null;
        str.length();
    }
    public void show5() throws MyException {
        System.out.println("自定义异常....");
        throw new MyException();
    }
}
package com.itheima.controller;
import com.itheima.exception.MyException;
import com.itheima.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.FileNotFoundException;
@Controller
public class DemoController {
    @Autowired
    private DemoService demoService;
    @RequestMapping(value="/show")
    public String show(@RequestParam(value="name",required=true) String name) throws FileNotFoundException, MyException {
        System.out.println("show running......");
        demoService.show1();
        //demoService.show2();
        //demoService.show3();
        //demoService.show4();
        //demoService.show5();
        return "index";
    }
}
package com.itheima.exception;
public class MyException extends Exception{}
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd
">
    <bean id="demoService" class="com.itheima.service.DemoServiceImpl"></bean>
</beans>
<?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
">
    <!--1、mvc注解驱动-->
    <mvc:annotation-driven/>
    <!--2、配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--3、静态资源权限开放-->
    <mvc:default-servlet-handler/>
    <!--4、组件扫描  扫描Controller-->
    <context:component-scan base-package="com.itheima.controller"/>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
	<!--配置监听器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
	<!--配置SpringMVC的前端控制器-->
	<servlet>
	    <servlet-name>DispatcherServlet</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	    <!--加载Spring-mvc.xml文件,在配置控制器的时候告知配置文件-->
	    <init-param>
	        <param-name>contextConfigLocation</param-name>
	        <param-value>classpath:spring-mvc.xml</param-value>
	    </init-param>
	    <load-on-startup>1</load-on-startup>
	</servlet>
	<!--配置映射地址-->
	<servlet-mapping>
	    <servlet-name>DispatcherServlet</servlet-name>
	    <url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

index.jsp文件

<html>
	<body>
		<h2>Hello World!</h2>
	</body>
</html>

error.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>通用的错误提示页面</h1>
</body>
</html>

(二)项目异常测试

2.1 异常处理的思路

在这里插入图片描述

2.2 异常处理两种方式

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

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

2.3 简单异常处理器 SimpleMappingExceptionResolver

在这里插入图片描述

(1)默认错误视图

在这里插入图片描述

<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <!--默认错误视图-->
    <property name="defaultErrorView" value="error"/>
</bean>

在这里插入图片描述

(2)根据错误异常类型,进行自定义设定的错误视图跳转

<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <map>
            <entry key="java.lang.ClassCastException" value="error1"></entry>
        </map>
    </property>
</bean>

在这里插入图片描述

<!--配置异常处理器-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <map>
            <entry key="com.itheima.exception.MyException" value="error2"></entry>
        </map>
    </property>
</bean>

在这里插入图片描述

2.4 自定义异常处理步骤

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

package com.itheima.resolver;
import com.itheima.exception.MyException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyExceptionResolver implements HandlerExceptionResolver {
    /*参数Exception 异常对象
    * 返回值ModelAndView 跳转到视图信息*/
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if (e instanceof MyException){
            modelAndView.addObject("info","自定义异常");
        }else if (e instanceof ClassCastException){
            modelAndView.addObject("info","类转换异常");
        }
        modelAndView.setViewName("error");
        return modelAndView;
    }
}

②、在spring-mvc.xml里面配置异常处理器

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

③、在error.jsp中,编写异常页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>通用的错误提示页面</h1>
    <h1>${info}</h1>
</body>
</html>

④测试异常跳转

package com.itheima.controller;
import com.itheima.exception.MyException;
import com.itheima.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.FileNotFoundException;
@Controller
public class DemoController {
    @Autowired
    private DemoService demoService;
    @RequestMapping(value="/show")
    public String show() throws FileNotFoundException, MyException {
        System.out.println("抛出类型转换异常...");
        Object str = "zhangsan";
        Integer num = (Integer) str;
        return "index";
    }
}

在这里插入图片描述

到此这篇关于关于SpringMVC的异常处理机制详细解读的文章就介绍到这了,更多相关SpringMVC的异常处理机制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文