首先定义验证码和登录监测的两个注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 检查验证码
* @author wanlf
*/
@Target(value = { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckCode {
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 检查是否登录注解
* @author wanlf
*/
@Target(value = { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckLogin {
}
然后定义两个切面aop
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.miaoshaproject.annotation.CheckCode;
import com.miaoshaproject.tool.IConstant;
/**
* 验证码验证
* @author wanlf
*/
@Component
@Aspect
public class CheckCodeAop implements IConstant{
private static final Logger logger=LoggerFactory.getLogger(CheckCodeAop.class);
@Resource
HttpServletRequest request;
@Pointcut("execution(* com.icbc.support.controller..*(..))")
public void controller(){
}
@Around("controller()")
public Object beforeController(ProceedingJoinPoint joinPoint)throws Throwable{
Map<String, Object> retMap = new HashMap<String, Object>();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
if (method.isAnnotationPresent(CheckCode.class)) {
logger.info("------[CheckCodeAop]----验证码开始");
String webCode = getWebCode(joinPoint);
logger.info("---前台送的code是:{}", webCode);
if (StringUtils.isNoneBlank(webCode)) {
String code = (String) request.getSession().getAttribute("CK_validateCode");
logger.info("---从session中取出的code是:{}", code);
long codeTime = 0;
String validateTime = request.getSession().getAttribute("CK_validateTime") == null ? ""
: String.valueOf(request.getSession().getAttribute("CK_validateTime"));
logger.info("-----从session中取出的code生成时间:{}", validateTime);
if (StringUtils.isNotBlank(validateTime) && StringUtils.isNumeric(validateTime)) {
codeTime = Long.parseLong(validateTime);
} else {
logger.info("未取到用户服务放置到session中code的生成时间------");
request.getSession().setAttribute("CK_validateCode", "");
retMap.put(RETCODE, RETCODE_CODE_FAIL);
retMap.put(RETMSG, "未取到服务生成验证码时间,无法校验,请重试");
logger.info("------[CheckCodeAop]----拦截结束");
return retMap;
}
if ((System.currentTimeMillis() - codeTime) > 5 * 60 * 1000) {
logger.info("-----[CheckCodeAop]---验证码已过期,有效时间5分钟");
request.getSession().setAttribute("CK_validateCode", "");
retMap.put(RETCODE, RETCODE_CODE_FAIL);
retMap.put(RETMSG, "验证码已过期,请重新输入");
logger.info("------[CheckCodeAop]----拦截结束");
return retMap;
} else if (!webCode.equalsIgnoreCase(code)) {
logger.info("-----[CheckCodeAop]---验证码错误");
request.getSession().setAttribute("CK_validateCode", "");
retMap.put(RETCODE, RETCODE_CODE_FAIL);
retMap.put(RETMSG, "验证码错误,请重新输入");
logger.info("------[CheckCodeAop]----拦截结束");
return retMap;
}
} else {
logger.info("-----目标打上了@CheckCode标签,但又没有送code-------");
request.getSession().setAttribute("CK_validateCode", "");
retMap.put(RETCODE, RETCODE_CODE_FAIL);
retMap.put(RETMSG, "请提供验证码");
logger.info("------[CheckCodeAop]----拦截结束");
return retMap;
}
request.getSession().setAttribute("CK_validateCode", "");
}
return joinPoint.proceed();
}
//获取验证码
private String getWebCode(ProceedingJoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String[] paramsName = signature.getParameterNames(); // 方法的所有的参数名
Object[] obj = joinPoint.getArgs(); // 方法所有的参数值
int webCodeIndex = -1;
if (paramsName.length > 0) {
for (int i = 0; i < paramsName.length; i++) {
if ("webCode".equals(paramsName[i])) {
webCodeIndex = i;
break;
}
}
if (webCodeIndex == -1)
return null; // 说明未找到webCode验证码
return (String) obj[webCodeIndex]; // 返回验证码
}
return null;
}
}
import java.lang.reflect.Method;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.miaoshaproject.annotation.CheckLogin;
import com.miaoshaproject.service.ex.NotLoginException;
/**
* 登陆验证
* @author wanlf
*/
@Component
@Aspect
public class CheckLoginAop {
private static final Logger logger=LoggerFactory.getLogger(CheckLoginAop.class);
@Resource
HttpServletRequest request;
@Pointcut("execution(* com.icbc.support.controller..*(..))")
public void controller(){
}
@Around("controller()")
public Object beforeController(ProceedingJoinPoint joinPoint)throws Throwable{
logger.info("------[CheckLoginAop]---是否登录验证开始");
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
if (method.isAnnotationPresent(CheckLogin.class)) {
if (request.getSession().getAttribute("user") == null) {
logger.info("未登陆异常");
throw new NotLoginException("未登陆异常");
} else {
logger.info("---session.getAttribute----用户已登陆");
return joinPoint.proceed();
}
} else {
logger.info("----[CheckLoginAop]----无需验证");
return joinPoint.proceed();
}
}
}
异常定义及处理
public class NotLoginException extends RuntimeException {
private static final long serialVersionUID = 69111509634504432L;
public NotLoginException() {
}
public NotLoginException(String message) {
super(message);
}
}
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.miaoshaproject.service.ex.NotLoginException;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = NotLoginException.class)
public void exceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws IOException {
logger.info("处理异常开始");
if (e instanceof NotLoginException) {
logger.info("处理未登陆异常进行中");
resp.sendRedirect(req.getContextPath() + "/templates/serviceSystem/index.html");
logger.info("处理未登陆异常结束");
}
logger.info("处理异常结束");
}
}
跨域处理
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SuppressWarnings("deprecation")
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
// 跨域配置
corsRegistry.addMapping("/**").allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS").allowCredentials(true);
}
}