简介
对于简单的全局异常处理,可以使用SpringMVC的异常处理机制,方法非常的简单;例如:使用异常处理来处理用户登录的情景,如下提供了一段伪代码
("/login")
public String login(String userName, String password, HttpSession session) {
User tempUser = userService.getUserByUserName(userName);
if(null == tempUser) {
throw new UserException("用户不存在");
}
if(!tempUser.getPassword().equals(password)) {
throw new UserException("密码不正确");
}
session.setAttribute("user", tempUser);
return "success";
}
实现步骤
-
首先先创建一个异常处理的类,UserException.class,这个类要继承 RuntimeException
-
在 UserException.class 中右键点击 Source --> Generate Constructors from Supperclass,重写构造方法
public class UserException extends RuntimeException {
private String message;
public UserException(String message) {
this.message = message;
}
... ...
}
- 在 spring-servlet.xml 文件中添加如下配置,prop 的 key 定义的是映射到哪个异常,error 是显示异常的页面;这里我们将异常统一跳转到 common/error.jsp 页面显示
<bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.ibm.reskill.exception.UserException">common/error</prop>
<prop key="java.sql.QSLException">common/error</prop>
</props>
</property>
</bean>
- 在 error.jsp 页面显示异常信息应使用如下方式,${exception.message}
<html>
<head>
<title>全局异常处理</title>
</head>
<body>
<h1>系统错误</h1>
<h2 style="color:red;">${exception.message}</h2>
</body>
</html>