use interceptor to log informations (J2EE 6 利用interceptor 打Log)

import javax.interceptor.AroundInvoke;

import javax.interceptor.Interceptor;

import javax.interceptor.InvocationContext;

 

 

Here is the example :

        1.Define the annotation for interceptor

//@Inheritedto specify that the annotation can

//be inherited from superclasses

@Inherited

@InterceptorBinding

@Retention(RetentionPolicy.RUNTIME)

@Target({TYPE, METHOD})

public @interface Logged {

}

 

2. Define the interceptor

@Logged

@Interceptor

public class LoggedInterceptor implements Serializable {

       private static final long serialVersionUID = 274175956305979479L;

 

       public LoggedInterceptor() {

    }

 

    @AroundInvoke

    public Object logMethodEntry(InvocationContext invocationContext)

            throws Exception {

        System.out.println("Entering method: "

                + invocationContext.getMethod().getName() + " in class "

                + invocationContext.getMethod().getDeclaringClass().getName()+"—start”);

        Object o = invocationContext.proceed();

        System.out.println("Entering method: "

                + invocationContext.getMethod().getName() + " in class "

                + invocationContext.getMethod().getDeclaringClass().getName()+"--end");

        return o;

    }

}

 

 

<interceptors>

              <class>com.interceptors.LoggedInterceptor</class>

        </interceptors>    add this in beans.xml to register the interceptor .

 

3.  Use the inceptor : just put the annotation upon the method you want log something

@Logged

       public String redirectUrlTest (){

             

              return "detail.jsf";

       }

 

            here is the output

Entering method: redirectUrlTest in class com.test.render.TestMB--start

 

15:06:18,372 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) hi you are the best  James ! Gentle

 

15:06:18,373 INFO  [stdout] (http-localhost/127.0.0.1:8080-1) Entering method: redirectUrlTest in class com.test.render.TestMB--end

 

猜你喜欢

转载自k1280000.iteye.com/blog/1750421