- 通过spring的aop特性,可以很方便的拦截用户的请求,将未登陆的用户的请求拦截。
- 在spring配置文件里面加入注解,让spring去自动创建基于类的代理
<aop:aspectj-autoproxy proxy-target-class="true"/>
- 编写切面逻辑处理类,拦截controllers包中除开LoginController中的接口外的其他所有接口的请求,通过获取session中是否含有用户基本信息,不包含的用户信息则认为用户未登陆或者登陆已经超时
package com.bim.controllers
import com.bi.controllers.util.ResultUtil
import com.bi.module.User
import com.bi.module.constants.ResponseConstants
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.stereotype.Component
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
@Component
@Aspect
public class AopBean {
private static final Logger logger = LoggerFactory.getLogger(AopBean.class)
@Pointcut("within(com.bim.controllers..*) && !within(com.bim.controllers.LoginController)")
public void pointCut() {
}
@Around("pointCut()")
public Object trackInfo(ProceedingJoinPoint pjp) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()
HttpServletRequest retValue = attributes.getRequest()
User user = (CDObjUser) retValue.getSession().getAttribute("user")
if (user == null) {
logger.info("-------------用户未登陆------sessionID:{}", retValue.getSession().getId())
return ResultUtil.getResponse(Boolean.FALSE, ResponseConstants.E133.getCode(), ResponseConstants.E133.getMessage())
}
return pjp.proceed()
}
}