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. 1.远程仓库的使用(github)

    1.登录Github,新建一个仓库(远程仓库) (1)使用Github账号密码登录 (2)点击+旁边的小三角,选择new repository--输入repository name--点击create ...

  2. Python nltk English Detection

    http://blog.alejandronolla.com/2013/05/15/detecting-text-language-with-python-and-nltk/ >>> ...

  3. 20165226 2017-2018-4 《Java程序设计》第8周学习总结

    20165226 2017-2018-4 <Java程序设计>第8周学习总结 教材学习内容总结 第十二章 创建线程的方式有三种,分别是: - 继承Thread类创建线程,程序中如果想要获取 ...

  4. 模拟admin组件自己开发stark组件之自定义list_display,反向解析url

    反向解析 在上一篇文章中,我们创建好了stark这个组件,一个应用一个表有四个默认的url,那么我们如何区别这些url,因为可能会有重复现象(本组件不会,因为前面拼接了应用名,表明,肯定唯一),概念请 ...

  5. 使用wifi网卡笔记3---工具wpa_supplicant(STA模式)

    1.  wpa_supplicant介绍 supplicant是恳求者的意思,是wpa的发起者,是发送认证请求的设备(手机),手机--AP--认证服务器,可用于上述4种"认证/加密" ...

  6. 【做题记录】USACO silver * 50(第一篇)

    由于我太菜,决定按照AC人数从小到大慢慢做. BZOJ开了权限号真的快了好多诶~ 29/50 1606: [Usaco2008 Dec]Hay For Sale 购买干草 背包dp 1610: [Us ...

  7. WordSmith2013-7-31

    WordSmith Good Evening Ladies and Gentlemen,I’am Jason,I’m pleasured  to be wordsmith tonight. First ...

  8. input标签存在的兼容问题?

    当input标签在type为text时,在Firefox和Safari中的默认高度为22像素(包括上下边框)宽度为146像素(包括左右边框),而在IE中的默认高度为24像素,而宽度却和Firefox和 ...

  9. Storm概念理解

    组成: Topology是Storm里的最高抽象概念,相当于Hadoop里的MapReduce,Topology(流转换图)由Spouts和Bolts组成.Spout创建Stream,Stream由无 ...

  10. 用嵌套List实现DataGrid的主从表显示

    //首先构造嵌套List,也就是一个list在另一个list中充当成员//如:referModels 在res中充当成员var res = totalAffectedMedels.Select(c = ...