類似用戶權(quán)限的需求膝晾,有些操作需要登錄栓始,有些操作不需要,可以使用過濾器filter血当,但在此使用過濾器比較死板幻赚,如果用的話,就必須在配置文件里加上所有方法臊旭,而且 不好使用通配符落恼。這里可以采用一種比較簡單靈活的方式,是采用spring 的 methodInterceptor攔截器完成的离熏,并且是基于注解的佳谦。大概是用法是這樣的:
@LoginRequired
@RequestMapping(value = "/comment")
public void comment(HttpServletRequest req, HttpServletResponse res) {
// doSomething,,,,,,,,
}
這里是在Spring mvc 的controller層的方法上攔截的,注意上面的@LoginRequired 是自定義的注解滋戳。這樣的話钻蔑,該方法被攔截后啥刻,如果有該注解,則表明該 方法需要用戶登錄后才能執(zhí)行某種操作咪笑,于是可帽,我們可以判斷request里的session或者Cookie是否包含用戶已經(jīng)登錄的身份,然后判斷是否執(zhí)行該方法窗怒;如果沒有蘑拯,則執(zhí)行另一種操作。
下面是自定義注解的代碼:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {
}
下面是自定義的方法攔截器兜粘,繼續(xù)自aop的MethodInterceptor
import javax.servlet.http.HttpServletRequest;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class LoginRequiredInterceptor1 implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
Object[] ars = mi.getArguments();
for(Object o :ars){
if(o instanceof HttpServletRequest){
System.out.println("------------this is a HttpServletRequest Parameter------------ ");
}
}
// 判斷該方法是否加了@LoginRequired 注解
if(mi.getMethod().isAnnotationPresent(LoginRequired.class)){
System.out.println("----------this method is added @LoginRequired-------------------------");
}
//執(zhí)行被攔截的方法,切記弯蚜,如果此方法不調(diào)用孔轴,則被攔截的方法不會(huì)被執(zhí)行。
return mi.proceed();
}
}
配置文件:
<bean id="springMethodInterceptor" class="com.qunar.wireless.ugc.interceptor.LoginRequiredInterceptor1" ></bean>
<aop:config>
<!--切入點(diǎn)-->
<aop:pointcut id="loginPoint" expression="execution(public * com.qunar.wireless.ugc.controllor.web.*.*(..)) "/>
<!--在該切入點(diǎn)使用自定義攔截器-->
<aop:advisor pointcut-ref="loginPoint" advice-ref="springMethodInterceptor"/>
</aop:config>