springboot实现拦截器之验证登录示例
程序员文章站
2024-03-06 19:59:14
整理文档,搜刮出一个springboot实现拦截器之验证登录示例,稍微整理精简一下做下分享。
添加jar包,这个jar包不是必须的,只是在拦截器里用到了,如果不用的话...
整理文档,搜刮出一个springboot实现拦截器之验证登录示例,稍微整理精简一下做下分享。
添加jar包,这个jar包不是必须的,只是在拦截器里用到了,如果不用的话,完全可以不引入
<dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-lang3</artifactid> <version>3.5</version> </dependency>
springboot默认为tomcat,如果用jetty,还需要引入
<dependency> <groupid>javax.servlet</groupid> <artifactid>javax.servlet-api</artifactid> <version>3.1.0</version> </dependency>
1、以登录验证为例,首先创建个@auth注解
package com.demo.interceptor; import java.lang.annotation.*; /** * created by huguoju on 2016/12/30. * 在类或方法上添加@auth就验证登录 */ @target({elementtype.type, elementtype.method}) @retention(retentionpolicy.runtime) @documented public @interface auth { }
2、创建一个constants,在拦截器里用
package com.demo.util; /** * created by huguoju on 2016/12/30. */ public interface constants { int max_file_upload_size = 5242880; string mobile_number_session_key = "sessionmobilenumber"; string user_code_session_key = "usercode"; string session_key = "sessionid"; }
3、创建一个sessiondata,用于保存在session中的字段
package com.demo.model; import lombok.data; /** * created by huguoju on 2016/12/30. */ @data public class sessiondata { private integer usercode; private string mobilenumber; }
4、实现登录拦截实现
package com.demo.interceptor; import com.demo.model.sessiondata; import com.demo.util.redisutil; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.component; import org.springframework.web.method.handlermethod; import org.springframework.web.servlet.handler.handlerinterceptoradapter; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.lang.reflect.method; import static com.demo.util.constants.mobile_number_session_key; import static com.demo.util.constants.session_key; import static com.demo.util.constants.user_code_session_key; /** * created by huguoju on 2016/12/30. */ @component public class logininterceptor extends handlerinterceptoradapter { @autowired private redisutil redisutils; private final static string session_key_prefix = "session:"; public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception { if (!handler.getclass().isassignablefrom(handlermethod.class)) { return true; } handlersession(request); final handlermethod handlermethod = (handlermethod) handler; final method method = handlermethod.getmethod(); final class<?> clazz = method.getdeclaringclass(); if (clazz.isannotationpresent(auth.class) || method.isannotationpresent(auth.class)) { if(request.getattribute(user_code_session_key) == null){ throw new exception(); }else{ return true; } } return true; } public void handlersession(httpservletrequest request) { string sessionid = request.getheader(session_key); if(org.apache.commons.lang3.stringutils.isblank(sessionid)){ sessionid=(string) request.getsession().getattribute(session_key); } if (org.apache.commons.lang3.stringutils.isnotblank(sessionid)) { sessiondata model = (sessiondata) redisutils.get(session_key_prefix+sessionid); if (model == null) { return ; } request.setattribute(session_key,sessionid); integer usercode = model.getusercode(); if (usercode != null) { request.setattribute(user_code_session_key, long.valueof(usercode)); } string mobile = model.getmobilenumber(); if (mobile != null) { request.setattribute(mobile_number_session_key, mobile); } } return ; } }
5、配置拦截器
package com.demo.interceptor; import org.hibernate.validator.hibernatevalidator; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.autowired; import org.springframework.context.messagesource; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.componentscan; import org.springframework.context.annotation.configuration; import org.springframework.context.annotation.propertysource; import org.springframework.context.support.propertysourcesplaceholderconfigurer; import org.springframework.context.support.reloadableresourcebundlemessagesource; import org.springframework.validation.validator; import org.springframework.validation.beanvalidation.localvalidatorfactorybean; import org.springframework.validation.beanvalidation.methodvalidationpostprocessor; import org.springframework.web.servlet.viewresolver; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.requestmappinghandlermapping; import org.springframework.web.servlet.view.internalresourceviewresolver; /** * created by huguoju on 2016/12/30. */ @configuration @enablewebmvc @componentscan(basepackages = "com.demo.controller") @propertysource(value = "classpath:application.properties", ignoreresourcenotfound = true,encoding = "utf-8") public class mvcconfig extends webmvcconfigureradapter { private static final logger logger = loggerfactory.getlogger(mvcconfig.class); @autowired logininterceptor logininterceptor; /** * <p> * 视图处理器 * </p> * * @return */ @bean public viewresolver viewresolver() { logger.info("viewresolver"); internalresourceviewresolver viewresolver = new internalresourceviewresolver(); viewresolver.setprefix("/web-inf/jsp/"); viewresolver.setsuffix(".jsp"); return viewresolver; } /** * 拦截器配置 * @param registry */ @override public void addinterceptors(interceptorregistry registry) { // 注册监控拦截器 registry.addinterceptor(logininterceptor) .addpathpatterns("/**") .excludepathpatterns("/configuration/ui"); } @override public void addcorsmappings(corsregistry registry) { registry.addmapping("/**") .allowedorigins("*") .allowedheaders("*/*") .allowedmethods("*") .maxage(120); } /** * 资源处理器 * @param registry */ @override public void addresourcehandlers(resourcehandlerregistry registry) { logger.info("addresourcehandlers"); registry.addresourcehandler("/swagger-ui.html") .addresourcelocations("classpath:/meta-inf/resources/"); registry.addresourcehandler("/webjars/**") .addresourcelocations("classpath:/meta-inf/resources/webjars/"); } }
以上就完成了,测试时可以在logininterceptor里打断点,然后在controller上或者方法上添加@auth注解,
controller上添加以后这个controller里所有请求都验证登录,在方法里添加只有请求这个方法时验证
@auth @restcontroller public class testcontroller { }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。