最近开发有一个需求需要在 aop 中获取request response ,搜索许久没有答案,故此记录~
package com.example.easy_im.aop;
import com.example.easy_im.Context;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.Objects;
@Aspect
@Component
@Slf4j
public class TokenAop {
@Around("@annotation(com.example.easy_im.annotation.NeedToken)")
public Object check(ProceedingJoinPoint pjp) throws Throwable {
try {
HttpServletRequest servletRequest = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
HttpServletResponse servletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
String authorizationHeader = servletRequest.getHeader("Authorization");
if(StringUtils.isBlank(authorizationHeader) || servletResponse == null) {
servletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return "请携带Authorization请求头";
}
// 执行目标方法
Object proceed = pjp.proceed();
Context.clear();
return proceed;
} catch (Exception e) {
return "fail";
}
}
}
package com.example.easy_im.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NeedToken {
}
package com.example.easy_im.controller;
import com.example.easy_im.Context;
import com.example.easy_im.annotation.NeedToken;
import com.example.easy_im.dao.UserDao;
import com.example.easy_im.entity.User;
import com.example.easy_im.util.TokenUtil;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Example;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserDao userDao;
@PostMapping("/login")
public String login(@Validated @RequestBody User user) {
User obj = userDao.findUserByNameAndPwd(user.getUserName(), user.getUserPwd());
if(obj == null) {
return "fail";
}
return TokenUtil.generateToken(obj);
}
@DeleteMapping("/logout")
@NeedToken
public String logout() {
String token = Context.getToken();
TokenUtil.destroyToken(token);
return "ok";
}
}