在springMVC在配置文件:
这里基本的类是SimpleMappingExceptionResolver类,和他的父类AbstractHandlerExceptionResolver类。你也能够实现HandlerExceptionResolver接口,写一个自己的异常处理程序.通过SimpleMappingExceptionResolver我们能够将不同的异常映射到不同的jsp页面(通过exceptionMappings属性的配置)。同一时候我们也能够为全部的异常指定一个默认的异常提示页面(通过defaultErrorView属性的配置),假设所抛出的异常在exceptionMappings中没有相应的映射,则Spring将用此默认配置显示异常信息。Login.java測试类import java.io.File;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Login {
@RequestMapping("/null")
public void testNullPointerException() {
File file = null;
// 空指针异常,返回定义在SpringMVC配置文件里的null视图
System.out.println(file.getName());
}
@RequestMapping("/number")
public void testNumberFormatException() {
// NumberFormatException。返回定义在SpringMVC配置文件里的number视图
Integer.parseInt("abc");
}
@RequestMapping("/default")
public void testDefaultException() {
if (1 == 1)
// 因为该异常类型在SpringMVC的配置文件里没有指定,所以就会返回默认的exception视图
throw new RuntimeException("Error!");
}
}显示错误的jsp页面(已error.jsp为例)
<%
Exception e = (Exception)request.getAttribute("exception");
out.print(e.getMessage());
%>
測试URL: http://localhost:8080/spring_exception/null http://localhost:8080/spring_exception/number http://localhost:8080/spring_exception/default项目源代码下载:http://download.csdn.net/detail/itmyhome/7382465精彩链接
发表评论