ANNOTATION,SPRING,AOP concepts such as this is not introduced here, the relevant knowledge on the Internet in a large pile, but also the major companies interview must test content. A large part of the current AOP technology scenario should be used to implement operational logging, since almost every company has its own development framework, and many frameworks are highly encapsulated in such operations as CRUD, and the service level almost eliminates 90% of the code, This makes it a bit cumbersome to use AOP to record CRUD operations for each module, and here's a way to use annotation to log on the controller level:
1. Homepage Create a annotation class
Import Java.lang.annotation.ElementType;
Import java.lang.annotation.Inherited;
Import java.lang.annotation.Retention;
Import Java.lang.annotation.RetentionPolicy;
Import Java.lang.annotation.Target;
@Inherited
@Retention (retentionpolicy.runtime)
@Target (elementtype.method) public
@interface traced {
String name () default "";//defaults to NULL
}
2. Create core AOP action classes: Controllertraceaspect
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.lang.builder.ToStringBuilder;
Import Org.aspectj.lang.ProceedingJoinPoint;
Import Org.aspectj.lang.annotation.Around;
Import Org.aspectj.lang.annotation.Aspect;
Import Org.aspectj.lang.annotation.Pointcut;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import org.springframework.beans.factory.annotation.Autowired;
Import Org.springframework.core.annotation.AnnotationUtils;
Import Org.springframework.security.core.context.SecurityContextHolder;
Import Org.springframework.security.core.userdetails.UserDetails;
Import Org.springframework.security.web.authentication.WebAuthenticationDetails;
@Aspect public class controllertraceaspect{protected Logger Logger = Loggerfactory.getlogger (GetClass ());
/** * All Inquiries method * * * @Around ("Execution (* org.tshark.core.orm.hibernate.EntityManager.search (..))") Public Object Searchaground (Proceedingjoinpoint pjp) throws Throwable {if (Tracecontextholderfactory.gettracecontextholder (). GetContext () = null) {return pjp.proceed ();
else {return doaround (null, Getusercode (), Getremotehost (), PJP); The Pointcut @Pointcut ("Within (@org. Springframework.stereotype.Controller *)") is only Controller to the public void Controller
Pointcut () {}/** * records its execution parameters and returns results for methods that have @traced tags. */@Pointcut ("@annotation (org.tshark.framework.trace.Traced)") public void Tracedmethodpointcut () {} @Around ("Contro Llerpointcut () && tracedmethodpointcut ()) Public Object tracearound (Proceedingjoinpoint pjp) throws Throwable
{return Doaroundcontroller (PJP); Private Object Doaroundcontroller (Proceedingjoinpoint pjp) throws Throwable {String methodname = Pjp.getsignature ()
. GetName ();
object[] args = Pjp.getargs ();
class[] Argsclazz = new Class[args.length];
The parameters of all methods in the controller, the first two respectively: Request,response argsclazz[0] = Httpservletrequest.class;
ARGSCLAZZ[1] = Httpservletresponse.class; TheThree the uploaded model if (args.length = = 3) {argsclazz[2] = Args[2].getclass () for the Save; } traced tracedannotation = Annotationutils.findannotation (Pjp.gettarget (). GetClass (). Getdeclaredmethod (MethodName
, Argsclazz), Traced.class);
String tracename = Tracedannotation.name ();
Return Doaround (Tracename, Getusercode (), Getremotehost (), PJP);
//Get the current logged-on user private string Getusercode () {string usercode = "_system";
Object principal = Securitycontextholder.getcontext (). Getauthentication (). Getprincipal (); if (principal!= null && principal instanceof userdetails) {Usercode = ((userdetails) principal). GetUserName ()
;
return usercode;
//Get current User IP private string getremotehost () {string host = null; Webauthenticationdetails authdetails = (webauthenticationdetails) securitycontextholder.getcontext ().
Getauthentication (). Getdetails ();
if (authdetails!= null) {host = Authdetails.getremoteaddress ();
} return host; } Private String Getoperatecontext (object[] args) {StringBuffer strbuffer = new StringBuffer (); for (int i = 0; i < args.length i++) {if (i==2) {//The third parameter is model Strbuffer.append (Tostringbuilder.reflectiontostri
Ng (Args[i]));
} return strbuffer.tostring ();
Protected Object Doaround (String tracename, String curruser, String host, Proceedingjoinpoint PJP) throws Throwable { Log Records}}
3.Spring configuration file
Configuration in the Web.xml
<servlet>
<servlet-name>TS-Dispatcher</servlet-name>
<servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class>
<init-param>
< Param-name>contextconfiglocation</param-name>
<param-value>classpath*:action-servlet.xml </param-value>
</init-param>
</servlet>
<servlet-mapping>
< servlet-name>ts-dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
Related configuration in Action-servlet.xml (the following configuration must be placed in a configuration file where Action-servlet.xml cannot be placed in service)
<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:jee= "Http://www.springframework.org/schema/jee" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ Spring-mvc-3.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.0.xsd Http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/ Spring-jee-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.0.xsd HTTP://WWW.SPRINGFRAmework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd " Default-lazy-init= "true" > <context:component-scan base-package= "org.tshark.**.action"/> <aop:aspectj- Autoproxy proxy-target-class= "true" > <aop:include name= "controlleraspect"/> </aop:aspectj-autoproxy > <bean id= "controlleraspect" class= "Org.tshark.framework.trace.ControllerTraceAspect"/>
4. Use method, add @Traced to controller (name= "Basic Management > User management: Add or Modify User")
For example:
@Traced (name= management > User management: New or modified users)
@RequestMapping (value = "/save", method = Requestmethod.post)
public void Save (HttpServletRequest request, httpservletresponse response, Usermodel Usermodel) throws Exception {
。。。
}