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: ...
随机推荐
- node编译安装
node应用编译安装 安装node编译环境 # apt-get install gcc make build-essential openssl g++ zlib1g-dev libssl-doc a ...
- WebApi全局异常处理方式
自定义错误消息 public class ErrorMessage:DelegatingHandler { protected override Task<HttpResponseMessage ...
- wdlinux重新编译nginx
背景: 由于web站点需要换主机,并且切换环境. 站点需要做反相代理(nginx),主机从美国迁移到香港[考虑到速度问题,为什么不用大陆阿里云ECS服务器?几十个域名备案麻烦,还有阿里云内地没有多ip ...
- 老齐python-基础2(字符串)
1.字符串 1.1索引和切片 索引: >>> lang = "study python" >>> lang[0] 's' >>> ...
- 初识C++模板元编程(Template Mega Programming)
前言:毕设时在开源库上做的程序,但是源码看得很晕(当时导师告诉我这是模板元编程,可以不用太在乎),最近自己造轮子时想学习STL的源码,但也是一样的感觉,大致了解他这么做要干什么,但是不知道里面的机制. ...
- 黄聪:免费C#反编译软件工具。Reflector已经out了,试试ILSpy吧
转载自:http://www.cnblogs.com/JamesLi2015/archive/2011/09/08/2170519.html Reflector是.NET开发中必备的反编译工具.即使没 ...
- IT运维的定义
IT运维是IT管理的核心和重点部分,也是内容最多.最繁杂的部分,该阶段主要用于IT部门内部日常运营管理,涉及的对象分成两大部分,即IT业务系统和运维人员,该阶段的管理内容又可细分为七个子系统: ...
- linux环境下搭建MySQL
linux下搭建mysql的方式很多,网上也详解了很多种搭建方式,有直接yum的.有rpm的..总之,“坑”是层出不穷,有相关文件依赖性.权限.GPG keys等等. 本人也在今天搭建了一下.是出“坑 ...
- Linux中常用的查找文件的命令
我们经常在linux要查找某个文件,但不知道放在哪里了,可以使用下面的一些命令来搜索.这些是从网上找到的资料(参考资料1),因为有时很长时间不会用到,当要用的时候经常弄混了,所以放到这里方便使用. w ...
- Pymol
如何用Pymol做出那些美呆的结构图(基础篇) 2016-10-31 翾园 摘自 BioEngX生化... 阅 1079 转 6 转藏到我的图书馆 微信分享: 摘自微信公众号:BioE ...