SpringBoot自定义拦截器实现
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自定义拦截器实现的更多相关文章
- SpringBoot自定义拦截器实现IP白名单功能
SpringBoot自定义拦截器实现IP白名单功能 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8993331.html 首先,相关功能已经上线了,且先让我先 ...
- SpringMVC拦截器与SpringBoot自定义拦截器
首先我们先回顾一下传统拦截器的写法: 第一步创建一个类实现HandlerInterceptor接口,重写接口的方法. 第二步在XML中进行如下配置,就可以实现自定义拦截器了 SpringBoot实现自 ...
- SpringBoot(11) SpringBoot自定义拦截器
自定义拦截器共两步:第一:注册.第二:定义拦截器. 一.注册 @Configuration 继承WebMvcConfigurationAdapter(SpringBoot2.X之前旧版本) 旧版本代码 ...
- springboot 2.0+ 自定义拦截器
之前项目的springboot自定义拦截器使用的是继承WebMvcConfigurerAdapter重写常用方法的方式来实现的. 以下WebMvcConfigurerAdapter 比较常用的重写接口 ...
- SpringBoot学习笔记:自定义拦截器
SpringBoot学习笔记:自定义拦截器 快速开始 拦截器类似于过滤器,但是拦截器提供更精细的的控制能力,它可以在一个请求过程中的两个节点进行拦截: 在请求发送到Controller之前 在响应发送 ...
- 【学习】SpringBoot之自定义拦截器
/** * 自定义拦截器 **/ @Configuration//声明这是一个拦截器 public class MyInterceptor extends WebMvcConfigurerAdapte ...
- SpringBoot之自定义拦截器
一.自定义拦截器实现步骤 1.创建拦截器类并实现HandlerInterceptor接口 2.创建SpringMVC自定义配置类,实现WebMvcConfigurer接口中addInterceptor ...
- springboot实现自定义拦截器
为了更容易理解,我们通过一个代码例子来演示. 例子: 我们现在要访问http://localhost:8080/main.html页面,这个页面需要登录之后才能够浏览,没登录不能浏览. 那么现在问题来 ...
- SpringBoot 2.x 自定义拦截器并解决静态资源访问被拦截问题
自定义拦截器 /** * UserSecurityInterceptor * Created with IntelliJ IDEA. * Author: yangyongkang * Date: ...
随机推荐
- WCF引用方式之IIS方式寄宿服务
通过IIS方式寄宿服务 之前的例子是将控制台作为WCF的寄宿方式或者是直接添加契约项目的引用,然后通过配置或者是ChannelFactory的形式进行创建服务对象,其实在大多的开发中以IIS的形式创建 ...
- 轻量级封装DbUtils&Mybatis之一概要
Why 一时兴起,自以为是的对Jdbc访问框架做了一个简单的摸底,近期主要采用Mybatis,之前也有不少采用Dbutils,因此希望能让这两个框架折腾的更好用. DbUtils:非常简单的Jdbc访 ...
- Memory stream is not expandable
发现项目有一个地方在做图片缩放剪切的一个操作中.碰到有一些特殊的图片会报 Memory stream is not expandable 的错误 跟踪的时候发现是 由方法 originalStream ...
- Zookeeper--Watcher 和 ACL
Zookeeper--Watcher 和 ACL Watcher (观察) Zookeeper中的znode可以被监控,这是zk的核心特性. 通过exists,getChildren和getData这 ...
- python查找字符串 函数find() 用法
sStr1 = 'abcdefg' sStr2 = 'cde' print sStr1.find(sStr2) 输出 2意思是在sStr1字符里的第2位置找到了包含cde字符的字段
- 阻塞队列之五:LinkedBlockingQueue
一.LinkedBlockingQueue简介 LinkedBlockingQueue是一个使用链表完成队列操作的阻塞队列.链表是单向链表,而不是双向链表.采用对于的next构成链表的方式来存储对象. ...
- Visual Studio Online 创建项目
VSO是微软为软件开发人员提供的一款基于云计算的开发平台.Team Foundation Server已经可以基于云端使用,无需再为配置和部署耗费多余的时间(PS:当初为了在服务器上部署这个鼓捣了4个 ...
- 关于alter database open resetlogs及incarnation的一点理解
关于alter database open resetlogs及incarnation的一点理解 不完全恢复只能做一次吗? 采用rman的默认设置,对数据库进行了backup database备份,进 ...
- POJ-3273 Monthly Expense (最大值最小化问题)
/* Monthly Expense Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 10757 Accepted: 4390 D ...
- Linux无法登录,显示module is unknown,一闪而过
1.使用单用户模式登录系统(不作介绍) 2.查看日志:vim /var/log/secure 3.记忆起曾经配置oracle添加过该参数 vim/etc/pam.d/login中加入了: sessio ...