springboot拦截器过滤token,并返回结果及异常处理
package com.xxxx.interceptor; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;
import org.springframework.web.servlet.mvc.method.annotation.ViewNameMethodReturnValueHandler; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects; /**
* 基础拦截器,通过@Configuration自行配置为Bean,可以配置成多个拦截器。
*
* @author obiteaaron
* @since 2019/12/26
*/
public class BaseInterceptor implements AsyncHandlerInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(BaseInterceptor.class); private ApplicationContext applicationContext; protected InterceptorPreHandler interceptorPreHandler; @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean checkResult = interceptorPreHandler.check(request, response, handler);
if (!checkResult) {
postInterceptor(request, response, handler);
return false;
} else {
return true;
}
} /**
* 拦截后处理
*/
protected void postInterceptor(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 如果被拦截,返回信息
if (((HandlerMethod) handler).getMethodAnnotation(ResponseBody.class) != null) {
// 返回json
HandlerMethod handlerMethod = new HandlerMethod(((HandlerMethod) handler).getBean(), ((HandlerMethod) handler).getMethod());
Object returnValue = interceptorPreHandler.getResponseBody();
MethodParameter returnValueType = handlerMethod.getReturnValueType(returnValue);
applicationContext.getBean(RequestMappingHandlerAdapter.class).getReturnValueHandlers();
RequestResponseBodyMethodProcessor requestResponseBodyMethodProcessor = findRequestResponseBodyMethodProcessor();
requestResponseBodyMethodProcessor.handleReturnValue(returnValue, returnValueType, new ModelAndViewContainer(), new ServletWebRequest(request, response));
// end
} else {
// 返回页面
HandlerMethod handlerMethod = new HandlerMethod(((HandlerMethod) handler).getBean(), ((HandlerMethod) handler).getMethod());
String viewName = interceptorPreHandler.getViewName();
MethodParameter returnValueType = handlerMethod.getReturnValueType(viewName);
ViewNameMethodReturnValueHandler viewNameMethodReturnValueHandler = findViewNameMethodReturnValueHandler();
ModelAndViewContainer modelAndViewContainer = new ModelAndViewContainer();
// viewNameMethodReturnValueHandler 内的实现非常简单,其实可以不用这个的,直接new ModelAndViewContainer()就好了。
viewNameMethodReturnValueHandler.handleReturnValue(viewName, returnValueType, modelAndViewContainer, new ServletWebRequest(request, response)); // 抛出异常由Spring处理
ModelMap model = modelAndViewContainer.getModel();
ModelAndView modelAndView = new ModelAndView(modelAndViewContainer.getViewName(), model, modelAndViewContainer.getStatus());
throw new ModelAndViewDefiningException(modelAndView);
// end
}
} private RequestResponseBodyMethodProcessor findRequestResponseBodyMethodProcessor() {
RequestMappingHandlerAdapter requestMappingHandlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);
for (HandlerMethodReturnValueHandler value : Objects.requireNonNull(requestMappingHandlerAdapter.getReturnValueHandlers())) {
if (value instanceof RequestResponseBodyMethodProcessor) {
return (RequestResponseBodyMethodProcessor) value;
}
}
// SpringMVC的环境下一定不会走到这里
throw new UnsupportedOperationException("cannot find RequestResponseBodyMethodProcessor from RequestMappingHandlerAdapter by Spring Context.");
} private ViewNameMethodReturnValueHandler findViewNameMethodReturnValueHandler() {
RequestMappingHandlerAdapter requestMappingHandlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);
for (HandlerMethodReturnValueHandler value : Objects.requireNonNull(requestMappingHandlerAdapter.getReturnValueHandlers())) {
if (value instanceof ViewNameMethodReturnValueHandler) {
return (ViewNameMethodReturnValueHandler) value;
}
}
// SpringMVC的环境下一定不会走到这里
throw new UnsupportedOperationException("cannot find ViewNameMethodReturnValueHandler from RequestMappingHandlerAdapter by Spring Context.");
} public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
} public void setInterceptorPreHandler(InterceptorPreHandler interceptorPreHandler) {
this.interceptorPreHandler = interceptorPreHandler;
} public interface InterceptorPreHandler {
/**
* @see HandlerInterceptor#preHandle(HttpServletRequest, HttpServletResponse, Object)
*/
boolean check(HttpServletRequest request, HttpServletResponse response, Object handler); /**
* 拦截后返回的视图名称
*
* @see ModelAndView
* @see ViewNameMethodReturnValueHandler
*/
String getViewName(); /**
* 拦截后返回的对象
*
* @see ResponseBody
* @see RequestResponseBodyMethodProcessor
*/
Object getResponseBody();
}
}
SpringBoot版本:2.1.6.RELEASE
SpringMVC版本:5.1.8.RELEASE
SpringMVC拦截器
比如说在SpringMVC Web环境下,需要实现一个权限拦截的功能,一般情况下,大家都是实现了org.springframework.web.servlet.AsyncHandlerInterceptor或者org.springframework.web.servlet.HandlerInterceptor接口,从而实现的SpringMVC拦截。而要实现拦截功能,通常都是通过preHandle方法返回false拦截。
拦截器的preHandle
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
那么拦截后,如果你什么都不做,会直接返回空页面,页面上什么也没有。如果要返回结果,需要自己给response写数据。简单的写法网上很多,这里不赘述,这里将会讲解如何通过SpringMVC本身的处理机制在拦截后返回结果。
拦截后返回结果
拦截后返回数据通常是两种,第一种如果是返回的Restful接口,那么返回一个json数据即可,第二种如果返回的是一个页面,那么需要返回错误页面(比如无权限页面)。
SpringMVC的所有结果都是通过HandlerMethodReturnValueHandler接口的实现类返回的,无论是Json,还是View。因此可以通过具体的实现类返回我们想要的数据。与之对应的还有``,这些所有的参数和返回结果的处理器,都定义在RequestMappingHandlerAdapter中,这个Adapter可以从容器中获取到。这里我们主要用到的只有两个RequestResponseBodyMethodProcessor和ViewNameMethodReturnValueHandler。
返回纯数据
返回纯数据,适用于返回Controller的方法通过@ResponseBody标注了。因此需要用到RequestResponseBodyMethodProcessor。
RequestResponseBodyMethodProcessor里面对不同的数据会有不同的处理方式,一般都是处理为json,具体实现可以看HttpMessageConverter的实现类。这里是直接将结果写到了response中。实现代码在文末。
返回视图
返回视图,适用于返回Controller的方法通过是个String,其实是ViewName。因此需要用到ViewNameMethodReturnValueHandler。
通过查看DispatcherServlet代码会发现,其实preHandle方法执行在RequestMappingHandlerAdapter执行前,所以没有ModelAndView生成,因此需要自己向Response里面写数据。这里只是借助了RequestMappingHandlerAdapter生产需要写入的数据。然后通过抛出异常ModelAndViewDefiningException,从而将我们的生产的ModeAndView透出给Spring进行渲染DispatcherServlet#processDispatchResult。
实现代码在文末。
直接使用视图解析器方法
如果你知道自己的视图解析器是谁,那么还有一个方法,比如,我用的是Velocity的视图解析器,Velocity的视图解析器配置的beanName是velocityViewResolver,因此可以用下面的方法实现。
SpringBoot下注册拦截器:org.springframework.web.servlet.config.annotation.WebMvcConfigurer#addInterceptors
结尾
其他类型的实现,可以自行实现。
springboot拦截器过滤token,并返回结果及异常处理的更多相关文章
- SpringBoot拦截器中Bean无法注入(转)
问题 这两天遇到SpringBoot拦截器中Bean无法注入问题.下面介绍我的思考过程和解决过程: 1.由于其他bean在service,controller层注入一点问题也没有,开始根本没意识到Be ...
- 【SpringBoot】SpringBoot拦截器实战和 Servlet3.0自定义Filter、Listener
=================6.SpringBoot拦截器实战和 Servlet3.0自定义Filter.Listener ============ 1.深入SpringBoot2.x过滤器Fi ...
- springboot拦截器总结
Springboot 拦截器总结 拦截器大体分为两类 : handlerInterceptor 和 methodInterceptor 而methodInterceptor 又有XML 配置方法 和A ...
- Java结合SpringBoot拦截器实现简单的登录认证模块
Java结合SpringBoot拦截器实现简单的登录认证模块 之前在做项目时需要实现一个简单的登录认证的功能,就寻思着使用Spring Boot的拦截器来实现,在此记录一下我的整个实现过程,源码见文章 ...
- Springboot拦截器实现IP黑名单
Springboot拦截器实现IP黑名单 一·业务场景和需要实现的功能 以redis作为IP存储地址实现. 业务场景:针对秒杀活动或者常规电商业务场景等,防止恶意脚本不停的刷接口. 实现功能:写一个拦 ...
- SpringBoot拦截器及源码分析
1.拦截器是什么 java里的拦截器(Interceptor)是动态拦截Action调用的对象,它提供了一种机制可以使开发者在一个Action执行的前后执行一段代码,也可以在一个Action执行前阻止 ...
- SpringBoot拦截器中无法注入bean的解决方法
SpringBoot拦截器中无法注入bean的解决方法 在使用springboot的拦截器时,有时候希望在拦截器中注入bean方便使用 但是如果直接注入会发现无法注入而报空指针异常 解决方法: 在注册 ...
- Springboot拦截器未起作用
之前遇到要使用springboot拦截器却始终未生效的状况,查了网上的博客,大抵都是@Component,@Configuration注解未加,或是使用@ComponentScan增加包扫描,但是尝试 ...
- SpringMvc Controller请求链接忽略大小写(包含拦截器)及@ResponseBody返回String中文乱码处理
SpringMvc Controller请求链接忽略大小写(包含拦截器)及@ResponseBody返回String中文乱码处理... @RequestMapping(value = "/t ...
- SpringBoot拦截器中service或者redis注入为空的问题
原文:https://my.oschina.net/u/1790105/blog/1490098 这两天遇到SpringBoot拦截器中Bean无法注入问题.下面介绍我的思考过程和解决过程: 1.由于 ...
随机推荐
- electron 菜单选项 - 隐藏,设置菜单
隐藏菜单 const { app, Menu, session } = require('electron'); /*隐藏electron的菜单栏*/ Menu.setApplicationMenu( ...
- 从url地址获取主机名
function getHost(url) { var host = "null"; if(typeof url == "undefined"|| null = ...
- 理解 keep-alive
keep-alive 是 Vue 内置的一个组件,可以使被包含的组件保留状态,避免重新渲染 : 对应两个钩子函数 activated 和 deactivated ,当组件被激活时,触发钩子函数 act ...
- Tarjan缩点题单 刷题题解
Tarjan缩点可以将一个图的每个强连通分量缩成一个点,然后构建新图,该图就会变成一个有向无环图.变成有向无环图之后就能结合最短路,拓扑......解决相应题目 洛谷题单分享: https://www ...
- 云原生周刊:一条 Kubernetes 命令引发的悲剧
开源项目 KSail 用于在 Docker 中配置支持 GitOps 的 K8s 集群的 CLI 工具. nginx-gateway-fabric NGINX Gateway Fabric 是一个开源 ...
- python 爬虫如何爬取动态生成的网页内容
--- 好的方法很多,我们先掌握一种 --- [背景] 对于网页信息的采集,静态页面我们通常都可以通过python的request.get()库就能获取到整个页面的信息. 但是对于动态生成的网页信 ...
- Java面试题及答案整理汇总(2024最新版)
前言 辞退了老板,准备找下家,又要开始面试了,不得不准备准备八股文,还是很有必要针对性的刷一些题,很多朋友的实战能力很强,但是理论比较薄弱,要多准备准备理论知识,攻克面试官.这是我在全网寻找稍微比较完 ...
- 2024/9/16 CSP-S模拟赛试题
A 这题是很有意思的一个题,思路就是你考虑kt的位置只可能在四个角,因为这种情况下,他的距离才会最远对吧,所以你就暴力找另一个人fengwu的点的位置,然后计算他们之间的距离然后你求一个\(\max\ ...
- 遗传算法+强化学习—TPG—Emergent Tangled Graph Representations for Atari Game Playing Agents
最近在看进化算法在强化学习(RL)领域的一些应用,有些论文中将使用进化算法解决强化学习问题的算法归为非强化学习算法,然而又有些论文把使用进化算法解决强化学习问题的算法归为强化学习算法,不过更多的论文是 ...
- games101_Homework3
在Raster部分实现数值插值,然后实现四种不同的像素着色器 作业描述: 作业1:修改函数 rasterize_triangle(const Triangle& t) in rasterize ...