[转] https://www.jianshu.com/p/7edab536e4b9
前言
这2天开始写web接口,由于项目后端就我一个人,写起来比较慢。,遇到好多奇怪的问题,也基本只能一个人去解决。今天下午给这个问题坑了半天。现在脑壳子还疼。
问题
业务上需要实现一个功能,拦截请求的参数。检查是否包含token。项目是基于springmvc来实现的,这里很自然使用 spring 切面技术。拦截所有controller的请求,然后检查是否携带了token参数。如果没携带,则抛一个自定义异常。再调用 统一异常处理类来处理。
涉及的类如下:
package com.insigmaunited.lightai.base;
import com.insigmaunited.lightai.exception.TokenEmptyException;
import com.insigmaunited.lightai.result.Response;
import com.insigmaunited.lightai.util.StringUtil;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 权限拦截AOP
* @author Administrator
*
*/
@Component
@Aspect
public class PermissionAop {
private final Logger logger = LoggerFactory.getLogger(PermissionAop.class);
// 定义切点Pointcut
@Pointcut("execution(* com.insigmaunited.lightai.controller.*Controller.*(..))")
public void pointCut(){}
@Before("pointCut()")
public void before() throws Throwable {
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
HttpServletRequest request = sra.getRequest();
String url = request.getRequestURL().toString();
String method = request.getMethod();
String uri = request.getRequestURI();
String queryString = request.getQueryString();
System.out.println(url);
System.out.println(method);
System.out.println(uri);
System.out.println(queryString);
if (StringUtil.isNotEmpty(queryString) && queryString.indexOf("token") != -