STRUTS2 Interceptor Recording System operation log

Source: Internet
Author: User

    • Objective

Recently developed a project, because the project in the entire development process in a hurry state (almost every project), so the project in the closing phase of the discovery of the lack of logging system log function, the previous system is directly written in the code of each module, and then deposited into the form, on the page can view some of the logs. This system does not have this requirement, so it is thought to do a system common log records, the main record data are: Operation time, Operation Object, operation method, the operation of some parameters and operation results. The immediate idea was to use aspect to implement AOP logging, but in practice it was found that aspect was not a friendly interception action, but was primarily used to intercept service layer operations. Since the system framework is based on the SSH framework, the final consideration is to use STRUTS2 's own interceptor interceptor.

    • What interceptor?

  Interceptors are objects that dynamically intercept Action calls. It provides a mechanism to enable developers to define code that executes before and after an action executes, or to prevent it from executing before an action executes. It also provides a way to extract the reusable parts of an action . When it comes to interceptors, there's one more word you should know-the interceptor chain (Interceptor Chain, called the Interceptor stack interceptor stackin Struts 2 ). The Interceptor chain is a chain that binds the interceptor in a certain order. When accessing an intercepted method or field, interceptors in the interceptor chain are called in the order in which they were previously defined.

    • The principle and approximate flow of interceptors

When 1.ActionInvocation is initialized, all INTERC eptor associated with the action are loaded according to the configuration.

2. When the action implementation is invoked by the Actioninvocation.invoke method, the interceptor is executed.

Interceptor has a lot of functionality from our action, which reduces the code of our action, and the behavior of independence is very good reusability. Many of the features of Xwork and WebWork are interceptor implemented, and you can assemble the interceptor that the action uses in the configuration file, which runs before and after the action in the order you specify.

    • Project Implementation Interceptor Code
1  Packagecom.mnsn.utils;2 3 ImportJava.io.BufferedWriter;4 ImportJava.io.File;5 ImportJava.io.FileWriter;6 ImportJava.util.Calendar;7 ImportJava.util.Map;8 ImportJava.util.Set;9 Ten ImportOrg.apache.struts2.ServletActionContext; One  A ImportCom.mnsn.project.user.User; - Importcom.opensymphony.xwork2.ActionInvocation; - ImportCom.opensymphony.xwork2.interceptor.Interceptor; the ImportCom.opensymphony.xwork2.interceptor.PreResultListener; -  - /** - * System Log Interceptor + * @AUTHER Liulonglong - * @Motto goals determine what is going to be. + * @URLhttp://www.cnblogs.com/mvilplss/ A * @Time pm 04:09:37 at * @Version -  */ -  Public classDologImplementsInterceptor { -  -     Private Static Final LongSerialversionuid = 1L; -  in      PublicString intercept (actioninvocation ai)throwsException { -  toAi.addpreresultlistener (NewPreresultlistener () { +  -              Public voidBeforeresult (actioninvocation ai, String arg1) { the                 Try { *StringBuffer SB =NewStringBuffer (); $Sb.append (MYUTILS.GETDATAYMDHMS2 () + ":");Panax NotoginsengMap<string, object> session =Ai.getinvocationcontext (). getsession (); -User user = (user) Session.get ("Loginuser")); the                     if(User! =NULL) { +Sb.append ("Operator:" +user.getname ()); A}Else { theSb.append ("Operator: System not acquired"); +                     } -Sb.append ("Class name:" + ai.getaction () + ""); $Sb.append ("Method Name:" + Ai.getinvocationcontext (). GetName () + ""); $map<string, object> map =Ai.getinvocationcontext (). GetParameters (); -set<string> keys =Map.keyset (); -Sb.append ("parameter:"); the                      for(String key:keys) { -Sb.append (key + "=" + ((object[]) Map.get (key)) [0]+ "#");Wuyi                     } theSb.append (""); -Sb.append ("Execution Result:" + ai.getresultcode () + ""); WuString AppPath = Servletactioncontext.getservletcontext (). Getrealpath ("/"); -Savelog (AppPath + "Operlog", sb.tostring ()); About}Catch(Exception e) { $ e.printstacktrace (); -                 } -  -             } A         }); +  the         returnAi.invoke (); -     } $  the      Public Static voidSavelog (String dir, string content) { the         Try { theFile Path =NewFile (dir); the             if(!path.exists ()) { - Path.mkdir (); in             } theFile LogDir =NewFile (path + "/" the+ (Calendar.getinstance (). Get (Calendar.month) + 1)); About             if(!logdir.exists ()) { the Logdir.mkdir (); the             } theFile File =NewFile (LogDir + "/" ++calendar.getinstance (). Get (Calendar.day_of_month) -+ ". Log"); the             if(!file.exists ()) {Bayi file.createnewfile (); the             } theBufferedWriter br =NewBufferedWriter (NewFileWriter (file,true)); - br.write (content); - br.newline (); the Br.flush (); the br.close (); the  theFile Logdirold =NewFile ( - Path the+ "/" the+ (Calendar.getinstance (). Get (Calendar.month)-2 > 0?(Calendar the. getinstance (). Get (Calendar.month)-2)94 : Calendar.getinstance () the. Get (Calendar.month) + 10)); the             if(Logdirold.exists ()) { thefile[] Fileolds =logdirold.listfiles ();98                  for(File f:fileolds) { About F.delete (); -                 }101 Logdirold.delete ();102             }103}Catch(Exception e) {104 e.printstacktrace (); the         }106 107     }108 109      Public voiddestroy () { the 111     } the 113      Public voidinit () { the  the     } the}
    • Project section Configuration

<!--configuring interceptors-        <interceptors>            class= "Com.mnsn.utils.Dolog" ></interceptor>            <interceptor-stack name= "Defaultstack" >                <interceptor-ref name= "Dolog" ></interceptor-ref >                   <interceptor-ref name= "Defaultstack" ></interceptor-ref>               </interceptor-stack>        </interceptors>

    • Execution results

Taken from file: C:\Program files (x86) \tomcat-6.0.43-myeclipse\webapps\qzdl\operlog\3\10.log

20150310173309: operator: The system did not get the class name: [email protected] Method name: Login parameter: loginname=ss#password=ss#x=31#y=11# Execution Result: Pass20150310173313: operator: Qinzhou boss class name: [email protected] Method Name: List parameter: Execution result: List20150310173322: operator: Qinzhou boss class name: [email protected] Method name: Delete parameter: users[0].id=402881ec4b38cf8f014b38d4510f0001# Execution Result: toList20150310173323: operator: Qinzhou boss class name: [email protected] Method Name: List parameter: Execution result: List20150310173326: operator: Qinzhou boss class name: [email protected] Method name: Tooper parameter: user.id=402881fd4becf4d5014becf8253c0000# Execution Result: Oper20150310173328: operator: Qinzhou boss class name: [email protected] Method name: Update parameter: towhere= #user. createtime=2015-03-06 10:44:20.0# User.group.id=402881ef4a9f4536014a9f69be6c0005#user.id=402881fd4becf4d5014becf8253c0000#user.job= Department Head # User.loginname=wml#user.mobilephone=18758010019#user.name= Wang Ming Lu #user.office_telephone=0571-6856156#user.password =123456#user.remark= This person is a departmental administrator #user.unit.id=402881fd4becf4d5014bed053ce80001# Execution Result: toList20150310173328: operator: Qinzhou boss class name: [email protected] Method Name: List parameter: Execution result: List
    • Summarize

Struts2 interceptors are relatively easy to use and understand relative to aspect, for the requirements of the general system operation log can be used interceptors, and aspect important for fine-grained control method of the export and import, to achieve the logic layer enhancement, such as declarative things.

    • Note

This article in busy work in the code out, if there is a mistake unavoidable, hope readers point out, thank you!

STRUTS2 Interceptor Recording System operation log

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.