当前位置:编程学习 > XML/UML >>

xml方式---spring的AOP拦截用户操作

需要日志记录,将所有的web操作记录到数据库中,使用aop来记录日志,当然是一个好的选择,spring中集成aop记录日志的方式有多种(aop的配置方式有多种,注解、xml配置),这里只说一个xml配置的例子。
 
   1、编写日志记录类
   2、配置aop
 
   1、编写日志记录类
 
Java代码 
@SuppressWarnings("unchecked")    
public class LogService {        
   public void logAll(JoinPoint jp){        
  System.out.println("in LogService, method logAll invoked.");        
 System.out.println("========================");       
     StringBuilder sb = new StringBuilder();        
   sb.append("method:" + jp.getSignature().getName());          
 HttpServletRequest request = ServletActionContext.getRequest();    
        Iterator<Entry<String, Object>> iter = request.getParameterMap().entrySet().iterator();        
    boolean isFirst = true;       
     sb.append(" paras:");      
      while(iter.hasNext()){        
        Entry<String, Object> entry = iter.next();      
          if(isFirst){         
           isFirst = false;         
       }else{             
       sb.append("#");      
          }               
 sb.append(entry.getKey() + "=");      
          Object[] allValue = (Object[]) entry.getValue();          
      for(int i = 0; i < allValue.length; i++){           
         if(i != 0){        
                sb.append(",");        
            }               
     sb.append(allValue[i].toString());          
      }        
    }           
           System.out.println(sb.toString());        
    System.out.println("========================");      
  }  
  }          
 
 
 
 2、配置aop
   在applicationContext.xml中配置
Xml代码 
</aop:config>          
    <bean id="logService" class="com.cjnetwork.cms.service.LogService"></bean>           
<aop:config>  www.zzzyk.com
<aop:aspect id="myAspect" ref="logService">  
<aop:pointcut expression="execution(* com.cjnetwork.cms.action.*.*(..))" id="logPointCut"/>  
<aop:before method="logAll" pointcut-ref="logPointCut"/>  
</aop:aspect>  
</aop:config>  
<bean id="logService" class="com.cjnetwork.cms.service.LogService"></bean>  
<aop:config proxy-target-class="true" />    
 
 
基本配置就是这样的,这里需要配置<aop:config proxy-target-class="true" /> ,表示强制使用cglib代理,而不是java本身的代理,这个很重要,如果使用java自带的代理,则会抛出异常,提示说代理类无法转换为我们自己的类,这是因为默认的该属性为false,这种代理方式,需要实现接口的方式,代理返回的类可以转换为对应的接口类,但无法直接转换为类的实现,这种方式不推荐。
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,