Spring MVC配置全局异常处理器!!!

为什么要使用全局异常处理器:如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。

异常处理思路

系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:

Spring MVC配置全局异常处理器!!!_第1张图片

创建异常处理器:GlobalException:

/*
 * Copyright (c) 2020, 2024,  All rights reserved.
 *
 */
package com.by.exception;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 

Project: SpringMVC - GlobleException

*

Powered by scl On 2024-01-10 14:09:52

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ @Component public class GlobalException implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { /** * 1.发邮件、发信息 * 2.跳转到错误页面 */ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("msg",e.getMessage()); modelAndView.setViewName("exception"); return modelAndView; } }

  编写controller:ExceptionController:

/*
 * Copyright (c) 2020, 2024,  All rights reserved.
 *
 */
package com.by.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 

Project: SpringMVC - execptionController

*

Powered by scl On 2024-01-10 14:14:44

*

描述:

* * @author 孙臣龙 [[email protected]] * @version 1.0 * @since 17 */ @Controller @RequestMapping("/account") public class ExceptionController { @RequestMapping("/findException") public String findException() throws Exception{ System.out.println(4/0); return "exception"; } }

在index.jsp里面定义超链接: 

  全局异常处理器

结果展示:

Spring MVC配置全局异常处理器!!!_第2张图片

Spring MVC配置全局异常处理器!!!_第3张图片

 项目结构:Spring MVC配置全局异常处理器!!!_第4张图片

 

项目配置可参考:Spring MVC文件上传!!!-CSDN博客

你可能感兴趣的:(spring,mvc,java,后端,intellij-idea)