springMVC之异常处理

1. 自己定义一个异常类: UserException.java

public class UserException extends RuntimeException {

	private static final long serialVersionUID = 1L;

	public UserException() {
		super();
	}

	public UserException(String message, Throwable cause) {
		super(message, cause);
	}

	public UserException(String message) {
		super(message);
	}

	public UserException(Throwable cause) {
		super(cause);
	}

}

2. 使用用户登录的样例: UserController.java

   假定username不存在或用户password错误系统会抛出异常, 并跳到error.jsp页面

@Controller
@RequestMapping("/user")
public class UserController {
	// 使用map模拟数据库 
	private Map<String, User> userMap = new HashMap<String, User>();

	public UserController() {
		userMap.put("zhangsan", new User("zhangsan", "123"));
		userMap.put("lishimin", new User("lishimin", "456"));
	}
	
	// 用户登录之异常处理
	// 訪问方法: http://localhost/springmvc_user/login.jsp
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public String login(String username, String password, HttpSession session) {
		if(!userMap.containsKey(username)) {
			throw new UserException("用户名不存在");
		}
		User user = userMap.get(username); 
		if(!user.getPassword().equals(password)) {
			throw new UserException("用户密码不对");
		}
		session.setAttribute("loginUser", user);
		return "redirect:/user/users";
	}
	
	/**
	 * 局部异常处理(仅仅能处理这个控制器中的异常)
	 */
	@ExceptionHandler(value={UserException.class})
	public String handlerException(UserException e,HttpServletRequest request) {
		request.setAttribute("exception",e); 
		return "exception/error";
	}
	
}

3. 配置全局异常处理: user-servlet.xml

<!-- 全局异常处理 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	<property name="exceptionMappings">
		<props>
			<prop key="com.zdp.exception.UserException">exception/error</prop>
		</props>
	</property>
</bean>

4. 错误信息页面: error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误页面</title>
</head>
<body>
发现错误: ${exception.message}
</body>
</html>



原文地址:https://www.cnblogs.com/jzssuanfa/p/6847997.html