AOP做登录
作者:互联网
controller
不需要验证登录的controller
@RestController
public class LoginController {
@RequestMapping("/login")
public String login(HttpSession session, String name, String password){
System.out.println(name);
System.out.println(password);
// 这个需要查数据库判断用户名和密码是否正确
if(Objects.equals(name, "xx") && Objects.equals(password, "xx"))
{
// 成功服务器记录sessionid,并设置生存时间,可以自行设置删除策略
LoginAop.MAP.put(session.getId(),16);
return "成功";
}
return "失败";
}
@RequestMapping("/index")
public String index(){
return "登录";
}
}
需要验证controller
@RestController
public class TestController {
@RequestMapping("/hello")
public String helloWorld(){
return "hello world";
}
@RequestMapping("/hello02")
public String helloWorld02(){
return "hello world 02";
}
}
aop 设置
用within定义aop所代理的类(需要验证登录的类)
用!within定义aop不需要代理的类(不需要验证登录的类)
@Aspect
@Component
public class LoginAop {
public static final HashMap<String, Integer> MAP = new HashMap<>();
@Pointcut("within(com.example.dockerredisqueue.controller.*)&&!within(com.example.dockerredisqueue.controller.LoginController)")
public void loginCut(){
}
@Autowired
LoginController loginController;
@Around("loginCut()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attributes != null;
HttpServletRequest request = attributes.getRequest();
if(!MAP.containsKey(request.getRequestedSessionId())) {
System.out.println(request.getRequestedSessionId());
return loginController.index();
}
// 获取session中的用户信息
return proceedingJoinPoint.proceed();
}
}
标签:return,String,登录,within,controller,AOP,public,RequestMapping 来源: https://www.cnblogs.com/jefferyeven/p/16066513.html