访问Controller方法前拦截添加业务处理逻辑及Spring拦截器的使用于配置_controller调用方法前-程序员宅基地

技术标签: SpringBoot  Spring  

要借助Spring实现拦截器功能,可以实现HandlerInterceptor接口或者实现WebRequestInterceptor接口或者继承HandlerInterceptorAdapter适配器【建议使用】

如果实现HandlerInterceptor或者WebRequestInterceptor接口的话,三个方法必须实现,就算是空实现,也必须要放着
 不管你需不需要,所以继承HandlerInterceptorAdapter适配器是更好的选择,可以只实现需要的方法,拦截器可以基于自定义注解来拦截,也可以通过请求的url来拦截,等等

下面是一个外围系统调用Controller前,判断用户是否登录的一个逻辑

需要拦截的注解标识,在Controller上使用,可以看到Target可以是类和方法

package cn.cuit.hardlogin;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface RequireHardLogin {
}

拦截器逻辑:

package cn.cuit.hardlogin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 有时候我们可能只需要实现三个回调方法中的某一个,如果实现HandlerInterceptor接口的话,三个方法必须实现,
 * 不管你需不需要,此时spring提供了一个HandlerInterceptorAdapter适配器
 * (种适配器设计模式的实现),允许我们只实现需要的回调方法。
 *
 * https://www.jianshu.com/p/1e8d088c2be9
 */
public class BeforeControllerHandlerInterceptor extends HandlerInterceptorAdapter {

	private static final String INTERCEPTOR_ONCE_KEY = BeforeControllerHandlerInterceptor.class.getName();

	// 拦截后要执行的处理[被封装成单独的各个处理类然后注入]
	private List<BeforeControllerHandler> beforeControllerHandlers;

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
			throws Exception {
		if (request.getAttribute(INTERCEPTOR_ONCE_KEY) == null) {
			// [设置标记,防止重复访问]
			request.setAttribute(INTERCEPTOR_ONCE_KEY, Boolean.TRUE);

			if (handler instanceof HandlerMethod) {
				final HandlerMethod handlerMethod = (HandlerMethod) handler;

				// 【调用一系列的Controller方法请求前要完成的操作】
				for (final BeforeControllerHandler beforeControllerHandler : getBeforeControllerHandlers()) {
					if (!beforeControllerHandler.beforeController(request, response, handlerMethod)) {
						// 如果处理程序返回false,则立即返回
						System.out.println(">>>>>>>>>>>>>>>没有访问权限");
						return false;
					}
				}
			}
		}
		return true;
	}

	public void setBeforeControllerHandlers(final List<BeforeControllerHandler> beforeControllerHandlers) {
		this.beforeControllerHandlers = beforeControllerHandlers;
	}

	public List<BeforeControllerHandler> getBeforeControllerHandlers() {
		return beforeControllerHandlers;
	}
}

拦截中处理具体逻辑的接口:

package cn.cuit.hardlogin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;

public interface BeforeControllerHandler {

	/**
	 * 在DispatcherServlet调用控制器之前调用。
	 */
	boolean beforeController(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler)
			throws Exception;
}

拦截中处理具体逻辑的接口实现,被注入拦截器中使用:

package cn.cuit.hardlogin;

import java.io.OutputStream;
import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class UserAuthenticationHandler implements BeforeControllerHandler {

	private static final Logger LOG = Logger.getLogger(UserAuthenticationHandler.class);

	// @Autowired
	// private Jedis jedis;

	@Override
	public boolean beforeController(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler)
			throws Exception {
		// 返回一个布尔值,指示此请求是否是使用安全通道(例如HTTPS)进行的。
		if (request.isSecure()) {
			String token = request.getHeader("TOKEN");
			LOG.info("Token is: " + token);
			if (StringUtils.isNotBlank(token)) {
				// eg: get user detail from redis server
			} else {
				// do Other sth
			}
			// 检查处理程序Handler是否包含我们的RequireHardLogin注解
			final RequireHardLogin annotation = findAnnotation(handler, RequireHardLogin.class);
			if (annotation != null) {
				if (StringUtils.isBlank(token)) {
					response.setContentType("application/json; charset=utf-8");
					response.setCharacterEncoding("UTF-8");

					OutputStream out = response.getOutputStream();
					out.write(convertObjectToJson(ResultData.failureResult("Invalid Token")).getBytes("UTF-8"));
					out.flush();
					return false;
				}
			}
		}
		return true;
	}

	protected <T extends Annotation> T findAnnotation(final HandlerMethod handlerMethod,
			final Class<T> annotationType) {
		// 搜索方法级别注解
		final T annotation = handlerMethod.getMethodAnnotation(annotationType);
		if (annotation != null) {
			return annotation;
		}

		// 搜索类级别注解
		return AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), annotationType);
	}

	public String convertObjectToJson(Object object) throws JsonProcessingException {
		if (object == null) {
			return null;
		}
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(object);
	}
}

xml中配置拦截器和拦截器中具体逻辑的各个处理类

    <mvc:interceptors>
        <ref bean="beforeControllerHandlerInterceptor"/>
    </mvc:interceptors>
    <util:list id="beforeControllerHandlers">
        <bean class="cn.cuit.hardlogin.UserAuthenticationHandler">
            <!-- <property name="jedis" ref="jedis"/> -->
        </bean>
    </util:list>

如果使用SpringBoot,可以实现WebMvcConfigurerAdapter【过时】,WebMvcConfigurer,或者继承WebMvcConfigurationSupport 【推荐使用】

随便使用一个则如下配置:

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

	@Bean
	BeforeControllerHandler userAuthenticationHandler() {
		return new UserAuthenticationHandler();
	}

	@Bean
	List<BeforeControllerHandler> beforeControllerHandlers() {
		List<BeforeControllerHandler> list = new ArrayList<>();
		list.add(userAuthenticationHandler());
		return list;
	}

	@Autowired
	List<BeforeControllerHandler> beforeControllerHandlers;

	/**
	 * 拦截器配置
	 * 
	 * @param registry
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		super.addInterceptors(registry);
		BeforeControllerHandlerInterceptor beforeControllerHandlerInterceptor = new BeforeControllerHandlerInterceptor();
		beforeControllerHandlerInterceptor.setBeforeControllerHandlers(beforeControllerHandlers);
		registry.addInterceptor(beforeControllerHandlerInterceptor);
	}
}

有没有觉得@Bean这种配置比XML难写,而且不好理解,所以个人还是喜欢xml配置,看项目吧,追求新就可以玩注解,不过一般是追求稳,大多数人都会的,习惯的,不要盲目跟风,合适的才是最好的

********************************* 不积跬步无以至千里,不积小流无以成江海 *********************************

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42465125/article/details/88525661

智能推荐

如何配置filezilla服务端和客户端_filezilla server for windows (32bit x86)-程序员宅基地

文章浏览阅读7.8k次,点赞3次,收藏9次。如何配置filezilla服务端和客户端百度‘filezilla server’下载最新版。注意点:下载的版本如果是32位的适用xp和win2003,百度首页的是适用于win7或更高的win系统。32和64内容无异。安装过程也是一样的。一、这里的filezilla包括服务端和客户端。我们先来用filezilla server 架设ftp服务端。看步骤。1选择标准版的就可以了。 _filezilla server for windows (32bit x86)

深度学习图像处理01:图像的本质-程序员宅基地

文章浏览阅读724次,点赞18次,收藏8次。深度学习作为一种强大的机器学习技术,已经成为图像处理领域的核心技术之一。通过模拟人脑处理信息的方式,深度学习能够从图像数据中学习到复杂的模式和特征,从而实现从简单的图像分类到复杂的场景理解等多种功能。要充分发挥深度学习在图像处理中的潜力,我们首先需要理解图像的本质。本文旨在深入探讨深度学习图像处理的基础概念,为初学者铺平通往高级理解的道路。我们将从最基础的问题开始:图像是什么?我们如何通过计算机来理解和处理图像?

数据探索阶段——对样本数据集的结构和规律进行分析_数据分析 规律集-程序员宅基地

文章浏览阅读62次。在收集到初步的样本数据之后,接下来该考虑的问题有:(1)样本数据集的数量和质量是否满足模型构建的要求。(2)是否出现从未设想过的数据状态。(3)是否有明显的规律和趋势。(4)各因素之间有什么样的关联性。解决方案:检验数据集的数据质量、绘制图表、计算某些特征量等,对样本数据集的结构和规律进行分析。从数据质量分析和数据特征分析两个角度出发。_数据分析 规律集

上传计算机桌面文件图标不见,关于桌面上图标都不见了这类问题的解决方法-程序员宅基地

文章浏览阅读8.9k次。关于桌面上图标都不见了这类问题的解决方法1、在桌面空白处右击鼠标-->排列图标-->勾选显示桌面图标。2、如果问题还没解决,那么打开任务管理器(同时按“Ctrl+Alt+Del”即可打开),点击“文件”→“新建任务”,在打开的“创建新任务”对话框中输入“explorer”,单击“确定”按钮后,稍等一下就可以见到桌面图标了。3、问题还没解决,按Windows键+R(或者点开始-->..._上传文件时候怎么找不到桌面图标

LINUX 虚拟网卡tun例子——修改_怎么设置tun的接收缓冲-程序员宅基地

文章浏览阅读1.5k次。参考:http://blog.csdn.net/zahuopuboss/article/details/9259283 #include #include #include #include #include #include #include #include #include #include #include #include _怎么设置tun的接收缓冲

UITextView 评论输入框 高度自适应-程序员宅基地

文章浏览阅读741次。创建一个inputView继承于UIView- (instancetype)initWithFrame:(CGRect)frame{ self = [superinitWithFrame:frame]; if (self) { self.backgroundColor = [UIColorcolorWithRed:0.13gre

随便推点

字符串基础面试题_java字符串相关面试题-程序员宅基地

文章浏览阅读594次。字符串面试题(2022)_java字符串相关面试题

VSCODE 实现远程GUI,显示plt.plot, 设置x11端口转发_vscode远程ssh连接服务器 python 显示plt-程序员宅基地

文章浏览阅读1.4w次,点赞12次,收藏21次。VSCODE 实现远程GUI,显示plt.plot, 设置x11端口转发问题服务器 linux ubuntu16.04本地 windows 10很多小伙伴发现VSCode不能显示figure,只有用自带的jupyter才能勉强个截图、或者转战远程桌面,这对数据分析极为不方便。在命令行键入xeyes(一个显示图像的命令)会failed,而桌面下会出现:但是Xshell能实现X11转发图像,有交互功能,但只能用Xshell输入命令plot,实在不方便。其实VScode有X11转发插件!!方法_vscode远程ssh连接服务器 python 显示plt

element-ui switch开关打开和关闭时的文字设置样式-程序员宅基地

文章浏览阅读3.3k次,点赞2次,收藏2次。element switch开关文字显示element中switch开关把on-text 和 off-text 属性改为 active-text 和 inactive-text 属性.怎么把文字描述显示在开关上?下面就是实现方法: 1 <el-table-column label="状态"> 2 <template slot-scope="scope">..._el-switch 不同状态显示不同字

HttpRequestUtil方法get、post、JsonToPost_httprequestutil.httpget-程序员宅基地

文章浏览阅读785次。java后台发起请求使用的工具类package com.cennavi.utils;import org.apache.http.Header;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apach_httprequestutil.httpget

App-V轻量级应用程序虚拟化之三客户端测试-程序员宅基地

文章浏览阅读137次。在前两节我们部署了App-V Server并且序列化了相应的软件,现在可谓是万事俱备,只欠东风。在这篇博客里面主要介绍一下如何部署客户端并实现应用程序的虚拟化。在这里先简要的说一下应用虚拟化的工作原理吧!App-V Streaming 就是利用templateServer序列化出一个软件运行的虚拟环境,然后上传到app-v Server上,最后客户..._app-v 客户端