1.运行环境
Windows 10 intellij idea
2.文件位置
3. 代码和运行效果
3.1 代码
3.1.1 异常控制器ExceptionController
package com.itheima.web.controller;
import com.itheima.exception.CustomerException;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* springMVC的异常处理
*/
@Controller("exceptionController")
@RequestMapping("/springmvc")
public class ExceptionController {
/**
* 测试自定义异常处理
* @param username
* @return
*/
@RequestMapping("/testException")
public String testException(String username) throws CustomerException {
System.out.println("testException执行了......."+username);
//判断用户名是否为空,如果为空就会抛出异常
if(StringUtils.isEmpty(username)){
throw new CustomerException("用户名为空");
}
return "success";
}
}
3.1.2 自定义异常
package com.itheima.exception;
public class CustomerException extends Exception {
//定义异常信息
private String message;
/**
* 通过构造函数提供异常信息
* @param message
*/
public CustomerException(String message) {
this.message = message;
}
//获取异常信息
@Override
public String getMessage() {
return message;
}
}
3.1.3 自定义异常处理器
package com.itheima.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义异常处理器
*/
public class CustomerExceptionResolver extends Exception implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,Object handler, Exception ex) {
//打印异常信息
ex.printStackTrace();
//定义一个自己的异常类对象
CustomerException customerException =null;
//判断当前传入的异常对象是否是自定义异常对象
if(ex instanceof CustomerException){
customerException = (CustomerException)ex;
}else{
customerException = new CustomerException("系统问题,请联系管理员");
}
//创建ModelAndView对象
ModelAndView mv = new ModelAndView();
mv.setViewName("error");
mv.addObject("errorMessage",customerException.getMessage());
return mv;
}
}
3.1.4.在Spring配置文件中配置自定义异常处理器
!--配置自定义异常处理器 -->
<bean id="handlerExceptionResolver" class="com.itheima.exception.CustomerExceptionResolver" />
3.1.5 异常处理页面
<%--
Created by IntelliJ IDEA.
User: Fingertips
Date: 2019/4/11
Time: 11:26
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>springmvc的异常处理</title>
</head>
<body>
<form action="springmvc/testException" method="post">
用户名称:<input type="text" name="username"/><br/>
<input type="submit" value="保存" />
</form>
</body>
</html>
3.1.6 异常跳转页面
<%--
Created by IntelliJ IDEA.
User: Fingertips
Date: 2019/4/17
Time: 23:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误提示页面</title>
</head>
<body>
执行失败${errorMessage}
</body>
</html>