SpringMVC——异常处理机制

目录结构
SpringMVC——异常处理机制_第1张图片

目录

    • 一、导入坐标
    • 二、web.xml配置前端处理器
    • 三、配置springmvc的配置文件
    • 四、配置一个错误的方法
    • 五、注意,这里一定要是message
    • 六、配置异常处理类
    • 七、jsp页面
      • 1.index页面
      • 2.error页面

一、导入坐标

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!--版本锁定-->
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>
  
 <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

二、web.xml配置前端处理器



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  <filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>characterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>


三、配置springmvc的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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="edu.xiao"/>
    <!--视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--文件所在目录-->
        <property name="prefix" value="/WEB-INF/pages/" />
        <!--文件的后缀名-->
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--配置异常处理器-->
    <bean class="edu.xiao.exception.ErrorResolver" id="errorResolver"/>

    <!--开启SpringMVC注解支持和类型转换器-->
    <mvc:annotation-driven  />
</beans>

四、配置一个错误的方法

package edu.xiao;

import edu.xiao.exception.SystemExc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/view")
public class ViewController {
    @RequestMapping("testException")
    public String testException() throws SystemExc {
        System.out.println("testException执行了...");

        try {
            // 模拟异常
            int a = 10/0;
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 抛出自定义异常信息
            throw new SystemExc("查询所有用户出现错误了...");
        }
        return "success";

    }
}

五、注意,这里一定要是message

package edu.xiao.exception;

public class SystemExc extends Exception {
    /*必须是message*/
  private String message;

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SystemExc(String message) {
        this.message = message;
    }
}

六、配置异常处理类

package edu.xiao.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 ErrorResolver implements HandlerExceptionResolver{

    /**
     * 处理异常业务逻辑
     */
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 获取到异常对象
        SystemExc e = null;
        if(ex instanceof SystemExc){
            e = (SystemExc)ex;
        }else{
            e = new SystemExc("系统正在维护....");
        }
        // 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",e.getMessage());
        mv.setViewName("error");
        return mv;
    }

}

七、jsp页面

1.index页面

<%--
  Created by IntelliJ IDEA.
  User: dell
  Date: 2020/4/7
  Time: 16:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
<a href="view/testException">testExceptiona>
body>
html>

2.error页面

<%--
  Created by IntelliJ IDEA.
  User: dell
  Date: 2020/4/7
  Time: 17:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
        ${errorMsg}
body>
html>

你可能感兴趣的:(技术笔记,SpringMvc)