1、编写拦截器实现类,此类必须实现接口   HandlerInterceptor,然后重写里面需要的三个比较常用的方法,实现自己的业务逻辑代码

如:OneInterceptor

 package com.leecx.interceptors.interceptor;

 import com.leecx.pojo.LeeJSONResult;
import com.leecx.utils.JsonUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException; public class OneInterceptor implements HandlerInterceptor{ /**
* 在请求处理之前进行调用(Controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { System.out.println("=====================");
if (true) {
returnErrorResponse(httpServletResponse, LeeJSONResult.errorMsg("被one拦截..."));
} System.out.println("被one拦截..."); return false;
} /**
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } /**
* 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } public void returnErrorResponse(HttpServletResponse response, LeeJSONResult result) throws IOException, UnsupportedEncodingException {
OutputStream out = null;
try{
response.setCharacterEncoding("utf-8");
response.setContentType("text/json");
out = response.getOutputStream();
out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
out.flush();
} finally{
if(out!=null){
out.close();
}
}
}
}

说明:

1、preHandle  方法会在请求处理之前进行调用(Controller方法调用之前)

2、postHandle  请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)

3、afterCompletion  在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)

2、编写拦截器配置文件主类 WebMvcConfigurer  此类必须继承  WebMvcConfigurerAdapter 类,并重写其中的方法  addInterceptors   并且在主类上加上注解  @Configuration

如:WebMvcConfigurer

 package com.leecx.interceptors.config;

 import com.leecx.interceptors.interceptor.OneInterceptor;
import com.leecx.interceptors.interceptor.TwoInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter{ /**
* <p>Title:</p>
* <p>Description:重写增加自定义拦截器的注册,某一个拦截器需要先注册进来,才能工作</p>
* param[1]: null
* return:
* exception:
* date:2018/4/18 0018 下午 17:29
* author:段美林[duanml@neusoft.com]
*/
@Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**"); registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/one/**")
.addPathPatterns("/two/**"); super.addInterceptors(registry);
}
}

说明:

拦截器的执行是会根据 registry 注入的先后顺序执行,比如:/one/**   同时被  OneInterceptor、TwoInterceptor 拦截,但会先执行 OneInterceptor拦截的业务请求,因为它先注入进来的

3、在controller业务层,只要请求的地址为  拦截器 申明的需要拦截地址即可进入相应的业务处理。

如:OneInterceptorController    这个controller 类的所有实现方法都会被 拦截器  OneInterceptor   所拦截到。

 package com.leecx.controller;

 import java.util.ArrayList;
import java.util.Date;
import java.util.List; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import com.leecx.pojo.User; @Controller
@RequestMapping("/one")
public class OneInterceptorController { @RequestMapping("/index")
public String index(ModelMap map) {
System.out.println("=========one is index");
map.addAttribute("name", "itzixi22");
return "thymeleaf/index";
} @RequestMapping("center")
public String center() {
return "thymeleaf/center/center";
} @RequestMapping("test")
public String test(ModelMap map) { User user = new User();
user.setAge(18);
user.setName("manager");
user.setPassword("123456");
user.setBirthday(new Date()); map.addAttribute("user", user); User u1 = new User();
u1.setAge(19);
u1.setName("itzixi");
u1.setPassword("123456");
u1.setBirthday(new Date()); User u2 = new User();
u2.setAge(17);
u2.setName("LeeCX");
u2.setPassword("123456");
u2.setBirthday(new Date()); List<User> userList = new ArrayList<>();
userList.add(user);
userList.add(u1);
userList.add(u2); map.addAttribute("userList", userList); return "thymeleaf/test";
} @PostMapping("postform")
public String postform(User user) {
System.out.println(user.getName());
return "redirect:/th/test";
}
}

SpringBoot自定义拦截器实现的更多相关文章

  1. SpringBoot自定义拦截器实现IP白名单功能

    SpringBoot自定义拦截器实现IP白名单功能 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8993331.html 首先,相关功能已经上线了,且先让我先 ...

  2. SpringMVC拦截器与SpringBoot自定义拦截器

    首先我们先回顾一下传统拦截器的写法: 第一步创建一个类实现HandlerInterceptor接口,重写接口的方法. 第二步在XML中进行如下配置,就可以实现自定义拦截器了 SpringBoot实现自 ...

  3. SpringBoot(11) SpringBoot自定义拦截器

    自定义拦截器共两步:第一:注册.第二:定义拦截器. 一.注册 @Configuration 继承WebMvcConfigurationAdapter(SpringBoot2.X之前旧版本) 旧版本代码 ...

  4. springboot 2.0+ 自定义拦截器

    之前项目的springboot自定义拦截器使用的是继承WebMvcConfigurerAdapter重写常用方法的方式来实现的. 以下WebMvcConfigurerAdapter 比较常用的重写接口 ...

  5. SpringBoot学习笔记:自定义拦截器

    SpringBoot学习笔记:自定义拦截器 快速开始 拦截器类似于过滤器,但是拦截器提供更精细的的控制能力,它可以在一个请求过程中的两个节点进行拦截: 在请求发送到Controller之前 在响应发送 ...

  6. 【学习】SpringBoot之自定义拦截器

    /** * 自定义拦截器 **/ @Configuration//声明这是一个拦截器 public class MyInterceptor extends WebMvcConfigurerAdapte ...

  7. SpringBoot之自定义拦截器

    一.自定义拦截器实现步骤 1.创建拦截器类并实现HandlerInterceptor接口 2.创建SpringMVC自定义配置类,实现WebMvcConfigurer接口中addInterceptor ...

  8. springboot实现自定义拦截器

    为了更容易理解,我们通过一个代码例子来演示. 例子: 我们现在要访问http://localhost:8080/main.html页面,这个页面需要登录之后才能够浏览,没登录不能浏览. 那么现在问题来 ...

  9. SpringBoot 2.x 自定义拦截器并解决静态资源访问被拦截问题

      自定义拦截器 /** * UserSecurityInterceptor * Created with IntelliJ IDEA. * Author: yangyongkang * Date: ...

随机推荐

  1. 数据结构与算法JavaScript描述——链表

    1.数组的缺点 数组不总是组织数据的最佳数据结构,原因如下. 在很多编程语言中,数组的长度是固定的,所以当数组已被数据填满时,再要加入新的元素就会非常困难. 在数组中,添加和删除元素也很麻烦,因为需要 ...

  2. 1094 The Largest Generation

    题意:略. 思路:层序遍历:在结点中增加一个数据域表示结点所在的层次. 代码: #include <cstdio> #include <queue> #include < ...

  3. Java 连接数据库及字符编码

    通过JDBC方式连接MYSQL数据库: public static Connection getConnection(){ String username="root" ; Str ...

  4. 10 删除topic中的数据

    1 打开    server.properties2  添加一条:  delete.topic.enable=true 3  执行命令:   bin/kafka-topics.sh --delete ...

  5. 设置itemcontrol的item点击前后不同状态

    转自:http://www.cnblogs.com/linzheng/p/3764300.html <Page.Resources> <!--选中数据项的样式--> <D ...

  6. nginx转发请求

    location / { proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_add ...

  7. python 之 Collections模块

    官方文档:https://yiyibooks.cn/xx/python_352/library/collections.html 参考: https://blog.csdn.net/songfreem ...

  8. C#命名规则和风格(收集)

    1.     文件命名组织 1-1文件命名 1.        文件名遵从Pascal命名法,无特殊情况,扩展名小写. 2.        使用统一而又通用的文件扩展名: C# 类 .cs 1-2文件 ...

  9. 第七章 : Git 介绍 (上)[Learn Android Studio 汉化教程]

    Learn Android Studio 汉化教程 [翻译]Git介绍 Git版本控制系统(VCS)快速成为Android应用程序开发以及常规的软件编程领域内的事实标准.有别于需要中心服务器支持的早期 ...

  10. 接口测试基础operation

    Jmeter接口测试 一般分五个步骤: (1)添加线程组 (2)添加http请求 (3)在http请求中写入接入url.路径.请求方式和参数 (4)添加查看结果树 (5)调用接口.查看返回值