springaop实现登陆验证

时间:2022-11-05 23:01:02

1.首先配置好springmvc和springaop

2.先写好登陆方法,通过注解写代理方法

通过代理获得登陆方法的参数方法名,然后再aop代理方法内进行登陆验证

贴出代码

 package com.huawei.controller;

 import java.util.HashSet;
import java.util.Set; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import com.huawei.entity.User; @Controller
public class LoginController { private static Set<User> set; public Set<User> getSet() {
return set;
} public void setSet(Set<User> set) {
this.set = set;
} static{
set = new HashSet<User>();
User user1 = new User(1, "tom", "123");
User user2 = new User(2, "sofiya", "123");
User user3 = new User(3, "xuanxuan", "123");
set.add(user1);
set.add(user2);
set.add(user3); }
@SuppressWarnings("unused")
@RequestMapping(value={"/login"},method=RequestMethod.POST)
public String login(@RequestParam("username") String username, @RequestParam("password") String password,Model modle) {
String result=null;
for (User user : set) {
if (user.getUsername().equals(username) && user.getPassword().equals(password)) {
result = "success";
break;
} else {
result = "login";
}
}
return result;
}
@RequestMapping("/view")
public String view(){
return "login";
}
}
 package com.huawei.aop;

 import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component; @Component
@Aspect
public class LoginAop { @Before("execution(* com.huawei.controller.*.*(..))")
public void befores(JoinPoint point){
System.out.println(point);
System.out.println("LoginAop.befores()");
登陆验证方法省略
}
}
Enhancer 重生成代理类
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserServiceImpl.class);
enhancer.setCallback(new MyMethodInterceptor());
UserServiceImpl userService = (UserServiceImpl)enhancer.create();