SpringMVC中的异常处理

这是个WebProject,用到的是spring-framework-3.1.1.RELEASE


首先是web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
		<servlet-name>user</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>user</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>SpringCharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>SpringCharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<welcome-file-list>
		<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
	</welcome-file-list>
</web-app>

然后是SpringMVC的配置文件user-servlet.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
	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/mvc
						http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
						http://www.springframework.org/schema/context 
						http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<context:component-scan base-package="com.jadyer"/>
	
	<mvc:annotation-driven/>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
</beans>

下面是用户登录页面//WEB-INF//jsp//login.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<form action="<%=request.getContextPath()%>/user/login" method="POST">
	username: <input type="text" name="username"/><br/>
	password: <input type="password" name="password"/><br/>
	<input type="submit" value="登录"/>
</form>

下面是用户登录失败页面//WEB-INF//jsp//error.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
${myex.message}

下面是用户登录成功页面//WEB-INF//jsp//user//loginSuccess.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
welcome: ${loginUser.nickname}

接下来是用到的实体类User.java

package com.jadyer.model;

/**
 * User
 * @author 宏宇
 * @create May 12, 2012 1:24:43 AM
 */
public class User {
	private String username;
	private String nickname;
	private String password;
	private String email;
	/*==四个属性的getter()、setter()略==*/
	public User() {}
	public User(String username, String nickname, String password, String email) {
		this.username = username;
		this.nickname = nickname;
		this.password = password;
		this.email = email;
	}
}

然后是自定义的异常类UserException.java

package com.jadyer.exception;

/**
 * UserException
 * @author http://blog.csdn/net/jadyer
 * @create May 12, 2012 6:43:29 PM
 */
@SuppressWarnings("serial")
public class UserException extends RuntimeException {
	public UserException() {
		super();
	}

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

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

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

最后是核心的UserController.java

package com.jadyer.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.jadyer.exception.UserException;
import com.jadyer.model.User;

/**
 * SpringMVC中的异常处理方式
 * @see 第一步:创建自定义异常类
 * @see 第二步:在Controller中创建一个用于截获并处理异常方法,方法名可随意
 *            然后在方法上标注@ExceptionHandler(你的自定义异常类名.class)
 *            接着就可以在该方法内部,进行符合我们业务逻辑的异常处理
 * @see 第三步:在需要抛异常的地方抛出来就行了,第二步所创建的方法会自动截获并处理的
 * @author http://blog.csdn/net/jadyer
 * @create May 12, 2012 7:28:31 PM
 */
@Controller
@RequestMapping("/user")
@SessionAttributes("loginUser")
public class UserController {
	private final static Map<String,User> users = new HashMap<String,User>();
	
	//模拟数据源,构造初始数据
	public UserController(){
		users.put("张起灵", new User("张起灵", "闷油瓶", "02200059", "[email protected]"));
		users.put("李寻欢", new User("李寻欢", "李探花", "08866659", "[email protected]"));
		users.put("拓拔野", new User("拓拔野", "搜神记", "05577759", "[email protected]"));
		users.put("孙悟空", new User("孙悟空", "美猴王", "03311159", "[email protected]"));
	}
	
	/**
	 * 用于异常处理的方法
	 */
	@ExceptionHandler(UserException.class)
	public String myExceptionHandler(Exception ex, HttpServletRequest request){
		request.setAttribute("myex", ex);
		return "error";
	}
	
	/**
	 * 用户登录
	 * @see SpringMVC会自动收集表单控件值,赋给方法的同名参数上
	 */
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public String login(String username, String password, Model model){
		if(!users.containsKey(username)){
			throw new UserException("用户不存在");
		}
		if(!users.get(username).getPassword().equals(password)){
			throw new UserException("密码不正确");
		}
		model.addAttribute("loginUser", users.get(username)); //将登录用户信息放到HttpSession中
		return "user/loginSuccess";
	}
}

你可能感兴趣的:(SpringMVC中的异常处理)