Spring boot中使用简单拦截器

在实际开发过程中,我们的项目要给某些特定的用户来使用或者调用。在调用过程中,会让其传递某些标识,验证通过之后,才让其调用接口或者访问系统。常用的方法是在项目中加入一个拦截器,在用户调用接口之前,就验证其是否合法,做法是在header中传递一下标识,让拦截器进行处理。

简要的拦截器实现如下:

1、新建一个拦截器,让其集成HandlerInterceptorAdapter()这个类,让后实现里面的preHandle方法,也就是在请求之前拦截。

import com.fasterxml.jackson.databind.ObjectMapper
import net.tiangu.aio.commons.exception.ApiException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.http.MediaType
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class ApiInterceptor : HandlerInterceptorAdapter() {

    @Autowired
    lateinit private var mongoTemplate: MongoTemplate

    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        try {
            val appId = if (request.getHeader("RAINBOW-DEBUG") != "true") {
                request.getHeader("RAINBOW-APP-ID") ?: throw ApiException("0001", "参数 appId 不能为空")
            } else {
                "123456"
            }
            request.setAttribute("appId ", appId )
            return true
        } catch (ex: ApiException) {
            response.status = 400
            response.contentType = MediaType.APPLICATION_JSON_UTF8_VALUE
            val stream = response.outputStream
            stream.write(ObjectMapper().writeValueAsBytes(mapOf("code" to ex.code, "message" to (ex.message ?: "未知错误"))))
            stream.flush()
            stream.close()
            return false
        }
    }
}

2、注册拦截器。为了能够让该拦截器生效,需要注册拦截器。
新建一个ApilicationConfig,并让该类继承WebMvcConfigurerAdapter()类,并在里面实现addInterceptors方法。

import net.tiangu.aio.interceptor.ApiInterceptor
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter

/**
 * Created by rainbow on 2017/4/28.
 *一事专注,便是动人;一生坚守,便是深邃!
 */
@Configuration
open class ApplicationConfig : WebMvcConfigurerAdapter() {

    @Bean
    open fun apiInterceptor() = ApiInterceptor()

     //可注册多个拦截器
    override fun addInterceptors(registry: InterceptorRegistry) {
     //拦截/api/v1/下的所有方法
        registry.addInterceptor(apiInterceptor()).addPathPatterns("/api/v1/**")
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 姓名: 李小娜 [嵌牛导读]: SpringMVC 中的Interceptor 拦截器也是相当重要和相当有用的,...
    n184阅读 3,211评论 0 4
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,378评论 11 349
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • 致良知是一种伟大的力量! 时间:2017年8月8日 文章:《教条示龙场诸生》 姓名:王海雨/立志班1组 【1】听分...
    胡芳叶梦之蓝阅读 659评论 0 0