1. 创建异常类:
创建一个自定义的异常类,例如CustomException:
package com.example.exception;
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
2. 创建Controller:
创建一个Controller类,包含一个抛出自定义异常的方法:
package com.example.controller;
import com.example.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class ExceptionController {
@RequestMapping(value = "/simulateException", method = RequestMethod.GET)
public String simulateException() {
throw new CustomException("This is a simulated custom exception.");
}
// 处理自定义异常
@ExceptionHandler(CustomException.class)
public String handleCustomException(CustomException ex, Model model) {
model.addAttribute("errorMessage", ex.getMessage());
return "errorPage";
}
}
3. 创建错误页面:
在src/main/webapp/WEB-INF/views目录下创建一个errorPage.jsp文件,用于显示异常信息:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<h2>Error Occurred</h2>
<p>${errorMessage}</p>
</body>
</html>
4. 配置spring-mvc-servlet.xml:
在src/main/webapp/WEB-INF目录下创建一个spring-mvc-servlet.xml文件,配置Spring MVC:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.example.controller" />
<!-- 开启注解驱动 -->
<mvc:annotation-driven />
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
5. 运行:
在你的IDE中运行或将项目打包并部署到支持Servlet容器的环境中。访问http://localhost:8080/your-project-name/simulateException,应该能看到错误页面显示自定义异常的信息。
在这个例子中,simulateException方法抛出了CustomException异常。使用@ExceptionHandler注解,handleCustomException方法被定义来处理这个自定义异常,并在errorPage.jsp中显示异常信息。这是一个简单的Spring MVC异常处理的例子,你可以根据实际需求进一步定制异常处理。
转载请注明出处:http://www.pingtaimeng.com/article/detail/6972/Spring