SSM异常处理

1.配置错误页面 404.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>主页</title> </head> <body> <html> <body> <h1><b th:text="${errorMsg}"></b></h1> </body> </html>

2.自定义异常处理器

package com.qcby.util; import com.qcby.entity.SysException; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SysExceptionResolver implements HandlerExceptionResolver { /** * 程序出现了异常,调用异常处理器中的方法 * @param httpServletRequest * @param httpServletResponse * @param o * @param e * @return */ @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { e.printStackTrace(); //在命令行打印异常信息在程序中出错的位置及原因。 // 做强转 SysException exception = null; // 判断 if(e instanceof SysException){ exception = (SysException)e; }else{ exception = new SysException("系统正在维护,请联系管理员"); } ModelAndView mv = new ModelAndView(); mv.addObject("errorMsg",exception.getMessage()); // 设置跳转的页面 mv.setViewName("404"); return mv; } }

3.自定义异常类

/** * 异常处理类 */ public class SysException extends Exception{ // 提示消息 private String message; public SysException(String message){ this.message = message; } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "SysException{" + "message='" + message + '\'' + '}'; } }

4.配置异常处理器

<!--配置异常处理器--> <bean id="sysExceptionResolver" class="com.qcby.util.SysExceptionResolver" />

5.Controller测试

/** * 使用异常处理器方式 * @return */ @RequestMapping("/findAll.do") public String findAll(){ System.out.println("执行了..."); // 模拟异常 int a = 10/0; return "suc"; }

相关推荐
学习路上_write1 小时前
Linux黑马命令学习
linux·运维·服务器
那年窗外下的雪.1 小时前
AIDC 学习日志|第 22 天|All-Active/Single-Active 故障演练设计
服务器·网络·学习·算法·哈希算法
Android系统攻城狮1 小时前
Linux Gstreamer深度解析之gst_audio_channel_reorder_map调用流程与实战(十八)
linux·运维·服务器·音视频进阶·gstreamer音视频进阶
新时代牛马2 小时前
docker run 起不来?从dockerd、containerd 到runc 一条线讲透
运维·docker·容器
TomEval2 小时前
【App 自动化】14 - App 自动化基础与环境
运维·自动化
cc_yy_zh2 小时前
学习使用kali抓包
服务器·学习·php
wzdark2 小时前
基于启发式搜索的最优路径规划算法研究4
算法
盛世宏博智慧档案2 小时前
户外配电柜为什么要装POE供电以太网温湿度传感器?
服务器·网络·人工智能·监控·温湿度·配电柜
新时代牛马2 小时前
Linux 防火墙:nftables 与iptables 兼容层
linux·运维·服务器
l1t2 小时前
用superpi、tinypi、tpi等工具计算圆周率的比较
c语言·算法