在实际开发中,总存在着这样的场景,比如拦截请求的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. React-Native到0.44版本后Navigator 不能用的问题

    新升级  到0.46版本以后 Navigator 不能使用报错. 'Navigator is deprecated and has been removed from this package. It ...

  2. SpringBoot获取配置文件的自定义参数

    1.在application.properties中自定义参数 spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datas ...

  3. eclipse php pdt插件安装

    安装动态语言工具包: help->new install software->work with 框输入 http://download.eclipse.org/technology/dl ...

  4. python项目实战三个小实例

    1.   让用户输入圆的半径,告诉用户圆的面积: import math while True:     # 用户输入     r = input("请输入圆的半径:")     ...

  5. HDU 3336 Count the string(next数组运用)

    Count the string Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  6. caffe调loss方法

    正文 what should I do if... ...my loss diverges? (increases by order of magnitude, goes to inf. or NaN ...

  7. 关于yum网络版仓库(本地yum仓库的安装配置,如果没网了,做一个局域网内的yum仓库)

    2017-11-13 22:49:48 1:两种方式:   a.每一台机器都配一个本地文件系统上的yum仓库 file:///packege/path/ b.在局域网内部配置一台节点(server-b ...

  8. 最小生成树模板【kruskal & prim】

    CDOJ 1966 Kruskal 解法 时间复杂度O(mlogm) m为边数,这里主要是边排序占时间,后面并查集还好 #include <cstdio> #include <cst ...

  9. java web获取请求体内容

    Java Web中如何获取请求体内容呢? 我们知道请求方式分为两种:Get,Post. /*** * Compatible with GET and POST * * @param request * ...

  10. python全栈开发day92-day96 Vue总结

    -- ES6常用语法 -- var let const -- 模板字符串 -- 反引号 -- ${} -- 箭头函数 -- 普通函数取决于函数最近的调用者 -- 箭头函数取决当前环境 -- 类 -- ...