JAVA网络爬虫
HttpClient

导航

 

SpringMVC自定义异常

项目结构

在这里插入图片描述

配置文件

  1. pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.xiaoge</groupId>
      <artifactId>springmvc_exception</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <name>springmvc_exception Maven Webapp</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <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>
    
      <build>
        <finalName>springmvc_exception</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
          <plugins>
            <plugin>
              <artifactId>maven-clean-plugin</artifactId>
              <version>3.1.0</version>
            </plugin>
            <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
            <plugin>
              <artifactId>maven-resources-plugin</artifactId>
              <version>3.0.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.8.0</version>
            </plugin>
            <plugin>
              <artifactId>maven-surefire-plugin</artifactId>
              <version>2.22.1</version>
            </plugin>
            <plugin>
              <artifactId>maven-war-plugin</artifactId>
              <version>3.2.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-install-plugin</artifactId>
              <version>2.5.2</version>
            </plugin>
            <plugin>
              <artifactId>maven-deploy-plugin</artifactId>
              <version>2.8.2</version>
            </plugin>
          </plugins>
        </pluginManagement>
      </build>
    </project>
    
    
  2. web.xml**(重点:中文乱码的配置)**

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <web-app>
      <display-name>Archetype Created Web Application</display-name>
    
      <!-- 前端控制器 -->
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring.xml</param-value>
        </init-param>
    
        <!-- 当启动服务器的时候创建servlet对象 -->
        <load-on-startup>1</load-on-startup>
    
      </servlet>
    
      <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    
      <!-- 配置解决中文乱码的过滤器 -->
      <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
    
    </web-app>
    
    
  3. spring.xml**(重点:配置自定义异常解析器)**

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           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
            https://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            https://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="com.xiaoge"></context:component-scan>
    
        <!-- 视图解析器 -->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
    
        <!-- 前端控制器, 那些静态资源不拦截 -->
        <!-- css目录下的所有资源不拦截 -->
        <mvc:resources  location="/css/" mapping="/css/**" />
        <!-- images目录下的所有资源不拦截 -->
        <mvc:resources  location="/images/" mapping="/images/**" />
        <!-- js目录下的所有资源不拦截 -->
        <mvc:resources  location="/js/" mapping="/js/**" />
    
        <!-- 配置异常处理器 -->
        <bean id="sysExceptionResolver" class="com.xiaoge.exception.SysExceptionResolver" />
    
        <!-- 开启SpringMVC注解 -->
        <mvc:annotation-driven ></mvc:annotation-driven>
    </beans>
    
    

控制器

  1. UserController

    package com.xiaoge.controller;
    
    import com.xiaoge.exception.SysException;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * @Author: 潇哥
     * @DateTime: 2020/4/24 下午8:18
     * @Description: 控制器
     */
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        @RequestMapping("testException")
        public String testException() throws SysException {
            System.out.println("testException执行了....");
    
            try {
                // 模拟异常
                int a = 10 / 0;
            } catch(Exception e) {
                // 打印异常信息
                e.printStackTrace();
                // 抛出自定义异常信息
                throw new SysException("查询所有用户出现错误了...");
            }
    
    
            return "success";
        }
    
    }
    
    

异常处理器和异常类

  1. SysException(异常类)

    package com.xiaoge.exception;
    
    /**
     * @Author: 潇哥
     * @DateTime: 2020/4/24 下午8:42
     * @Description: TODO
     */
    public class SysException extends Exception {
    
        // 存储提示信息的
        private String message;
    
    
        public SysException(String message) {
            this.message = message;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
    
    }
    
    
  2. SysExceptionResolver(自定义-异常处理器)

    package com.xiaoge.exception;
    
    import org.springframework.web.servlet.HandlerExceptionResolver;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @Author: 潇哥
     * @DateTime: 2020/4/24 下午8:59
     * @Description: 异常处理器
     */
    public class SysExceptionResolver implements HandlerExceptionResolver {
    
        /**
         * 处理异常业务逻辑
         * @param httpServletRequest
         * @param httpServletResponse
         * @param o 当前处理器对象
         * @param e 异常抛出的那个对象, 在这里是SysException对象
         * @return
         */
        @Override
        public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
            // 获取到异常对象
            SysException ex = null;
    
            // 如果e是SysException类型
            if (e instanceof SysException) {
                ex = (SysException)e;
            } else {
                ex = new SysException("系统正在维护.....");
            }
    
            // 创建ModelAndView对象
            ModelAndView mv = new ModelAndView();
            // 把这个键值对存到request域中
            mv.addObject("errorMsg", ex.getMessage());
            // 设置跳转的页面
            mv.setViewName("error");
    
            return mv;
        }
    }
    
    

前台页面

  1. index.jsp

    <%--
      Created by IntelliJ IDEA.
      User: xiaoge
      Date: 2020/4/24
      Time: 下午9:09
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>异常处理</title>
    </head>
    <body>
    <a href="user/testException">异常处理</a>
    </body>
    </html>
    
    
  2. success.jsp

    <%--
      Created by IntelliJ IDEA.
      User: xiaoge
      Date: 2020/4/24
      Time: 下午8:17
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>success</title>
    </head>
    <body>
    
    </body>
    </html>
    
    
  3. error.jsp

    <%--
      Created by IntelliJ IDEA.
      User: xiaoge
      Date: 2020/4/24
      Time: 下午8:17
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <html>
    <head>
        <title>error</title>
    </head>
    <body>
        ${errorMsg}
    </body>
    </html>
    
    
posted on 2020-04-25 18:08  gmlgxx  阅读(41)  评论(0)    收藏  举报