创建 BaseController 类,并在该类中使用 @ExceptionHandler 注解声明异常处理方法,具体代码如下:

    1. package controller;
    2. import java.sql.SQLException;
    3. import javax.servlet.http.HttpServletRequest;
    4. import org.springframework.web.bind.annotation.ExceptionHandler;
    5. import exception.MyException;
    6. public class BaseController {
    7. /** 基于@ExceptionHandler异常处理 */
    8. @ExceptionHandler
    9. public String exception(HttpServletRequest request, Exception ex) {
    10. request.setAttribute("ex", ex);
    11. // 根据不同错误转向不同页面,即异常与view的对应关系
    12. if (ex instanceof SQLException) {
    13. return "sql-error";
    14. } else if (ex instanceof MyException) {
    15. return "my-error";
    16. } else {
    17. return "error";
    18. }
    19. }
    20. }

    将所有需要异常处理的 Controller 都继承 BaseController 类,示例代码如下:

    1. @Controller
    2. public class TestExceptionController extends BaseController{
    3. ...
    4. }

    在使用 @ExceptionHandler 注解声明统一处理异常时不需要配置任何信息,此时将配置文件的代码修改如下:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xsi:schemaLocation="
    6. http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring一beans.xsd
    8. http://www.springframework.org/schema/context
    9. http://www.springframework.org/schema/context/spring-context.xsd">
    10. <!-- 使用扫描机制扫描包 -->
    11. <context:component-scan base-package="controller" />
    12. <context:component-scan base-package="service" />
    13. <context:component-scan base-package="dao" />
    14. <!-- 配置视图解析器 -->
    15. <bean
    16. class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    17. id="internalResourceViewResolver">
    18. <!--前缀 -->
    19. <property name="prefix" value="/WEB-INF/jsp/" />
    20. <!-- 后缀 -->
    21. <property name="suffix" value=".jsp" />
    22. </bean>
    23. </beans>

    发布 springMVCDemo10 应用到 Tomcat 服务器并启动服务器,然后即可通过地址“http://localhost:8080/springMVCDemo10/”测试应用。