博客以Demo的形式讲诉拦截器的使用
项目结构如图:
需要的jar:有springMVC配置需要的jar和jstl需要的jar
SpringMVC包的作用说明:
aopalliance.jar:这个包是AOP联盟的API包,里面包含了针对面向切面的接口。通常spring等其它具备动态织入功能的框架依赖这个jar
spring-core.jar:这个jar 文件包含Spring 框架基本的核心工具类。Spring 其它组件要都要使用到这个包里的类,是其它组件的基本核心
,当然你也可以在自己的应用系统中使用这些工具类。
外部依赖Commons Logging, (Log4J)。
spring-beans.jar:这个jar 文件是所有应用都要用到的,它包含访问配置文件、创建和管理bean 以及进行Inversion of Control /
Dependency Injection(IoC/DI)操作相关的所有类。如果应用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件
就可以了。
spring-aop.jar:这个jar 文件包含在应用中使用Spring 的AOP 特性时所需的类和源码级元数据支持。使用基于AOP 的Spring特性,如声明
型事务管理(Declarative Transaction Management),也要在应用里包含这个jar包。
外部依赖spring-core, (spring-beans,AOP Alliance, CGLIB,Commons Attributes)。
spring-context.jar:这个jar 文件为Spring 核心提供了大量扩展。可以找到使用Spring ApplicationContext特性时所需的全部类,JDNI
所需的全部类,instrumentation组件以及校验Validation 方面的相关类。
外部依赖spring-beans, (spring-aop)。
spring-context-support:Spring-context的扩展支持,用于MVC方面
spring-web.jar
这个jar 文件包含Web 应用开发时,用到Spring 框架时所需的核心类,包括自动载入Web Application Context 特性的类、Struts 与JSF
集成类、文件上传的支持类、Filter 类和大量工具辅助类。
外部依赖spring-context, Servlet API, (JSP API, JSTL, Commons FileUpload, COS)。
spring-webmvc.jar
这个jar 文件包含Spring MVC 框架相关的所有类。包括框架的Servlets,Web MVC框架,控制器和视图支持。当然,如果你的应用使用了独
立的MVC 框架,则无需这个JAR 文件里的任何类。
外部依赖spring-web, (spring-support,Tiles,iText,POI)。
spring-aspects.jar
提供对AspectJ的支持,以便可以方便的将面向方面的功能集成进IDE中,比如Eclipse AJDT。
外部依赖。
spring-jdbc.jar
这个jar 文件包含对Spring 对JDBC 数据访问进行封装的所有类。
外部依赖spring-beans,spring-dao。
spring-test.jar
对Junit等测试框架的简单封装
spring-tx.jar
Spring的tx事务处理的jar
spring-expression.jar
Spring表达式语言
编写控制器:
- package com.mvc.action;
-
- import javax.servlet.http.HttpSession;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
-
-
-
- @Controller
- public class LoginControl {
-
-
-
-
-
-
-
-
-
-
-
- @RequestMapping(value="/login")
- public String login(HttpSession session,String username,String password) throws Exception{
-
- session.setAttribute("username", username);
-
- return "redirect:hello.action";
- }
-
-
-
-
-
-
-
-
- @RequestMapping(value="/logout")
- public String logout(HttpSession session) throws Exception{
-
- session.invalidate();
-
- return "redirect:hello.action";
- }
-
-
-
- }
编写拦截器:- package com.mvc.interceptor;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
-
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
-
-
- public class LoginInterceptor implements HandlerInterceptor{
-
-
-
-
- public void afterCompletion(HttpServletRequest request,
- HttpServletResponse response, Object handler, Exception exc)
- throws Exception {
-
- }
-
-
-
-
- public void postHandle(HttpServletRequest request, HttpServletResponse response,
- Object handler, ModelAndView modelAndView) throws Exception {
- }
-
-
-
-
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
- Object handler) throws Exception {
-
- String url = request.getRequestURI();
-
- if(url.indexOf("login.action")>=0){
- return true;
- }
-
- HttpSession session = request.getSession();
- String username = (String)session.getAttribute("username");
-
- if(username != null){
- return true;
- }
-
- request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
-
- return false;
- }
-
- }
SpringMVC的配置文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
-
-
-
- <context:component-scan base-package="com.mvc.action" />
-
- <!-- 项目的Handler
- <bean name="/hello.action" class="com.mvc.action.HelloAction"></bean>
- -->
-
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
-
-
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
- <property name="messageConverters">
- <list>
- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
- </list>
- </property>
- </bean>
-
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
- <property name="prefix" value="/WEB-INF/jsp/" />
- <property name="suffix" value=".jsp" />
- </bean>
-
-
- <mvc:annotation-driven></mvc:annotation-driven>
-
- <mvc:interceptors>
-
- <mvc:interceptor>
- <mvc:mapping path="/**"/>
- <bean class="com.mvc.interceptor.LoginInterceptor"></bean>
- </mvc:interceptor>
- </mvc:interceptors>
-
- </beans>
登录界面:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'login.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- <form action="${pageContext.request.contextPath}/login.action" method="post">
- 用户名:<input type="text" name="username" /><br>
- 密码:<input type="text" name="password" /><br>
- <input type="submit" value="登录" />
- </form>
- </body>
- </html>
登录成功后,跳转的界面hello.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
- <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'hello.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- 当前用户:${username}
- <c:if test="${username!=null}">
- <a href="${pageContext.request.contextPath }/logout.action">退出</a>
- </c:if>
- ${message}
- </body>
- </html>
HelloControl.java,我写成HelloWorld形式的,自己要根据项目去改哦- package com.mvc.action;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- //标记这个类是一个Handler处理器
- @Controller
- public class HelloAction{
-
- @RequestMapping("/hello")//制定这个控制类对应的url
- public String hello(Model model){
- String message = "SpringMVC";
- //为model添加Attribute
- model.addAttribute("message",message);
- return "hello";
- }
- // public ModelAndView handleRequest(HttpServletRequest request,
- // HttpServletResponse response) throws Exception {
- //
- // //在页面上提示一行信息
- // String message = "hello world!";
- //
- // //通过request对象将信息在页面上展示
- // //request.setAttribute("message", message);
- //
- // ModelAndView modelAndView = new ModelAndView();
- // // 相当于request.setAttribute(), 将数据传到页面展示
- // //model数据
- // modelAndView.addObject("message", message);
- // //设置视图
- // modelAndView.setViewName("hello");
- //
- // return modelAndView;
- // }
-
-
-
-
- }
第二篇
博客以Demo的形式讲诉拦截器的使用
项目结构如图:
需要的jar:有springMVC配置需要的jar和jstl需要的jar
SpringMVC包的作用说明:
aopalliance.jar:这个包是AOP联盟的API包,里面包含了针对面向切面的接口。通常spring等其它具备动态织入功能的框架依赖这个jar
spring-core.jar:这个jar 文件包含Spring 框架基本的核心工具类。Spring 其它组件要都要使用到这个包里的类,是其它组件的基本核心
,当然你也可以在自己的应用系统中使用这些工具类。
外部依赖Commons Logging, (Log4J)。
spring-beans.jar:这个jar 文件是所有应用都要用到的,它包含访问配置文件、创建和管理bean 以及进行Inversion of Control /
Dependency Injection(IoC/DI)操作相关的所有类。如果应用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件
就可以了。
spring-aop.jar:这个jar 文件包含在应用中使用Spring 的AOP 特性时所需的类和源码级元数据支持。使用基于AOP 的Spring特性,如声明
型事务管理(Declarative Transaction Management),也要在应用里包含这个jar包。
外部依赖spring-core, (spring-beans,AOP Alliance, CGLIB,Commons Attributes)。
spring-context.jar:这个jar 文件为Spring 核心提供了大量扩展。可以找到使用Spring ApplicationContext特性时所需的全部类,JDNI
所需的全部类,instrumentation组件以及校验Validation 方面的相关类。
外部依赖spring-beans, (spring-aop)。
spring-context-support:Spring-context的扩展支持,用于MVC方面
spring-web.jar
这个jar 文件包含Web 应用开发时,用到Spring 框架时所需的核心类,包括自动载入Web Application Context 特性的类、Struts 与JSF
集成类、文件上传的支持类、Filter 类和大量工具辅助类。
外部依赖spring-context, Servlet API, (JSP API, JSTL, Commons FileUpload, COS)。
spring-webmvc.jar
这个jar 文件包含Spring MVC 框架相关的所有类。包括框架的Servlets,Web MVC框架,控制器和视图支持。当然,如果你的应用使用了独
立的MVC 框架,则无需这个JAR 文件里的任何类。
外部依赖spring-web, (spring-support,Tiles,iText,POI)。
spring-aspects.jar
提供对AspectJ的支持,以便可以方便的将面向方面的功能集成进IDE中,比如Eclipse AJDT。
外部依赖。
spring-jdbc.jar
这个jar 文件包含对Spring 对JDBC 数据访问进行封装的所有类。
外部依赖spring-beans,spring-dao。
spring-test.jar
对Junit等测试框架的简单封装
spring-tx.jar
Spring的tx事务处理的jar
spring-expression.jar
Spring表达式语言
编写控制器:
- package com.mvc.action;
-
- import javax.servlet.http.HttpSession;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
-
-
-
- @Controller
- public class LoginControl {
-
-
-
-
-
-
-
-
-
-
-
- @RequestMapping(value="/login")
- public String login(HttpSession session,String username,String password) throws Exception{
-
- session.setAttribute("username", username);
-
- return "redirect:hello.action";
- }
-
-
-
-
-
-
-
-
- @RequestMapping(value="/logout")
- public String logout(HttpSession session) throws Exception{
-
- session.invalidate();
-
- return "redirect:hello.action";
- }
-
-
-
- }
编写拦截器:- package com.mvc.interceptor;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
-
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
-
-
- public class LoginInterceptor implements HandlerInterceptor{
-
-
-
-
- public void afterCompletion(HttpServletRequest request,
- HttpServletResponse response, Object handler, Exception exc)
- throws Exception {
-
- }
-
-
-
-
- public void postHandle(HttpServletRequest request, HttpServletResponse response,
- Object handler, ModelAndView modelAndView) throws Exception {
- }
-
-
-
-
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
- Object handler) throws Exception {
-
- String url = request.getRequestURI();
-
- if(url.indexOf("login.action")>=0){
- return true;
- }
-
- HttpSession session = request.getSession();
- String username = (String)session.getAttribute("username");
-
- if(username != null){
- return true;
- }
-
- request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
-
- return false;
- }
-
- }
SpringMVC的配置文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
-
-
-
- <context:component-scan base-package="com.mvc.action" />
-
- <!-- 项目的Handler
- <bean name="/hello.action" class="com.mvc.action.HelloAction"></bean>
- -->
-
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
-
-
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
- <property name="messageConverters">
- <list>
- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
- </list>
- </property>
- </bean>
-
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
- <property name="prefix" value="/WEB-INF/jsp/" />
- <property name="suffix" value=".jsp" />
- </bean>
-
-
- <mvc:annotation-driven></mvc:annotation-driven>
-
- <mvc:interceptors>
-
- <mvc:interceptor>
- <mvc:mapping path="/**"/>
- <bean class="com.mvc.interceptor.LoginInterceptor"></bean>
- </mvc:interceptor>
- </mvc:interceptors>
-
- </beans>
登录界面:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'login.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- <form action="${pageContext.request.contextPath}/login.action" method="post">
- 用户名:<input type="text" name="username" /><br>
- 密码:<input type="text" name="password" /><br>
- <input type="submit" value="登录" />
- </form>
- </body>
- </html>
登录成功后,跳转的界面hello.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
- <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'hello.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- 当前用户:${username}
- <c:if test="${username!=null}">
- <a href="${pageContext.request.contextPath }/logout.action">退出</a>
- </c:if>
- ${message}
- </body>
- </html>
HelloControl.java,我写成HelloWorld形式的,自己要根据项目去改哦- package com.mvc.action;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- //标记这个类是一个Handler处理器
- @Controller
- public class HelloAction{
-
- @RequestMapping("/hello")//制定这个控制类对应的url
- public String hello(Model model){
- String message = "SpringMVC";
- //为model添加Attribute
- model.addAttribute("message",message);
- return "hello";
- }
- // public ModelAndView handleRequest(HttpServletRequest request,
- // HttpServletResponse response) throws Exception {
- //
- // //在页面上提示一行信息
- // String message = "hello world!";
- //
- // //通过request对象将信息在页面上展示
- // //request.setAttribute("message", message);
- //
- // ModelAndView modelAndView = new ModelAndView();
- // // 相当于request.setAttribute(), 将数据传到页面展示
- // //model数据
- // modelAndView.addObject("message", message);
- // //设置视图
- // modelAndView.setViewName("hello");
- //
- // return modelAndView;
- // }
-
-
-
-
- }
Spring MVC也可以使用拦截器对请求进行拦截处理。
自定义拦截器
用户可以通过实现HandlerInterceptor接口,使用自定义的拦截器。
下面展示如何配置自定义的拦截器:
创建拦截器类FirstInterceptor
public class FirstInterceptor implements HandlerInterceptor { /** * 该方法在目标方法之前被调用. * 若返回值为 true, 则继续调用后续的拦截器和目标方法. * 若返回值为 false, 则不会再调用后续的拦截器和目标方法. * * 可以考虑做权限. 日志, 事务等. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("[FirstInterceptor] preHandle"); return true; } /** * 调用目标方法之后, 但渲染视图之前. * 可以对请求域中的属性或视图做出修改. */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("[FirstInterceptor] postHandle"); } /** * 渲染视图之后被调用. 释放资源 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("[FirstInterceptor] afterCompletion"); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
springmvc配置文件
<mvc:interceptors> <bean class="com.MySpringMVC.interceptors.FirstInterceptor"> </bean></mvc:interceptors>
现在只要有任何页面提交请求,拦截器就会工作:
注意:即使页面请求的是不通过控制器,而是通过配置<mvc:view-controller>直接跳转到页面,拦截器也会捕获到请求。
可以通过在<mvc:interceptors>用<mvc:interceptor>配置拦截器,从而指定拦截器对哪些请求起作用,对哪些请求不起作用,例如,我们现在定义另一个拦截器类SecondInterceptor:
springmvc配置文件
<mvc:interceptors> <bean class="com.MySpringMVC.interceptors.FirstInterceptor"> </bean> <mvc:interceptor> <mvc:mapping path="/emps" /> <bean class="com.MySpringMVC.interceptors.SecondInterceptor"></bean> </mvc:interceptor></mvc:interceptors>
创建拦截器类 SecondInterceptor
public class SecondInterceptor implements HandlerInterceptor { /** * 该方法在目标方法之前被调用. * 若返回值为 true, 则继续调用后续的拦截器和目标方法. * 若返回值为 false, 则不会再调用后续的拦截器和目标方法. * * 可以考虑做权限. 日志, 事务等. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("[SecondInterceptor] preHandle"); return true; } /** * 调用目标方法之后, 但渲染视图之前. * 可以对请求域中的属性或视图做出修改. */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("[SecondInterceptor] postHandle"); } /** * 渲染视图之后被调用. 释放资源 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("[SecondInterceptor] afterCompletion"); }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
现在,如果我们在页面上请求访问的路径为emps,那么两个拦截器FirstInterceptor和SecondInterceptor都会起作用,如果请求访问emps路径以外的路径,那么只有FirstInterceptor拦截器会起作用。
拦截器方法及其执行顺序
1、单个拦截器各方法的执行顺序
HandlerInterceptor接口定义了三个方法:
2、多个拦截器之间各方法的执行顺序
当有多个拦截器同时工作时,则它们的preHandle()方法按照拦截器的配置的顺序执行,它们的postHandle()方法和afterCompletion()方法按照配置顺序的反序执行。例如我们在上面的springmvc配置文件中,先配置了FirstInterceptor,后配置了SecondInterceptor,那么当请求两个拦截器都起作用的emps路径时,拦截器的执行顺序为:
即:
如果当SecondInterceptor的preHandle方法返回false时,程序会怎样执行呢?
我们令SecondInterceptor的preHandle方法返回false,运行程序:
即SecondInterceptor的preHandle方法返回false后,仅执行了FirstInterceptor的afterCompletion()方法,查看Spring的源码,我了解到了其工作流程是这样的:
1、当页面发送请求后,DispatcherServlet会通过其中的HandlerExecutionChain对象依次调用各拦截器的的preHandle()方法;
2、查看该HandlerExecutionChain对象,发现其中的interceptors属性记录了当前项目配置的所有拦截器:
其中除了我们自定义的两个拦截器以外,还有一个SpringMVC内置的ConversionServiceExposingInterceptor拦截器。此外,还有一个int型参数interceptorIndex用于记录当前时刻 preHandle()方法已经返回true的拦截器的最大下标,例如现在我们的SecondInterceptor拦截器的preHandle()方法返回了false,那么interceptorIndex参数便为1,代表拦截器ConversionServiceExposingInterceptor和FirstInterceptor的preHandle()方法返回了true:
3、当HandlerExecutionChain对象发现SecondInterceptor拦截器的preHandle()方法返回了false后,便执行triggerAfterCompletion()方法用于从下标值为interceptorIndex开始执行各拦截器的afterCompletion()方法,直到下标值减为-1为止:
那么,我们就很好理解了为什么当SecondInterceptor拦截器的preHandle()方法返回了false后,程序运行结果为上述截图的那样了,运行流程如下:
博客以Demo的形式讲诉拦截器的使用
项目结构如图:
需要的jar:有springMVC配置需要的jar和jstl需要的jar
SpringMVC包的作用说明:
aopalliance.jar:这个包是AOP联盟的API包,里面包含了针对面向切面的接口。通常spring等其它具备动态织入功能的框架依赖这个jar
spring-core.jar:这个jar 文件包含Spring 框架基本的核心工具类。Spring 其它组件要都要使用到这个包里的类,是其它组件的基本核心
,当然你也可以在自己的应用系统中使用这些工具类。
外部依赖Commons Logging, (Log4J)。
spring-beans.jar:这个jar 文件是所有应用都要用到的,它包含访问配置文件、创建和管理bean 以及进行Inversion of Control /
Dependency Injection(IoC/DI)操作相关的所有类。如果应用只需基本的IoC/DI 支持,引入spring-core.jar 及spring-beans.jar 文件
就可以了。
spring-aop.jar:这个jar 文件包含在应用中使用Spring 的AOP 特性时所需的类和源码级元数据支持。使用基于AOP 的Spring特性,如声明
型事务管理(Declarative Transaction Management),也要在应用里包含这个jar包。
外部依赖spring-core, (spring-beans,AOP Alliance, CGLIB,Commons Attributes)。
spring-context.jar:这个jar 文件为Spring 核心提供了大量扩展。可以找到使用Spring ApplicationContext特性时所需的全部类,JDNI
所需的全部类,instrumentation组件以及校验Validation 方面的相关类。
外部依赖spring-beans, (spring-aop)。
spring-context-support:Spring-context的扩展支持,用于MVC方面
spring-web.jar
这个jar 文件包含Web 应用开发时,用到Spring 框架时所需的核心类,包括自动载入Web Application Context 特性的类、Struts 与JSF
集成类、文件上传的支持类、Filter 类和大量工具辅助类。
外部依赖spring-context, Servlet API, (JSP API, JSTL, Commons FileUpload, COS)。
spring-webmvc.jar
这个jar 文件包含Spring MVC 框架相关的所有类。包括框架的Servlets,Web MVC框架,控制器和视图支持。当然,如果你的应用使用了独
立的MVC 框架,则无需这个JAR 文件里的任何类。
外部依赖spring-web, (spring-support,Tiles,iText,POI)。
spring-aspects.jar
提供对AspectJ的支持,以便可以方便的将面向方面的功能集成进IDE中,比如Eclipse AJDT。
外部依赖。
spring-jdbc.jar
这个jar 文件包含对Spring 对JDBC 数据访问进行封装的所有类。
外部依赖spring-beans,spring-dao。
spring-test.jar
对Junit等测试框架的简单封装
spring-tx.jar
Spring的tx事务处理的jar
spring-expression.jar
Spring表达式语言
编写控制器:
- package com.mvc.action;
-
- import javax.servlet.http.HttpSession;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
-
-
-
- @Controller
- public class LoginControl {
-
-
-
-
-
-
-
-
-
-
-
- @RequestMapping(value="/login")
- public String login(HttpSession session,String username,String password) throws Exception{
-
- session.setAttribute("username", username);
-
- return "redirect:hello.action";
- }
-
-
-
-
-
-
-
-
- @RequestMapping(value="/logout")
- public String logout(HttpSession session) throws Exception{
-
- session.invalidate();
-
- return "redirect:hello.action";
- }
-
-
-
- }
编写拦截器:- package com.mvc.interceptor;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
-
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
-
-
-
- public class LoginInterceptor implements HandlerInterceptor{
-
-
-
-
- public void afterCompletion(HttpServletRequest request,
- HttpServletResponse response, Object handler, Exception exc)
- throws Exception {
-
- }
-
-
-
-
- public void postHandle(HttpServletRequest request, HttpServletResponse response,
- Object handler, ModelAndView modelAndView) throws Exception {
- }
-
-
-
-
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
- Object handler) throws Exception {
-
- String url = request.getRequestURI();
-
- if(url.indexOf("login.action")>=0){
- return true;
- }
-
- HttpSession session = request.getSession();
- String username = (String)session.getAttribute("username");
-
- if(username != null){
- return true;
- }
-
- request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
-
- return false;
- }
-
- }
SpringMVC的配置文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
-
-
-
- <context:component-scan base-package="com.mvc.action" />
-
- <!-- 项目的Handler
- <bean name="/hello.action" class="com.mvc.action.HelloAction"></bean>
- -->
-
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
-
-
- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
- <property name="messageConverters">
- <list>
- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
- </list>
- </property>
- </bean>
-
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
- <property name="prefix" value="/WEB-INF/jsp/" />
- <property name="suffix" value=".jsp" />
- </bean>
-
-
- <mvc:annotation-driven></mvc:annotation-driven>
-
- <mvc:interceptors>
-
- <mvc:interceptor>
- <mvc:mapping path="/**"/>
- <bean class="com.mvc.interceptor.LoginInterceptor"></bean>
- </mvc:interceptor>
- </mvc:interceptors>
-
- </beans>
登录界面:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'login.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- <form action="${pageContext.request.contextPath}/login.action" method="post">
- 用户名:<input type="text" name="username" /><br>
- 密码:<input type="text" name="password" /><br>
- <input type="submit" value="登录" />
- </form>
- </body>
- </html>
登录成功后,跳转的界面hello.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
- <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
- <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'hello.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
-
-
- </head>
-
- <body>
- 当前用户:${username}
- <c:if test="${username!=null}">
- <a href="${pageContext.request.contextPath }/logout.action">退出</a>
- </c:if>
- ${message}
- </body>
- </html>
HelloControl.java,我写成HelloWorld形式的,自己要根据项目去改哦- package com.mvc.action;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- //标记这个类是一个Handler处理器
- @Controller
- public class HelloAction{
-
- @RequestMapping("/hello")//制定这个控制类对应的url
- public String hello(Model model){
- String message = "SpringMVC";
- //为model添加Attribute
- model.addAttribute("message",message);
- return "hello";
- }
- // public ModelAndView handleRequest(HttpServletRequest request,
- // HttpServletResponse response) throws Exception {
- //
- // //在页面上提示一行信息
- // String message = "hello world!";
- //
- // //通过request对象将信息在页面上展示
- // //request.setAttribute("message", message);
- //
- // ModelAndView modelAndView = new ModelAndView();
- // // 相当于request.setAttribute(), 将数据传到页面展示
- // //model数据
- // modelAndView.addObject("message", message);
- // //设置视图
- // modelAndView.setViewName("hello");
- //
- // return modelAndView;
- // }
-
-
-
-
- }