SpringMVC处理异常

@(SpringMVC)[springmvc, 异常]

  • SpringMVC处理异常

    • SpringMVC单异常处理

      • SpitterController2
      • SpittleNotFoundException
      • MyError
    • springMvc架构级别异常处理
      • 案例

        • 自定义异常类
        • 自定义全局异常处理器
        • 错误页面errorjsp
        • 在SpringMVC配置文件中配置
        • 创建异常
        • 测试

SpringMVC单异常处理

SpitterController2

package spittr.web;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import spittr.Spittle;
import spittr.data.SpitterRepository;// 使用RestController,相当于在每个方法上加上了@ResponseBody
@RestController
@RequestMapping("/spitter2")
public class SpitterController2 {private SpitterRepository spitterRepository;@Autowiredpublic SpitterController2(SpitterRepository spitterRepository) {this.spitterRepository = spitterRepository;}@RequestMapping(value = "/{id}", method = RequestMethod.GET)public Spittle spittleById(@PathVariable long id) {Spittle spittle = spitterRepository.findOne(id);if (spittle == null) {throw new SpittleNotFoundException(id);}return spittle;}@ExceptionHandler(SpittleNotFoundException.class)@ResponseStatus(HttpStatus.NOT_FOUND)public MyError spittleNotFound(SpittleNotFoundException e) {long spittleId = e.getSpittleId();return new MyError(4, "Spittle[" + spittleId + "] not found");}}

SpittleNotFoundException

package spittr.web;/*** Created by Switch on 2017/1/14.*/
public class SpittleNotFoundException extends RuntimeException {private long spittleId;public SpittleNotFoundException(long spittleId) {this.spittleId = spittleId;}public long getSpittleId() {return spittleId;}
}

MyError

package spittr.web;/*** Created by Switch on 2017/1/14.*/
public class MyError {private int code;private String message;public MyError(int code, String message) {this.code = code;this.message = message;}public int getCode() {return code;}public String getMessage() {return message;}
}

springMvc架构级别异常处理

系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller 出现都通过throws Exception 向上抛出,最后由springmvc
前端控制器交由异常处理器进行异常处理,如下图:

案例

自定义异常类

package com.pc.ssm.exception;/*** 自定义异常* * @author Switch* @data 2017年1月13日* @version V1.0*/
public class CustomException extends Exception {private static final long serialVersionUID = -665787561868437767L;// 异常消息private String message;public CustomException() {}public CustomException(String message) {this.message = message;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}
}

自定义全局异常处理器

package com.pc.ssm.exception;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;/*** 自定义全局异常处理器* * @author Switch* @data 2017年1月13日* @version V1.0*/
public class CustomGlobalExceptionResolver implements HandlerExceptionResolver {@Overridepublic ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {ex.printStackTrace();String msg = "";if (ex instanceof CustomException) {msg = ((CustomException) ex).getMessage();} else {msg = "系统繁忙,请稍后再试,或与管理员取得联系!";}ModelAndView modelAndView = new ModelAndView();// 添加错误信息modelAndView.addObject("error", msg);modelAndView.setViewName("error");return modelAndView;}}

错误页面error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>系统通知</title></head><body> <h2>${error}</h2></body>
</html>

在SpringMVC配置文件中配置

    <!-- 配置异常处理器 --><bean id="handlerExceptionResolver" class="com.pc.ssm.exception.CustomGlobalExceptionResolver"/>

创建异常

    @RequestMapping("/showEdit")public String showEdit(@RequestParam(value = "id") String id, Model model) throws Exception {User user = userService.findById(Integer.parseInt(id));// 创造个异常if(user == null) {throw new CustomException("用户不存在!");} else if(user.getId() == 1) {int i = 1 / 0;}model.addAttribute("user", user);return "edit";}

测试

访问:http://localhost:8080/SpringMVCAdvanced/user/showEdit.action?id=1,出现“系统繁忙,请稍后再试,或与管理员取得联系!”。
访问:http://localhost:8080/SpringMVCAdvanced/user/showEdit.action?id=2,正常访问。
访问:http://localhost:8080/SpringMVCAdvanced/user/showEdit.action?id=1000023,出现“用户不存在!”。

SpringMVC处理异常相关推荐

  1. JAVA_OA(六):SpringMVC处理异常

    关于本部分的内容 这个部分网上的博文数量很多,内容很杂,虽然很全面,但是正好缺一篇新手级别的文章,于是我写了这篇文章,希望读完它,你快速轻易将学会如何使用它,而不用将太多的精力放在没用的地方. 在we ...

  2. SpringMVC教程--异常处理器详解

    异常处理器 springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑. 1.1 异常处理思路 系统中异常包括两类:预期异常和运行时异常Run ...

  3. 可以参考《SpringMVC接口测试异常:Can not deserialize instance

    2019独角兽企业重金招聘Python工程师标准>>> 之前使用springmvc搭建了restful风格的接口服务,在使用mockmvc进行集成测试的时候出现了异常:Can not ...

  4. SpringMVC中异常捕获

    如果SpringMVC的action中发生异常,我们想将其跳转到一个固定的错误页面,可以通过applicationContext.xml中增加如下配置实现: <bean class=" ...

  5. spring框架做全局异常捕获_springboot springmvc抛出全局异常的解决方法

    springboot中抛出异常,springboot自带的是springmvc框架,这个就不多说了. springmvc统一异常解决方法这里要说明的是.只是结合了springboot的使用而已.直接上 ...

  6. springMVC异常拦截

    springMvc配置 <!-- Springmvc的异常处理器 --> <bean class="com.itheima.springmvc.exception.Cust ...

  7. springMVC整合shiro权限框架示例与实践

    2019独角兽企业重金招聘Python工程师标准>>> 为什么写这篇文章 看过那么多框架.教程,大部分shiro的文章或教程是我见过思路最糟糕的.作者完不清楚想要表达什么起到什么作用 ...

  8. SpringMVC 全局异常处理的简单应用

    2019独角兽企业重金招聘Python工程师标准>>> 在SpringMVC框架的项目开发过程中,你还在使用 try{} catch(){} 输出异常吗?,那样你就真的OUT了,Sp ...

  9. SpringMVC 的总结

    一:EasyMVC 1.MVC思想 三层架构:WEB开发的最佳实践就是根据功能职责的不同,划分为控制层,业务层,持久层.![这里写图片描述](https://img-blog.csdn.net/201 ...

最新文章

  1. jsp中的contentType与pageEncoding的区别和作用
  2. 测试半桥电路 TPS28225,NCP3420驱动MOS半桥
  3. python学精通要多久-学习Python零基础需要学多久?
  4. 口语学习Day5:今天聊聊美国路牌PED XING是什么?
  5. explain都不懂,还好意思说会SQL调优?
  6. Hadoop 详细配置文档
  7. gitblit如何迁移入gitlab合并迁移_github仓库迁移到gitlab以及gitlab仓库迁移到另一个gitlab服务器...
  8. UILabel上展示不同颜色的文字(NSAttributedString)
  9. 解决IntelliJ IDEA报错:调用方法[manageApp]时发生异常java.lang.IllegalStateException: 启动子级时出错
  10. UVA 1160——X-Plosives
  11. c++服务器websocket支持
  12. java面向对象课件_《JAVA面向对象基础》PPT课件.ppt
  13. 200个最常见的JAVA面试问题(附答案)
  14. mysql 数据约束条件_mysql基本数据类型和约束条件
  15. 关于计算机的英语作文初中,computer初中英语作文范文
  16. Android直连MySQL数据库
  17. 魔兽争霸lostTemple地图
  18. 赛码网刷题记录acmcoder
  19. 十六进制与ascii码的互转(c语言),十六进制与ASCII码转换
  20. Pytorch项目(1)| 预测泰坦尼克号船上的生存乘客

热门文章

  1. Fedora/CentOS7/RedHat7关闭图形桌面开启文本界面
  2. 微信小程序入门四:实现table效果
  3. 【Java】输出10-1000中间既能被3整除又能被7整除的数
  4. 【HTML】iframe嵌套界面自适应,可高度自由收缩
  5. PHPStorm开启Debug
  6. sql中聚合函数和分组函数_SQL选择计数聚合函数-语法示例解释
  7. ibm cloud怎么使用_使用VueJS,FeathersJS和GraphQL快速入门IBM Cloud
  8. 电子科技大学计算机应用技术专科段,2020年电子科技大学成都学院计算机应用技术(专科)专业介绍...
  9. html生成pdf表格线加粗,iText 用 HTMLWorker 转换 HTML 为 PDF 时可设置表格列宽度
  10. __name__ == '__main__'