springMvc异常处理的思想分析

一个项目出现异常是很正常的,而对于异常处理就在于一个程序员的思想了。try或者throw,但是我们一般最好是抛出异常,这样才可以依据异常来处理错误。但是页面显示的异常也就懂程序的人看得懂,如何让操作人员也懂或者知道该怎么办,这就需要异常处理机制了,自定义自己的异常类。

异常分类:

业务异常(异常信息在当前页面展示)、系统异常(在特定的错误页面展示)

异常抛出的过程:

业务层-->控制层---->视图层(即用户界面展示)


代码部分

  1. 搭建springMvc
  2. 模拟业务层的添加删除出现业务异常,出现系统异常
  3. 控制层调用业务方法并返回视图
  4. 自定义异常类
  5. 自定义异常处理类并返回视图信息

 搭建springMvc

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: zy
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <base href="${pageContext.request.contextPath}/"/>
    <title>springMvc异常测试</title>
</head>
<body>
<div style="color: red;font-size: 16px">${param.message}</div>
<a href="user/registry?url=index">添加</a><br>
<a href="user/delete?url=index">删除</a><br>
<a href="user/error">系统错误</a><br>
</body>
</html>

搭建mvc首先需要依赖,第二就是配置前端控制器在web.xml中,第三就是spring的配置文件,名称随意xx.xml

这里就提供以上三个部分,不详细说了。

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.18.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           version="2.5">
    <!--配置过滤器-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
<servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--更改加载默认配置文件路径-->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springMvc-config.xml</param-value>
    </init-param>
    <!--让前端控制器和web容器一起实例化-->
    <load-on-startup>1</load-on-startup>
</servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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
        http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--开启扫描方式纳入需要管理的主键-->
<context:component-scan base-package="com.marvin.spring"/>
    <!--配置mvc最新的适配器,映射处理,转换器-->
    <mvc:annotation-driven/>
    <!--配置视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
<!--注册异常处理器(固定名称HandlerExceptionResolver)-->
    <bean name="HandlerExceptionResolver" class="com.marvin.spring.handler.CustomerHanderResolver"></bean>
</beans>

 模拟业务层的添加删除出现业务异常,出现系统异常

 1.先创建一个简单的实体类

package com.marvin.spring.pojo;

import java.io.Serializable;

public class UserInfo implements Serializable {
    private String userName;
    private  String passWord;

    public UserInfo() {
    }

    public UserInfo(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
}

2.创建业务层操作实体类的方法(接口自己提取)

package com.marvin.spring.service;

import com.marvin.spring.exception.CustomerException;
import com.marvin.spring.pojo.UserInfo;
import org.springframework.stereotype.Service;

/**
 * 业务处理类
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {
    /**
     * 添加方法
     */
    @Override
    public void addUser(UserInfo userInfo){
        try {
            throw  new Exception();
        }catch (Exception e){
            throw  new CustomerException("添加失败");
        }
    }
    /**
     * 删除方法
     */
    @Override
    public void deleteUser(UserInfo userInfo){
        try {
            throw  new Exception();
        }catch (Exception e){
            throw  new CustomerException("添加失败");
        }
    }
    /**
     * 系统异常
     */
    @Override
    public void errorSystem(UserInfo userInfo) throws Exception {
            throw  new Exception();
    }
}

控制层调用业务方法并返回视图

package com.marvin.spring.controller;

import com.marvin.spring.pojo.UserInfo;
import com.marvin.spring.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("index")
    public String index(){
        return "index";
    }

    @GetMapping("registry")
     public ModelAndView registry(UserInfo userInfo){
        //创建ModelAndView的对象
         ModelAndView mv=new ModelAndView();
         mv.setViewName("index");
         userInfoService.addUser(userInfo);
         return mv;
     }
    @GetMapping("delete")
    public ModelAndView delete(UserInfo userInfo){
        //创建ModelAndView的对象
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        userInfoService.deleteUser(userInfo);
        return mv;
    }
    @GetMapping("error")
    public ModelAndView error(UserInfo userInfo) throws Exception {
        //创建ModelAndView的对象
        ModelAndView mv=new ModelAndView();
        mv.setViewName("index");
        userInfoService.errorSystem(userInfo);
        return mv;
    }
}

 自定义异常类

package com.marvin.spring.exception;

public class CustomerException extends  RuntimeException {
    public CustomerException() {
        super();
    }

    public CustomerException(String message) {
        super(message);
    }

    public CustomerException(String message, Throwable cause) {
        super(message, cause);
    }
}

自定义异常处理类并返回视图信息

package com.marvin.spring.handler;

import com.marvin.spring.exception.CustomerException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomerHanderResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //打印错误信息
        System.out.println(e.getMessage());
        //定义自定义异常句柄
        CustomerException customerException;
        //获取参数
        String url = httpServletRequest.getParameter("url");
        //判断该异常是否为自定义异常
        if(e instanceof  CustomerException) {
            url="redirect:"+url;
            customerException = (CustomerException) e;
        }else{
            customerException=new CustomerException("系统出现异常,请与管理员联系");
            url="redirect:/error/error.jsp";
        }
        //创建对象
        ModelAndView mv=new ModelAndView();

        //从定向到错误页面
        mv.setViewName(url);
        mv.addObject("message",customerException.getMessage());
        return mv;

    }
}

 错误页面jsp

<%--
  Created by IntelliJ IDEA.
  User: zy
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>错误页面</title>
</head>
<body>
错误信息<span style="color: red;font-size: 16px" >${param.message}</span>
</body>
</html>

好了这就实现了业务异常显示到当前页面给操作人员看,系统异常则在error.jsp中显示。

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值