已经讲解异常处理机制,本身springmvc已经讲解完毕,后面两个内容为了解。拦截器在我们项目总还是很常用了,我用一个登录简单方法作为例子讲解。
我们经常看到各种resultful,其实就是一种规范。我简单贴出一个springmvc符合规范的例子;所谓规范就是四钟方法:get post put delete,而我们常用为前两种。没有参数,每一个url代表一个资源;
按照规范是用斜线代替的
<servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
@RequestMapping("/viewItems/{id}") @ResponseBody public ItemsCustom viewItemsCustom(@PathVariable("id") Integer id)throws Exception{ ItemsCustom itemsCustom = itemsService.getItemsById(id); return itemsCustom; }
<!--========================================静态资源=======================================================--> <mvc:resources mapping="/js/**" location="pages/jsp/js/"></mvc:resources>
<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping>
用户请求到DispatherServlet中,DispatherServlet调用HandlerMapping查找Handler,HandlerMapping返回一个拦截的链儿(多个拦截),springmvc中的拦截器是通过HandlerMapping发起的。在企业开发,使用拦截器实现用户认证(用户登陆后进行身份校验拦截),用户权限拦截。
<!--========================================拦截器态资源==============================================--> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="handlerInterceptor01"/> <ref bean="handlerInterceptor02"/> </list> </property> </bean> <bean id="handlerInterceptor01" class="com.ycy.interceptor.HandlerInterceptor01"/> <bean id="handlerInterceptor02" class="com.ycy.interceptor.HandlerInterceptor02"/>
<mvc:interceptors> <!--多个拦截器,顺序执行 --> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.ycy.interceptor.HandlerInterceptor01"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.ycy.interceptor.HandlerInterceptor02"></bean> </mvc:interceptor> </mvc:interceptors>
package com.ycy.interceptor; /** * Created by Administrator on 2015/10/10 0010. */ import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 拦截器01 */ public class HandlerInterceptor01 implements HandlerInterceptor{ //执行handler之前: // 用户校验等等 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return false; } //执行handler,返回modelAndView之前: //页面公共属性,视图信息 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } //执行handler后: //统一异常,性能监控等,统一日志 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
1】执行preHandle是顺序执行。执行postHandle、afterCompletion是倒序执行
2】只要有一个拦截器不放行,controller不能执行完成
3】只有前边的拦截器preHandle方法放行,下边的拦截器的preHandle才执行
package com.ycy.controller; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * <p>Title: LoginController</p> * <p>Description: 登陆和退出</p> */ @Controller public class LoginController { //用户登陆提交方法 @RequestMapping("/login") public String login(HttpSession session, String usercode,String password)throws Exception{ //调用service校验用户账号和密码的正确性 //.. //如果service校验通过,将用户身份记录到session session.setAttribute("username", usercode); //重定向到商品查询页面 return "redirect:/items/queryItems"; } //用户退出 @RequestMapping("/logout") public String logout(HttpSession session)throws Exception{ //session失效 session.invalidate(); //重定向到商品查询页面 return "redirect:/items/queryItems"; } }
<%@ 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> <form action="${pageContext.request.contextPath }/login.action"> 用户账号:<input type="text" name="usercode" /><br/> 用户密码 :<input type="password" name="password" /><br/> <input type="submit" value="登陆"/> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>查询商品列表</title> <script type="text/javascript"> //--------------------------------------批量删除商品---------------------------------------------- function deleteItems(){ document.itemsForm.action="${pageContext.request.contextPath }/items/deleteItems"; document.itemsForm.submit(); } </script> </head> <body> 当前用户:${username } <c:if test="${username!=null }"> <a href="${pageContext.request.contextPath }/logout">退出</a> </c:if> <form name="itemsForm" action="${pageContext.request.contextPath }/items/queryItem" method="post"> 查询条件: <table width="100%" border=1> <tr> <td><input type="submit" value="查询"/><input type="button" value="批量删除" onclick="deleteItems()"/> <select> <c:forEach items="${itemtype}" var="item"> <option value="${item.key}">${item.value}</option> </c:forEach> </select> </td> </tr> </table> 商品列表:33 <table width="100%" border=1> <tr> <td>商品名称</td> <td>商品价格</td> <td>生产日期</td> <td>商品描述</td> <td>操作</td> </tr> <c:forEach items="${itemsList}" var="item"> <tr> <td><input type="checkbox" name="delete_id" value="${item.id}"/></td> <td>${item.name}</td> <td>${item.price}</td> <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td> <td>${item.detail}</td> <td><a href="${pageContext.request.contextPath }/items/editItems?id=${item.id}">修改</a></td> <td><a href="${pageContext.request.contextPath }/items/viewItems/${item.id}">查询商品信息</a></td> </tr> </c:forEach> </table> </form> </body> </html>
package com.ycy.controller; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * * <p>Title: LoginController</p> * <p>Description: 登陆和退出</p> * <p>Company: www.itcast.com</p> * @author 传智.燕青 * @date 2015-3-22下午4:43:26 * @version 1.0 */ @Controller public class LoginController { //用户登陆提交方法 @RequestMapping("/login") public String login(HttpSession session, String usercode,String password)throws Exception{ //调用service校验用户账号和密码的正确性 //.. //如果service校验通过,将用户身份记录到session session.setAttribute("username", usercode); //重定向到商品查询页面 return "redirect:/items/queryItems"; } //用户退出 @RequestMapping("/logout") public String logout(HttpSession session)throws Exception{ //session失效 session.invalidate(); //重定向到商品查询页面 return "redirect:/items/queryItems"; } }
<!--拦截器 --> <mvc:interceptors> <!--多个拦截器,顺序执行 --> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.ycy.interceptor.HandlerInterceptor01"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.ycy.interceptor.HandlerInterceptor02"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.ycy.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>