當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring MVC笔记 添加错误页面
生活随笔
收集整理的這篇文章主要介紹了
Spring MVC笔记 添加错误页面
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用Spring MVC的Web項目,可以使用DispatcherServlet來指定異常頁面,下面是具體的配置:
在Spring配置文件中配置:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <?xml?version="1.0" encoding="UTF-8" ?> <beans?xmlns="http://www.springframework.org/schema/beans" ???????xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" ???????xmlns:context="http://www.springframework.org/schema/context" ???????xsi:schemaLocation="http://www.springframework.org/schema/beans ???????http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ???????http://www.springframework.org/schema/context ???????http://www.springframework.org/schema/context/spring-context-3.0.xsd"> ????<!-- 掃描web包,應用Spring的注解 --> ????<context:component-scan?base-package="com.xxx.training.spring.mvc"/> ????<!-- 配置視圖解析器,將ModelAndView及字符串解析為具體的頁面 --> ????<bean ????????????class="org.springframework.web.servlet.view.InternalResourceViewResolver" ????????????p:viewClass="org.springframework.web.servlet.view.JstlView" ????????????p:prefix="/WEB-INF/views/" ????????????p:suffix=".jsp"/> ????<!--定義異常處理頁面--> ????<bean?id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> ????????<property?name="exceptionMappings"> ????????????<props> ????????????????<prop?key="java.sql.SQLException">outException</prop> ????????????????<prop?key="java.io.IOException">outException</prop> ????????????</props> ????????</property> ????</bean> </beans> |
上面的定義異常處理部分的解釋為:只要發生了SQLException或者IOException異常,就會自動跳轉到WEB-INF/views/outException.jsp頁面。
一般情況下我們的outException.jsp頁面的代碼為:
| 1 2 3 4 5 6 7 8 9 10 11 | <%@ page contentType="text/html;charset=UTF-8"?language="java"?%> <html> <head> ????<title>異常處理頁面</title> </head> <body> <% Exception ex = (Exception) request.getAttribute("Exception");%> <H2>Exception:<%=ex.getMessage()%> </H2> </body> </html> |
另外,在web.xml也可以使用類似下面的方式處理異常:
| 1 2 3 4 5 6 7 8 9 | <error-page> ?????<error-code>404</error-code> ?????<location>/WEB-INF/pages/404.jsp</location> ?</error-page> ?<error-page> ?????<exception-type>java.lang.Exception</exception-type> ?????<location>/WEB-INF/pages/exception.jsp</location> ?</error-page> |
因為這兩個異常處理的維度是不一樣的,spring的resolver是spring內部使用的,而web.xml里的是整個webapp共同使用的。
?
總結
以上是生活随笔為你收集整理的Spring MVC笔记 添加错误页面的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在html使用a标签 直接下载图片 不通
- 下一篇: gradle idea java ssm