<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.learn</groupId><artifactId>springmvc_day02_04_interceptor</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>springmvc_day02_04_interceptor Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><spring.version>5.0.2.RELEASE</spring.version></properties><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>jsp-api</artifactId><version>2.0</version><scope>provided</scope></dependency></dependencies>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!-- 开启注解扫描 --><context:component-scan base-package="com.learn"/><!-- 视图解析器对象 --><bean id="internalResourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/pages/"/><property name="suffix" value=".jsp"/></bean><!--配置拦截器--><mvc:interceptors><!--配置拦截器--><mvc:interceptor><!--要拦截的具体的方法--><mvc:mapping path="/user/*"/><!--不要拦截的方法<mvc:exclude-mapping path=""/>--><!--配置拦截器对象--><bean class="com.learn.interceptor.MyInterceptor1" /></mvc:interceptor><!--配置第二个拦截器--><mvc:interceptor><!--要拦截的具体的方法--><mvc:mapping path="/**"/><!--不要拦截的方法<mvc:exclude-mapping path=""/>--><!--配置拦截器对象--><bean class="com.learn.interceptor.MyInterceptor2" /></mvc:interceptor></mvc:interceptors><!-- 开启SpringMVC框架注解的支持 --><mvc:annotation-driven /></beans>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><h3>拦截器</h3><a href="user/testInterceptor" >拦截器</a></body>
</html>
package com.learn.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
@RequestMapping("/user")
public class UserController {@RequestMapping("/testInterceptor")public String testInterceptor(){System.out.println("testInterceptor执行了...");return "success";}}
/** Copyright 2002-2017 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package org.springframework.web.servlet;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;/*** Workflow interface that allows for customized handler execution chains.* Applications can register any number of existing or custom interceptors* for certain groups of handlers, to add common preprocessing behavior* without needing to modify each handler implementation.** <p>A HandlerInterceptor gets called before the appropriate HandlerAdapter* triggers the execution of the handler itself. This mechanism can be used* for a large field of preprocessing aspects, e.g. for authorization checks,* or common handler behavior like locale or theme changes. Its main purpose* is to allow for factoring out repetitive handler code.** <p>In an asynchronous processing scenario, the handler may be executed in a* separate thread while the main thread exits without rendering or invoking the* {@code postHandle} and {@code afterCompletion} callbacks. When concurrent* handler execution completes, the request is dispatched back in order to* proceed with rendering the model and all methods of this contract are invoked* again. For further options and details see* {@code org.springframework.web.servlet.AsyncHandlerInterceptor}** <p>Typically an interceptor chain is defined per HandlerMapping bean,* sharing its granularity. To be able to apply a certain interceptor chain* to a group of handlers, one needs to map the desired handlers via one* HandlerMapping bean. The interceptors themselves are defined as beans* in the application context, referenced by the mapping bean definition* via its "interceptors" property (in XML: a &lt;list&gt; of &lt;ref&gt;).** <p>HandlerInterceptor is basically similar to a Servlet Filter, but in* contrast to the latter it just allows custom pre-processing with the option* of prohibiting the execution of the handler itself, and custom post-processing.* Filters are more powerful, for example they allow for exchanging the request* and response objects that are handed down the chain. Note that a filter* gets configured in web.xml, a HandlerInterceptor in the application context.** <p>As a basic guideline, fine-grained handler-related preprocessing tasks are* candidates for HandlerInterceptor implementations, especially factored-out* common handler code and authorization checks. On the other hand, a Filter* is well-suited for request content and view content handling, like multipart* forms and GZIP compression. This typically shows when one needs to map the* filter to certain content types (e.g. images), or to all requests.** @author Juergen Hoeller* @since 20.06.2003* @see HandlerExecutionChain#getInterceptors* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter* @see org.springframework.web.servlet.handler.AbstractHandlerMapping#setInterceptors* @see org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor* @see org.springframework.web.servlet.i18n.LocaleChangeInterceptor* @see org.springframework.web.servlet.theme.ThemeChangeInterceptor* @see javax.servlet.Filter*/
public interface HandlerInterceptor {/*** Intercept the execution of a handler. Called after HandlerMapping determined* an appropriate handler object, but before HandlerAdapter invokes the handler.* <p>DispatcherServlet processes a handler in an execution chain, consisting* of any number of interceptors, with the handler itself at the end.* With this method, each interceptor can decide to abort the execution chain,* typically sending a HTTP error or writing a custom response.* <p><strong>Note:</strong> special considerations apply for asynchronous* request processing. For more details see* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.* <p>The default implementation returns {@code true}.* @param request current HTTP request* @param response current HTTP response* @param handler chosen handler to execute, for type and/or instance evaluation* @return {@code true} if the execution chain should proceed with the* next interceptor or the handler itself. Else, DispatcherServlet assumes* that this interceptor has already dealt with the response itself.* @throws Exception in case of errors*/default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {return true;}/*** Intercept the execution of a handler. Called after HandlerAdapter actually* invoked the handler, but before the DispatcherServlet renders the view.* Can expose additional model objects to the view via the given ModelAndView.* <p>DispatcherServlet processes a handler in an execution chain, consisting* of any number of interceptors, with the handler itself at the end.* With this method, each interceptor can post-process an execution,* getting applied in inverse order of the execution chain.* <p><strong>Note:</strong> special considerations apply for asynchronous* request processing. For more details see* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.* <p>The default implementation is empty.* @param request current HTTP request* @param response current HTTP response* @param handler handler (or {@link HandlerMethod}) that started asynchronous* execution, for type and/or instance examination* @param modelAndView the {@code ModelAndView} that the handler returned* (can also be {@code null})* @throws Exception in case of errors*/default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable ModelAndView modelAndView) throws Exception {}/*** Callback after completion of request processing, that is, after rendering* the view. Will be called on any outcome of handler execution, thus allows* for proper resource cleanup.* <p>Note: Will only be called if this interceptor's {@code preHandle}* method has successfully completed and returned {@code true}!* <p>As with the {@code postHandle} method, the method will be invoked on each* interceptor in the chain in reverse order, so the first interceptor will be* the last to be invoked.* <p><strong>Note:</strong> special considerations apply for asynchronous* request processing. For more details see* {@link org.springframework.web.servlet.AsyncHandlerInterceptor}.* <p>The default implementation is empty.* @param request current HTTP request* @param response current HTTP response* @param handler handler (or {@link HandlerMethod}) that started asynchronous* execution, for type and/or instance examination* @param ex exception thrown on handler execution, if any* @throws Exception in case of errors*/default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable Exception ex) throws Exception {}}
package com.learn.interceptor;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** 自定义拦截器*/
public class MyInterceptor1 implements HandlerInterceptor{/*** 预处理,controller方法执行前* return true 放行,执行下一个拦截器,如果没有,执行controller中的方法* return false不放行* @param request* @param response* @param handler* @return* @throws Exception*/public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {System.out.println("MyInterceptor1执行了...前1111");// request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);return true;}/*** 后处理方法,controller方法执行后,success.jsp执行之前* @param request* @param response* @param handler* @param modelAndView* @throws Exception*/public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("MyInterceptor1执行了...后1111");// request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);}/*** success.jsp页面执行后,该方法会执行* @param request* @param response* @param handler* @param ex* @throws Exception*/public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("MyInterceptor1执行了...最后1111");}}
package com.learn.interceptor;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** 自定义拦截器*/
public class MyInterceptor2 implements HandlerInterceptor{/*** 预处理,controller方法执行前* return true 放行,执行下一个拦截器,如果没有,执行controller中的方法* return false不放行* @param request* @param response* @param handler* @return* @throws Exception*/public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {System.out.println("MyInterceptor2执行了...前2222");// request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);return true;}/*** 后处理方法,controller方法执行后,success.jsp执行之前* @param request* @param response* @param handler* @param modelAndView* @throws Exception*/public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("MyInterceptor2执行了...后2222");// request.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(request,response);}/*** success.jsp页面执行后,该方法会执行* @param request* @param response* @param handler* @param ex* @throws Exception*/public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("MyInterceptor2执行了...最后2222");}}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><h3>错误页面</h3></body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><h3>执行成功</h3><% System.out.println("success.jsp执行了..."); %></body>
</html>

SpringMVC拦截器之拦截器接口方法演示相关推荐

  1. 【SpringMVC】自定义拦截器和过滤器

    一.闲话 五一假期明天结束了,咬咬牙把SpringMVC结束掉 二.基本要点 1.过滤器 除了之前我们提到的spring提供的过滤器之外,我们还可以自定义过滤器,使用步骤如下 编写java类实现Fil ...

  2. (转)SpringMVC学习(十二)——SpringMVC中的拦截器

    http://blog.csdn.net/yerenyuan_pku/article/details/72567761 SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter, ...

  3. 【SpringMVC学习11】SpringMVC中的拦截器

    Springmvc的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理.本文主要总结一下springmvc中拦截器是如何定义的,以及测试拦截器的执行情况和使用 ...

  4. Java过滤器与SpringMVC拦截器之间的关系与区别

    今天学习和认识了一下,过滤器和SpringMVC的拦截器的区别,学到了不少的东西,以前一直以为拦截器就是过滤器实现的,现在想想还真是一种错误啊,而且看的比较粗浅,没有一个全局而又细致的认识,由于已至深 ...

  5. SpringMVC中的拦截器

    SpringMVC中的拦截器 拦截器的作用 Spring MVC 的处理器拦截器类似于 Servlet 开发中的过滤器 Filter,用于对处理器进行预处理和后处理. 用户可以自己定义一些拦截器来实现 ...

  6. springMVC之Interceptor拦截器

    转自:https://blog.csdn.net/qq_25673113/article/details/79153547 Interceptor拦截器用于拦截Controller层接口,表现形式有点 ...

  7. 框架:SpringMVC中Interceptor拦截器的两种实现

    Spring中使用Interceptor拦截器 SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,它的主要作用是拦截用户的请求并进行相应的处理.比如通过它来进行权限验证, ...

  8. springMVC 过滤器与拦截器的执行顺序问题。springboot一样参考

    最近项目要搞国际化,发现做国际化的时候是需要添加拦截器的,但是我们项目是通过filter过滤器做登录拦截,此时的报错信息总是国际化失败.折腾半天发现原因是国际化的拦截器没有用到导致.所以在此研究了下过 ...

  9. Springmvc中的拦截器interceptor及与过滤器filter的区别

    一.Springmvc中的拦截器概述及与过滤器filter的区别 1).Springmvc中的拦截器interceptor用于对控制器controller进行预处理和后处理的技术; 2).可以定义拦截 ...

最新文章

  1. RabbitMQ之消息确认机制(事务+Confirm)
  2. 桌面图标计算机的意义,关于电脑桌面图标的3个古老问题,答对一个都是高手,你会几个?...
  3. java单链表查询功能,Java 实现简答的单链表的功能
  4. P3292 [SCOI2016]幸运数字(树剖 + 线段树维护线性基)
  5. Win10 安装 MongoDB 3.6.5 失败的问题及解决方法
  6. 深入解析Node.js setTimeout方法的执行过程
  7. linux发包密码,linux下网络发包工具(cp过来的)
  8. win7下搭建opengl es 2.0开发环境
  9. 【转载】面向对象建模与数据库建模两种分析设计方法的比较
  10. 计算机毕业设计中用java/php/net/pythont物流配送中心管理系统设计
  11. eclipse python_一文教你配置得心应手的Python
  12. html货币相关符号
  13. Android中向ContactsProvider中插入大量联系人
  14. 交通灯控制(软件延时法)C语言,智能交通灯控制系统软件部分(49页)-原创力文档...
  15. HTML5网页设计实例:企业网站设计——红色文化传媒网站(20页) HTML+CSS+JavaScript
  16. 树莓派4B系统搭建(超详细版)
  17. SQL(09)_UNIQUE 约束
  18. 追踪算法MUSTer体验
  19. iOS开发-Please sign in with an app-specific password. You can create one at appleid.apple.com
  20. 交换机和BBU的接口编号以及华为ATN950 BBU接口写法

热门文章

  1. 用JavaScript实现图片剪切效果
  2. Keymob浅析2016网络营销十大趋势
  3. 安卓开发笔记——关于图片的三级缓存策略(内存LruCache+磁盘DiskLruCache+网络Volley)...
  4. 深入理解 Angular 变化检测(change detection)
  5. php通用的树型类创建无限级树型菜单
  6. 网站防刷方案 -摘自网络
  7. Revit API创建标高,单位转换
  8. 查看was中项目类的加载顺序
  9. Go 语言:我那么值钱,我骄傲了吗?
  10. 连续 4 年成为“开发者最喜欢的语言”,这门编程语言你了解过吗?