该注解标注在类上,表示对整个类里面的方法都拦截,如果标注在方法上,则单独拦截此方法。
1.注解类
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Authentication {
String value() default "";
}
2.切面类
@Aspect
@Component
public class ControllerAOP {
//within用于匹配指定类型内的方法执行;
@Pointcut(value = "@within(com.code.annotation.Authentication )")
public void controllerAspect() {
}
@Before("controllerAspect()")
public void doBefore(JoinPoint joinPoint) throws Exception{
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
HttpSession session = request.getSession();
User user= (User) session.getAttribute(SessionKey.SESSION_ADMIN);
if (user == null){
//跳转到登录页面
response.sendRedirect(request.getContextPath()+"/admin/login");
}
}
}
3.Controller
@Authentication //只有经过用户认证才能执行该类的方法
@Controller
@RequestMapping("user")
public class UserController {
@RequestMapping("list")
public ModelAndView list(){
ModelAndView mv = new ModelAndView("user/list");
return mv;
}
}
4.spring-mvc.xml
<!--此处aop和applicationContext.xml里面的aop不是同一个aop-->
<aop:aspectj-autoproxy proxy-target-class="true" />
这样,实现了UserController 里的方法只有登录后的用户才能进去。
网友评论