該注解標注在類上,表示對整個類里面的方法都攔截,如果標注在方法上,則單獨攔截此方法。
1.注解類
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Authentication {
String value() default "";
}
2.切面類
@Aspect
@Component
public class ControllerAOP {
//within用于匹配指定類型內(nèi)的方法執(zhí)行;
@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){
//跳轉(zhuǎn)到登錄頁面
response.sendRedirect(request.getContextPath()+"/admin/login");
}
}
}
3.Controller
@Authentication //只有經(jīng)過用戶認證才能執(zhí)行該類的方法
@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" />
這樣凿将,實現(xiàn)了UserController 里的方法只有登錄后的用戶才能進去。