1、参照 如下文章- 实战篇:设计自己的Annotation
http://www.iteye.com/topic/36659
2、
http://www.iteye.com/topic/36659
2、
- 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 NeedLogin {
- }
- mport java.util.Map;
- import java.util.Set;
- import javax.servlet.http.HttpSession;
- import org.aopalliance.intercept.MethodInterceptor;
- import org.aopalliance.intercept.MethodInvocation;
- import org.apache.struts.Globals;
- import com.xasxt.cake.common.WebContext;
- public class SafeAsepct implements MethodInterceptor {
- public Object invoke(MethodInvocation mi) throws Throwable {
- //判读用户身份
- HttpSession session = WebContext.getSession();
- if (session.getAttribute("USER_LOGIN")==null) {
- //如果没有,返回null。如果有,返回注解对象
- NeedLogin needLogin = mi.getMethod().getAnnotation(NeedLogin.class);
- if (needLogin!=null) {
- String uri = WebContext.getRequest().getRequestURI() + "?";
- //Key : String, Value : String[]
- Map map = WebContext.getRequest().getParameterMap();
- Set keys = map.keySet();
- for (Object key : keys) {
- uri += key + "=";
- //简化了问题
- uri += ((String[])map.get(key))[0] + "&";
- }
- System.out.println("uri = " + uri);
- WebContext.getSession().setAttribute("LAST_URI", uri);
- throw new LoginException("您需要登录才能使用此功能!");
- }
- }
- return mi.proceed(); //chain.doFilter(req, myRes);
- }
- public static void main(String[] args) {
- WebContext.getSession();
- }
- }
- <!-- 抽象Bean (模板) -->
- <bean id="BizTemplate"
- class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
- abstract="true">
- <property name="transactionManager" ref="tm"></property> <!-- 谁来代理 -->
- <property name="proxyTargetClass" value="true"></property> <!-- 代理方式true:cglib, false:动态代理 -->
- <property name="transactionAttributes">
- <props>
- <!-- 事务的传播行为 -->
- <prop key="get*">PROPAGATION_REQUIRED, readOnly</prop>
- <prop key="find*">PROPAGATION_REQUIRED, readOnly</prop>
- <prop key="*">PROPAGATION_REQUIRED</prop>
- </props>
- </property>
- </bean>
- <bean id="cakeBizTarget" class="com.xasxt.cake.biz.impl.CakeBiz">
- <property name="cakeDAO" ref="CakeDAO"></property>
- </bean>
- <bean id="shopBiz" parent="BizTemplate">
- <property name="target" ref="shopBizTarget"></property> <!-- 代理谁? -->
- </bean>
- <bean id="cakeBiz2" parent="BizTemplate">
- <property name="target" ref="cakeBizTarget"></property> <!-- 代理谁? -->
- </bean>
- <!-- 安全切面 -->
- <bean id="safe" class="com.xasxt.cake.aspect.SafeAsepct" />
- <!-- 配置代理 -->
- <bean id="cakeBiz" class="org.springframework.aop.framework.ProxyFactoryBean">
- <property name="target" ref="cakeBiz2"></property>
- <property name="interceptorNames" value="safe"></property>
- </bean>