在实际开发中,总存在着这样的场景,比如拦截请求的ip地址,或者在所有的请求都返回相同的数据,如果每一个方法都写出相同数据固然可以实现,但是随着项目的变大,重复的代码会越来越多,所以在这种情况我们可以用拦截器来实现。

最近一直在研究thymeleaf,越发的感觉这个很好用,所以这篇文章也选择结合这个来使用。

新建项目,pom文件如下:

<?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.dalaoyang</groupId>
<artifactId>springboot_interceptor</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>springboot_interceptor</name>
<description>springboot_interceptor</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.15</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

新建一个拦截器CommonInterceptor,继承HandlerInterceptorAdapter。给大家说一下,在继承HandlerInterceptorAdapter有三个拦截器是经常使用的:

1.preHandle在业务处理器处理请求之前被调用

2.postHandle在业务处理器处理请求执行完成后,生成视图之前执行

3.afterCompletion在DispatcherServlet完全处理完请求后被调用

本文使用的是postHandle,代码如下:

package com.dalaoyang.interceptor;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.interceptor
* @email yangyang@dalaoyang.cn
* @date 2018/4/27
*/
@Component
public class CommonInterceptor extends HandlerInterceptorAdapter {
Logger logger = Logger.getLogger(CommonInterceptor.class); //preHandle在业务处理器处理请求之前被调用,
//postHandle在业务处理器处理请求执行完成后,生成视图之前执行
//afterCompletion在DispatcherServlet完全处理完请求后被调用
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
logger.info("请求ip:"+request.getRemoteAddr());
logger.info("请求的方法:"+request.getMethod());
ModelMap modelMap = modelAndView.getModelMap();
modelMap.addAttribute("title","dalaoyang");
}
}

在启动类继承WebMvcConfigurerAdapter来为项目添加拦截器,代码如下:

package com.dalaoyang;

import com.dalaoyang.interceptor.CommonInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication
public class SpringbootInterceptorApplication extends WebMvcConfigurerAdapter { public static void main(String[] args) {
SpringApplication.run(SpringbootInterceptorApplication.class, args);
} @Autowired
CommonInterceptor commonInterceptor; // 增加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(commonInterceptor);
}
}

IndexController负责跳转,代码如下:

package com.dalaoyang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; /**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaaoyang.controller
* @email yangyang@dalaoyang.cn
* @date 2018/4/27
*/ @Controller
public class IndexController { @RequestMapping("/")
public String index(Model model){
model.addAttribute("content","hi , dalaoyang !");
return "index";
}
}

在templates下新建index.html,其中content是controller返回的内容,title是在拦截器中返回的内容,代码如下:

<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title th:text="${title}"></title>
</head>
<body>
<p th:text="${content}"></p>
</body>
</html>

启动项目,访问http://localhost:8888/,控制台如下:

在看一下页面:

源码下载 :大老杨码云

个人网站:https://dalaoyang.cn

SpringBoot拦截器的更多相关文章

  1. Java结合SpringBoot拦截器实现简单的登录认证模块

    Java结合SpringBoot拦截器实现简单的登录认证模块 之前在做项目时需要实现一个简单的登录认证的功能,就寻思着使用Spring Boot的拦截器来实现,在此记录一下我的整个实现过程,源码见文章 ...

  2. SpringBoot拦截器中Bean无法注入(转)

    问题 这两天遇到SpringBoot拦截器中Bean无法注入问题.下面介绍我的思考过程和解决过程: 1.由于其他bean在service,controller层注入一点问题也没有,开始根本没意识到Be ...

  3. 【SpringBoot】SpringBoot拦截器实战和 Servlet3.0自定义Filter、Listener

    =================6.SpringBoot拦截器实战和 Servlet3.0自定义Filter.Listener ============ 1.深入SpringBoot2.x过滤器Fi ...

  4. SpringBoot拦截器中无法注入bean的解决方法

    SpringBoot拦截器中无法注入bean的解决方法 在使用springboot的拦截器时,有时候希望在拦截器中注入bean方便使用 但是如果直接注入会发现无法注入而报空指针异常 解决方法: 在注册 ...

  5. Springboot拦截器未起作用

    之前遇到要使用springboot拦截器却始终未生效的状况,查了网上的博客,大抵都是@Component,@Configuration注解未加,或是使用@ComponentScan增加包扫描,但是尝试 ...

  6. SpringBoot拦截器中service或者redis注入为空的问题

    原文:https://my.oschina.net/u/1790105/blog/1490098 这两天遇到SpringBoot拦截器中Bean无法注入问题.下面介绍我的思考过程和解决过程: 1.由于 ...

  7. springboot + 拦截器 + 注解 实现自定义权限验证

    springboot + 拦截器 + 注解 实现自定义权限验证最近用到一种前端模板技术:jtwig,在权限控制上没有用springSecurity.因此用拦截器和注解结合实现了权限控制. 1.1 定义 ...

  8. Springboot 拦截器配置(登录拦截)

    Springboot 拦截器配置(登录拦截) 注意这里环境为springboot为2.1版本 1.编写拦截器实现类,实现接口   HandlerInterceptor, 重写里面需要的三个比较常用的方 ...

  9. Springboot拦截器实现IP黑名单

    Springboot拦截器实现IP黑名单 一·业务场景和需要实现的功能 以redis作为IP存储地址实现. 业务场景:针对秒杀活动或者常规电商业务场景等,防止恶意脚本不停的刷接口. 实现功能:写一个拦 ...

  10. SpringBoot 拦截器获取http请求参数

    SpringBoot 拦截器获取http请求参数-- 所有骚操作基础 目录 SpringBoot 拦截器获取http请求参数-- 所有骚操作基础 获取http请求参数是一种刚需 定义拦截器获取请求 为 ...

随机推荐

  1. spring-boot与spring-data-JPA的简单整合

    如何在boot中轻松使用JPA <!--首先引入JPA依赖--><dependency> <groupId>org.springframework.boot< ...

  2. 在线版区间众数 hzw的代码。。

    /* 查询区间众数,要求强制在线 设有T个块 1.众数只可能在大块[L,R]里或者两端[l,L) (R,r]里出现 2.大块的众数只要预处理打表一下即可,复杂度n*T(这样的区间有T*T个) 3.两端 ...

  3. windows下Qt播放flash

    Qt  版本:5.1.0 32bit 代码部分,参考1即可.配置发行时,需要将NPSWF32放在项目的plugins\目录中. 否则,可能找不到,导致无法运行. QWebSettings *setti ...

  4. 用ffmpeg把视频编码格式转为h.264

    command: ffmpeg -i infile.mp4 -an -vcodec libx264 -crf 23 outfile.h264

  5. MySQL查看库表的大小

    MySQL数据库空间使用情况查询 如果想知道MySQL数据库中每个表占用的空间.表记录的行数的话,可以打开MySQL的 information_schema 数据库.在该库中有一个 TABLES 表, ...

  6. 原生开发小程序 和 wepy 、 mpvue, Taro 对比

    https://blog.csdn.net/yang450712123/article/details/79623518 mpvue https://www.cnblogs.com/bgwhite/p ...

  7. 卸载win10内置的onenote

    powershell命令如下 get-appxpackage *onenote* | remove-appxpackage

  8. python的学习和使用

    1.python的官网:https://www.python.org/ Python简介: .Python 是一个高层次的结合了解释性.编译性.互动性和面向对象的脚本语言. .Python 的设计具有 ...

  9. jquery轻量级数字动画插件jquery.countup.js

    插件描述: jquery.countup.js 是一款轻量级jquery数字动画插件.该数字动画插件可以在页面滚动时,将指定的数字从0开始计数增加动画. 插件说明 jquery.countup.js  ...

  10. 使用Eclipse绑定Tomcat并发布应用

    l 步骤1:获得服务器运行环境配置,Window/Preferences/Server/Runtime Environmen l步骤2:添加服务器 l步骤3:选择服务器在硬盘的地址,然后所有的都是确定 ...