SpringMVC -SpringMVC拦截器详解与案例

文章目录

  • SpringMVC拦截器
    • 拦截器(interceptor)的作用
    • 拦截器和过滤器的区别
  • SpringMVC拦截器入门案例
    • 新建项目
      • 导入坐标
      • 编写Spring-mvc.xml
      • 编写web.xml
      • 编写index.jsp
      • 编写TargetController1类
      • 成功测试
      • 编写MyInterceptor类
      • 编写Spring-mvc.xml
      • 成功测试
    • preHandle方法
      • 变更preHandle返回值为true
      • 成功测试
      • 新建error视图
      • 编写preHandle
      • 成功测试
    • postHandle方法
      • 编写postHandle
      • 成功测试
    • 新建MyInterceptor2.java
      • 编写MyInterceptro2.java
      • 编写Spring-mvc.xml
      • 成功测试
        • 注意
  • 拦截器自我总结

SpringMVC拦截器

拦截器(interceptor)的作用

SpringMVC -SpringMVC拦截器详解与案例_第1张图片

拦截器和过滤器的区别

一般Spring或SpringMVC项目用Interceptor

SpringMVC -SpringMVC拦截器详解与案例_第2张图片

SpringMVC拦截器入门案例

SpringMVC -SpringMVC拦截器详解与案例_第3张图片

新建项目

new -> module

SpringMVC -SpringMVC拦截器详解与案例_第4张图片

导入坐标

<dependencies>
  <dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.32version>
  dependency>

  <dependency>
    <groupId>c3p0groupId>
    <artifactId>c3p0artifactId>
    <version>0.9.1.2version>
  dependency>

  <dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.10version>
  dependency>

  <dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
    <scope>testscope>
  dependency>

  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>5.0.5.RELEASEversion>
  dependency>

  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>5.0.5.RELEASEversion>
  dependency>

  <dependency>
    <groupId>javax.servletgroupId>
    <artifactId>javax.servlet-apiartifactId>
    <version>3.0.1version>
    <scope>providedscope>
  dependency>

  <dependency>
    <groupId>javax.servlet.jspgroupId>
    <artifactId>javax.servlet.jsp-apiartifactId>
    <version>2.2.1version>
    <scope>providedscope>
  dependency>

  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webartifactId>
    <version>5.0.5.RELEASEversion>
  dependency>

  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>5.0.5.RELEASEversion>
  dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-coreartifactId>
    <version>2.9.0version>
  dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.9.0version>
  dependency>

  <dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-annotationsartifactId>
    <version>2.9.0version>
  dependency>

  <dependency>
    <groupId>commons-fileuploadgroupId>
    <artifactId>commons-fileuploadartifactId>
    <version>1.3.1version>
  dependency>

  <dependency>
    <groupId>commons-iogroupId>
    <artifactId>commons-ioartifactId>
    <version>2.3version>
  dependency>

  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-jdbcartifactId>
    <version>5.0.5.RELEASEversion>
  dependency>

  <dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-txartifactId>
    <version>5.0.5.RELEASEversion>
  dependency>
dependencies>

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

编写Spring-mvc.xml


<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
">


    <mvc:annotation-driven/>


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    bean>


    <mvc:default-servlet-handler/>


    <context:component-scan base-package="com.taotao.controller"/>

beans>

编写web.xml

  
  <servlet>
    <servlet-name>DispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServletservlet-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...");
    }
}

成功测试

SpringMVC -SpringMVC拦截器详解与案例_第5张图片

编写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>

成功测试

SpringMVC -SpringMVC拦截器详解与案例_第6张图片

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...");
    }
}

成功测试

SpringMVC -SpringMVC拦截器详解与案例_第7张图片

新建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>Titletitle>
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...");
    }
}

成功测试

不带参数

SpringMVC -SpringMVC拦截器详解与案例_第8张图片

参数非 yes

SpringMVC -SpringMVC拦截器详解与案例_第9张图片

参数为yes

SpringMVC -SpringMVC拦截器详解与案例_第10张图片

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...");
    }
}

成功测试

SpringMVC -SpringMVC拦截器详解与案例_第11张图片

新建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>

成功测试

SpringMVC -SpringMVC拦截器详解与案例_第12张图片

注意

拦截器执行先后顺序

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

拦截器自我总结

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

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

你可能感兴趣的:(成长阶段,笔记)