springmvc异常处理(非注解与注解)
1.异常
程序中的异常一般分为两类:预期异常,运行时异常。前者是我们可预知的,我们一般通过捕获和抛出方式处理这些异常。后者主要通过代码规范、测试等手段来减少异常的发生。一般,我们在系统的DAO、Service层的异常都向上抛出,然后统一的在Controller中进行处理。但是每个Controller中的每个方法都写类似的异常处理逻辑,就显得非常的麻烦,并且代码重复。
Spring提供了异常处理器(HandlerExceptionResolver)来处理异常。我们定义好处理异常的逻辑,SpringMVC会在任何的Controller出现异常时,调用我们定义的异常处理逻辑。从而实现异常的统一管理,并且避免了代码的重复。
其异常处理流程如下:

2.非注解使用异常案例.
异常分为自定义异常和运行时异常,这就要分别编写自定义异常和运行时异常。
2.1编写一个controller类,给类方法中出现两个异常,分别是自定义和运行时异常,代码如下:
@RequestMapping("ex/")
@Controller
public class ExceptionController {
@RequestMapping("show/{id}")
@ResponseStatus(HttpStatus.OK)
public ModelAndView show(@PathVariable("id") Long id) throws MyException{
ModelAndView mv = new ModelAndView("hello");
// 自定义异常
if(id==){
throw new MyException("自定义异常出现");
}
System.out.println("exception");
// 运行时异常
System.out.println(/);
mv.addObject("msg", "传递参数"+id);
return mv;
}
2.2如果出现自定义异常,需要处理,需要编写自定义异常类,且继承Exception,代码如下:
package cn.exception;
public class MyException extends Exception {
/**
* 自定义异常
*/
private static final long serialVersionUID = 1L;
// 提供构造函数
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
}
2.3.需要定义异常处理器(编写类实现HandlerExceptionResolver )
package cn.exception; import java.io.PrintWriter;
import java.io.StringWriter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView; public class MyexceptionResolver implements HandlerExceptionResolver { //异常处理的方法
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ModelAndView mv = new ModelAndView("error");
String msg = null;
// 判断是否是自定义异常
if(ex instanceof MyException){
msg = ex.getMessage();
}else{
// 如果不是,则获取栈信息
StringWriter out = new StringWriter();
PrintWriter pw = new PrintWriter(out);
ex.printStackTrace(pw);
msg = out.toString();
}
// 添加异常信息到Model
mv.addObject("msg", msg);
return mv;
} }
2.4.在Springmvc配置文件中,配置异常处理器
<!-- 配置异常处理页面 -->
<bean class="cn.exception.MyexceptionResolver"></bean>
2.5.编写异常页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
异常发生了...${msg }
</body>
</html>
3.非注解使用异常案例.
package cn.controller; import java.io.PrintWriter;
import java.io.StringWriter; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView; import cn.exception.MyException; @ControllerAdvice
public class ExceptionControllerAdvice { // 处理自定义异常
@ExceptionHandler(MyException.class)
public ModelAndView zdyException(MyException e){
ModelAndView mv = new ModelAndView("error"); mv.addObject("msg", e.getMessage()); return mv;
} // 处理运行时异常
@ExceptionHandler(RuntimeException.class)
public ModelAndView zdyException(RuntimeException ex){
ModelAndView mv = new ModelAndView("error"); mv.addObject("msg", ex.getMessage());
StringWriter out = new StringWriter();
PrintWriter pw = new PrintWriter(out);
ex.printStackTrace(pw);
mv.addObject("msg", out.toString());
return mv;
} }
需要提供自定义异常类,见上面MyException
springmvc异常处理(非注解与注解)的更多相关文章
- SpringMVC的controller方法中注解方式传List参数使用@RequestBody
在SpringMVC控制器方法中使用注解方式传List类型的参数时,要使用@RequestBody注解而不是@RequestParam注解: //创建文件夹 @RequestMapping(value ...
- springMVC学习记录2-使用注解配置
前面说了一下使用xml配置springmvc,下面再说说注解配置.项目如下: 业务很简单,主页和输入用户名和密码进行登陆的页面. 看一下springmvc的配置文件: <?xml version ...
- SpringMVC源码解读 - RequestMapping注解实现解读 - RequestMappingInfo
使用@RequestMapping注解时,配置的信息最后都设置到了RequestMappingInfo中. RequestMappingInfo封装了PatternsRequestCondition, ...
- SpringMVC源码解读 - RequestMapping注解实现解读 - RequestCondition体系
一般我们开发时,使用最多的还是@RequestMapping注解方式. @RequestMapping(value = "/", param = "role=guest& ...
- SSM框架之SpringMVC(3)常用注解
SpringMVC(3)常用注解 1. RequestParam注解 1.作用:把请求中指定名称的参数传递给控制器中的形参赋值 2.属性: 1.value:请求参数的每次 2.required ...
- SpringMVC利用AOP实现自定义注解记录日志
作者:飞翔的拖鞋up 推荐:彻底征服 Spring AOP 之 实战篇 推荐:jason_zhangz 本文抛砖引玉,并没有详细的介绍更全面的内容,通过一个例子让初次使用的人能够快速入门,简单的介绍一 ...
- SpringMVC源码解读 - RequestMapping注解实现解读
SpringMVC源码解读 - RequestMapping注解实现解读 - RequestCondition体系 https://www.cnblogs.com/leftthen/p/520840 ...
- SpringMVC异常处理机制详解[附带源码分析]
目录 前言 重要接口和类介绍 HandlerExceptionResolver接口 AbstractHandlerExceptionResolver抽象类 AbstractHandlerMethodE ...
- SpringMVC异常处理机制
SpringMVC异常处理机制 springMVC会将所有在doDispatch方法中的异常捕获,然后处理.无法处理的异常会抛出给容器处理. 在doDispatch()中调用processDispat ...
随机推荐
- iOS -- 全局导航栏返回键
[UINavigationBar appearance].backIndicatorTransitionMaskImage = [UIImage imageNamed:@"backArrow ...
- iOS-毛玻璃、navigationBar滑动颜色渐变
1.毛玻璃实现 iOS8以上,官方提供了系统方法实现毛玻璃,代码如下: // iOS8 UIVisualEffectView UIImageView *bgView = [[UIImageView a ...
- 输入一个十进制数N,将它转换成R进制数输出(运用递归实现)
#include<stdio.h> int cnt=0; //用来记录每个进制存放的位置 char num[20]; //用来存 ...
- 关于lucene的RAMDirectory和FSDirectory的性能问题的困惑
关于lucene的RAMDirectory和FSDirectory的性能问题的困惑 在lucene in Action书中说RAMDirectory的性能总是比FSDirectory优越(书中2.7. ...
- 3 Steps(二分图)
C - 3 Steps Time limit : 2sec / Memory limit : 256MB Score : 500 points Problem Statement Rng has a ...
- 用SQL语句生成唯一标识
以前都是在代码中生成GUID值,然后保存到数据库中去,今天发现用sql也能生成GUID值,觉得很新奇,所以记下来. sellect newid(); //得到的即为GUID值 此sql内置函数返回的 ...
- IntelliJ IDEA For Mac 快捷键 [转]
Mac键盘符号和修饰键说明 ⌘ Command ⇧ Shift ⌥ Option ⌃ Control ↩︎ Return/Enter ⌫ Delete ⌦ 向前删除键(Fn+Delete) ↑ 上箭头 ...
- mix-in class selectors
语言特性 | Less 中文网 http://lesscss.cn/features/#mixins-feature Mixins "mix-in" properties from ...
- python系列七:Python3字典dict
#!/usr/bin/python #Python3 字典#字典是支持无限极嵌套的citys={ '北京':{ '朝阳':['国贸','CBD','天阶','我爱我家','链接地产 ...
- JavaScript数据结构与算法-栈练习
栈的实现 // 栈类 function Stack () { this.dataStore = []; this.top = 0; // 栈顶位置 相当于length,不是索引. this.push ...