springMVC入门-08

  这一讲介绍用户登录实现以及两种异常处理controller控制器的方法,最后提一下在springMVC中对静态资源访问的实现方法。

  用户登录需要一个登录页面login.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>Insert title here</title>
</head>
<body>
<form action="user/login" method="post">
Username:<input type="text" name="username"/><br/>
Password:<input type="password" name="password"/><br/>
<input type="submit"/>
</form>
</body>
</html>
View Code

  在controller类中login方法入参为传入的username和password,将对应字段需要存到session中,代码如下所示:

@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(String username,String password,HttpSession session) {
    if(!users.containsKey(username)) {
        throw new UserException("用户名不存在");
    }
   Users u = users.get(username);
    if(!u.getPassword().equals(password)) {
       throw new UserException("用户密码不正确");
    }
    session.setAttribute("loginUser", u);
    return "redirect:/user/users";
}
View Code

  在login方法中如果用户名或者密码不匹配会跑出userexception异常,这种异常需要匹配到error页面,因此针对异常有两种处理方法:局部异常和全局异常。局部异常可以针对具体的控制器将异常信息包装之后返回到error.jsp页面,全局异常是将异常信息(如userexception)在配置文件中声明,指定对应跳转的页面即可。

  局部异常的代码如下所示:

/**
 * 局部异常处理,仅仅只能处理这个控制器中的异常
 */
@ExceptionHandler(value={UserException.class})
public String handlerException(UserException e,HttpServletRequest req) {
    req.setAttribute("e",e);
    return "error";
}
View Code

    对应局部异常在前台页面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>Insert title here</title>
</head>
<body>
发现错误:
<h1>${e.message}</h1>
</body>
</html>
View Code

    全局异常在xxx-servlet.xml配置文件中对应使用SimpleMappingExceptionResolver来实现全局异常的捕获,针对可能会出现的自定义异常都可以在之下的prop节点下进行配置,对应代码如下所示:

<!-- 使用SimpleMappingExceptionResolver来拦截全局异常 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
            <!--key指定抛出的异常类,value指定跳转的页面-->
            <prop key="zttc.itat.model.UserException">error</prop>
        </props>
    </property>
</bean>
View Code

  对应全局异常的对象为exception,获取之后在前台使用${exception.message}来进行显示。
  在springMVC中要访问静态资源文件,可以在xxx-servlet.xml配置文件中使用以下代码来实现:

    <!-- 将静态文件指定到某个特殊的文件夹中(resources文件夹)统一处理 ,此处mapping表示处理resources文件夹以及其子文件夹的内容-->
    <mvc:resources location="/resources/" mapping="/resources/**"/>

posted @ 2015-03-10 23:13  birdman-peter  阅读(127)  评论(0编辑  收藏  举报