IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> SpringMVC -SpringMVC拦截器详解与案例 -> 正文阅读

[Java知识库]SpringMVC -SpringMVC拦截器详解与案例

SpringMVC拦截器

拦截器(interceptor)的作用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0oBqr3aU-1650703595670)(spring.assets/image-20220423121032784.png)]

拦截器和过滤器的区别

一般Spring或SpringMVC项目用Interceptor

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UMQDofny-1650703595670)(spring.assets/image-20220423121124175.png)]

SpringMVC拦截器入门案例

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lo0Y2TqI-1650703595671)(spring.assets/image-20220423121618546.png)]

新建项目

new -> module

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wNPWyACX-1650703595671)(spring.assets/image-20220423122024416.png)]

导入坐标

<dependencies>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.32</version>
  </dependency>

  <dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
  </dependency>

  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
  </dependency>

  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.5.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.5.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
  </dependency>

  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.2.1</version>
    <scope>provided</scope>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.0.5.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.5.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.0</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0</version>
  </dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.0</version>
  </dependency>

  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>

  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.3</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.0.5.RELEASE</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.5.RELEASE</version>
  </dependency>
</dependencies>

<build>
<plugins>
  <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.2</version>
  </plugin>
</plugins>
</build>

编写Spring-mvc.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.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">

<!--    1.mvc注解驱动-->
    <mvc:annotation-driven/>

<!--    2.配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

<!--    3.静态资源权限开放-->
    <mvc:default-servlet-handler/>

<!--    4.组件扫描 扫描Controller-->
    <context:component-scan base-package="com.taotao.controller"/>

</beans>

编写web.xml

  <!--配置SpringMVC的前端控制器-->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

编写index.jsp

<%@page language="java"  contentType="text/html;charset=UTF-8" %>
<%@page isELIgnored="false"%>
<html>
<body>
<h2>Hello World!${name}</h2>
</body>
</html>

编写TargetController1类

package com.taotao.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * create by 刘鸿涛
 * 2022/4/23 15:39
 */
@SuppressWarnings({"all"})
public class MyInterceptor1 implements HandlerInterceptor {
    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        return false;
    }

    //在目标方法执行之后 视图对象返回之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    //在流程都执行完毕后 执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

成功测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VutEabAz-1650703595672)(spring.assets/image-20220423153804238.png)]

编写MyInterceptor类

package com.taotao.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * create by 刘鸿涛
 * 2022/4/23 15:39
 */
@SuppressWarnings({"all"})
public class MyInterceptor implements HandlerInterceptor {
    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        return false;
    }

    //在目标方法执行之后 视图对象返回之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    //在流程都执行完毕后 执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

编写Spring-mvc.xml

配置拦截器

<!--    配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
<!--            对哪些资源执行拦截操作-->
            <mvc:mapping path="/**"/>
            <bean class="com.taotao.interceptor.MyInterceptor1"/>
        </mvc:interceptor>
    </mvc:interceptors>

成功测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qTRs3w9t-1650703595673)(spring.assets/image-20220423155157631.png)]

preHandle方法

变更preHandle返回值为true

编写MyInterceptor1.java

package com.taotao.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * create by 刘鸿涛
 * 2022/4/23 15:39
 */
@SuppressWarnings({"all"})
public class MyInterceptor1 implements HandlerInterceptor {
    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        return true;
    }

    //在目标方法执行之后 视图对象返回之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    //在流程都执行完毕后 执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

成功测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KFAPLFsC-1650703595674)(spring.assets/image-20220423155352277.png)]

新建error视图

<%--
  Created by IntelliJ IDEA.
  User: guigui
  Date: 2022/4/23
  Time: 16:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>error!!</h1>
</body>
</html>

编写preHandle

编写MyInterceptor.java

package com.taotao.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * create by 刘鸿涛
 * 2022/4/23 15:39
 */
@SuppressWarnings({"all"})
public class MyInterceptor1 implements HandlerInterceptor {
    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        String param = request.getParameter("param");
        if(param.equals("yes")){
            return true;    //返回true代表放行 false代表不放行
        }else{
            //跳转视图到error.jsp
            request.getRequestDispatcher("/error.jsp").forward(request,response);
            return false;
        }
    }

    //在目标方法执行之后 视图对象返回之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    //在流程都执行完毕后 执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

成功测试

不带参数

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s3a4hsym-1650703595675)(spring.assets/image-20220423162433355.png)]

参数非 yes

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QXocSM1f-1650703595675)(spring.assets/image-20220423162521855.png)]

参数为yes

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-y2JFaEye-1650703595676)(spring.assets/image-20220423162552720.png)]

postHandle方法

编写postHandle

modelAndView.addObject("name","liuhongtao");
package com.taotao.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * create by 刘鸿涛
 * 2022/4/23 15:39
 */
@SuppressWarnings({"all"})
public class MyInterceptor1 implements HandlerInterceptor {
    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle...");
        String param = request.getParameter("param");
        if("yes".equals(param)){
            return true;    //返回true代表放行 false代表不放行
        }else{
            //跳转视图到error.jsp
            request.getRequestDispatcher("/error.jsp").forward(request,response);
            return false;
        }
    }

    //在目标方法执行之后 视图对象返回之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        modelAndView.addObject("name","liuhongtao");
        System.out.println("postHandle...");
    }

    //在流程都执行完毕后 执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

成功测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f84w0xOx-1650703595677)(spring.assets/image-20220423163145867.png)]

新建MyInterceptor2.java

编写MyInterceptro2.java

package com.taotao.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * create by 刘鸿涛
 * 2022/4/23 15:39
 */
@SuppressWarnings({"all"})
public class MyInterceptor2 implements HandlerInterceptor {
    //在目标方法执行之前 执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle2222222...");
        return true;    //返回true代表放行 false代表不放行

    }

    //在目标方法执行之后 视图对象返回之前执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        modelAndView.addObject("name","liuhongtao");
        System.out.println("postHandle2222...");
    }

    //在流程都执行完毕后 执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion2222...");
    }
}

编写Spring-mvc.xml

<!--    配置拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
<!--            对哪些资源执行拦截操作-->
            <mvc:mapping path="/**"/>
            <bean class="com.taotao.interceptor.MyInterceptor1"/>
        </mvc:interceptor>

        <mvc:interceptor>
            <!--            对哪些资源执行拦截操作-->
            <mvc:mapping path="/**"/>
            <bean class="com.taotao.interceptor.MyInterceptor2"/>
        </mvc:interceptor>
    </mvc:interceptors>

成功测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1vtiqTpH-1650703595677)(spring.assets/image-20220423163656450.png)]

注意

拦截器执行先后顺序

1号拦截器先执行的原因,是因为xml配置拦截器的先后顺序

拦截器自我总结

鬼鬼骑士:
学完spring-mvc拦截器后关于我对“面向切面(AOP)”编程的简述:

鬼鬼骑士:
在一个类中编写流程代码可以轻松控制整个项目“开始”,“跳转”,“终止过程”,这个类叫做拦截器,我们仅仅需要在xml配置文件中开启或关闭此拦截器类,来确认是否应该应用此“过程”

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-04-24 09:15:04  更:2022-04-24 09:17:32 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 2:45:22-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码