Get Bean in struts 2 interceptor and read spring XML file in WEB-INF
1. Get Bean directly
Public class operaloginterceptor extends actinterceptor {Private Static final long serialversionuid = 1l; @ resolve ("unchecked") protected set excludemethods; @ resolve ("unchecked") protected set includemethods; /*** interceptor Method */@ suppresswarnings ({"unchecked", "static-access"}) Public String intercept (actioninvocation Invocation) {string result = NULL; httpservletrequest request = Serv Letactioncontext. getrequest (); baseaction action = (baseaction) invocation. getaction (); servletcontext SC = servletactioncontext. getservletcontext (); // applicationcontext CTX = webapplicationcontextutils. getrequiredwebapplicationcontext (SC); applicationcontext CTX = webapplicationcontextutils. getwebapplicationcontext (SC); moduleservice = (moduleservice) CTX. getbean ("moduleservice"); // module se Rviceoperationlogservice logservice = (operationlogservice) CTX. getbean ("operationservice"); // module servicetry {result = invocation. invoke (); // determine whether to write logs if (applymethod (excludemethods, includemethods, invocation. getproxy (). getmethod () {This. savelog (getmodulename (request, moduleservice), alphautil. getip (request), request. getremotehost (), action. getemployee (). geteid (), action. getemployee (). getename (), L Ogservice) ;}} catch (exception e) {e. printstacktrace (); Return Action. success;} return result;}/*** return module URL ** @ Param Request * @ Param action * @ return */@ suppresswarnings ("unchecked ") private string getmodulename (httpservletrequest request, moduleservice) {// string modulename = request. getrequesturi () + stringutil. getparamstring (request. getparametermap (); string modulename = ""; stri Ng url = request. getrequesturi (); If (URL. length ()> 20) {url = URL. substring (17);} List MList = moduleservice. query ("from tbmodule where murl = '" + URL + "'"); If (null! = MList & MList. size ()> 0) {tbmodule module = (tbmodule) MList. get (0); modulename = module. getmname ();} system. out. println ("modulename =" + modulename); Return modulename ;} /*** return whether to write operation logs ** @ Param excludemethods * @ Param includemethods * @ Param Method * @ return */private Boolean applymethod (set <string> excludemethods, set <string> includemethods, string method) {If (includemethods! = NULL) {for (string S: includemethods) {Boolean BL = pattern. compile (s ). matcher (method ). matches (); If (BL) return true ;}} if (excludemethods! = NULL) {for (string S: excludemethods) {Boolean BL = pattern. compile (s ). matcher (method ). matches (); If (BL) return false;} return true;}/*** write operation log * @ Param olbusinussname: business name * @ Param oloperationip: operator IP * @ Param oloperationtable: Operator table name * @ Param oloperationuserid: Operator ID * @ Param oloperationusername: Operator name * @ Param logservice */private void savelog (string olbusinussname, string oloperationip, string oloperationtable, integer oloperationuserid, string oloperationusername, operationlogservice logservice) {try {tboperationlog oplog = new tboperationlog (); oplog. setoloperationdate (new date (); oplog. setolbusinussname (olbusinussname); oplog. setoloperationip (oloperationip); oplog. setoloperationtable (oloperationtable); oplog. setoloperationuserid (oloperationuserid); oplog. setoloperationusername (oloperationusername); logservice. save (oplog);} catch (exception e) {e. printstacktrace () ;}} public void setexcludemethods (string excludemethods) {This. excludemethods = textparseutil. commadelimitedstringtoset (excludemethods);} public set getexcludemethodsset () {return excludemethods;} public void setincludemethods (string includemethods) {This. includemethods = textparseutil. commadelimitedstringtoset (includemethods);} public set getincludemethodsset () {return includemethods;} public static void main (string a []) {Boolean BL = pattern. compile (""). matcher (""). matches (); // if the condition is met, true is returned; otherwise, falsesystem is returned. out. println (BL );}}
2. Various methods for reading XML:
Read XML files/**
* Use xmlbeanfactory (resource Resource)
* Here, resource must be in XML format.
* Resources include: abstractresource, classpathresource, filesystemresource,
* Inputstreamresource, servletcontextresource, urlresource
*/
/*
* Use inputstreamresource (inputstream)
* Put applicationcontext. XML in the project root directory.
*/
Inputstream is = NULL;
Try {
Is = new fileinputstream ("applicationcontext. xml ");
} Catch (filenotfoundexception e ){
E. printstacktrace ();
}
Resource resource = new inputstreamresource (is );
Beanfactory factory = new xmlbeanfactory (Resource );
Userdao = (userdao) Factory. getbean ("userdao ");
/*
* Use properties
* Put bean. properties in the class path-source folder (SRC) directory.
*/
See http://blog.csdn.net/lwzcjd/archive/2008/10/21/3116298.aspx for details
1. Use classpathxmlapplicationcontext
You can read XML files from classpath.
(1) applicationcontext context = new classpathxmlapplicationcontext ("applicationcontext. xml ");
Userdao = (userdao) Context. getbean ("userdao ");
(2) classpathxmlapplicationcontext resource = new classpathxmlapplicationcontext (New String [] {"applicationContext-ibatis-oracle.xml", "applicationcontext. xml", "applicationContext-data-oracle.xml "});
Beanfactory factory = resource;
Userdao = (userdao) Factory. getbean ("userdao ");
2. Use classpathresource
You can read XML files from classpath.
Resource Cr = new classpathresource ("applicationcontext. xml ");
Beanfactory BF = new xmlbeanfactory (CR );
Userdao = (userdao) BF. getbean ("userdao ");
Loading an XML file org. springframework. Beans. Factory. config. propertyplaceholderconfigurer does not work.
3. Use xmlwebapplicationcontext to read
In the file architecture of a web application, specify a relative location to read the definition file.
The xmlwebapplicationcontext constructor cannot contain parameters, and you will find that the default location points to the/WEB-INF/applicationcontext. xml file by referring to the API file. Use its public static attribute default_config_location to obtain the default file name. Since I use myeclipse, one more "/webroot" directory is preset before the WEB-INF, therefore, if some web-independent programs in the web project need to use context (for example, to process the "M" section in some MVC architectures ), xmlwebapplicationcontext cannot be used to read the bean definition file, because the default location will be a "webroot" directory.
That is. in XML, the same is true for the definition of contextconfiglocation in the dispatcherservlet definition (this definition can override the default_config_location value in xmlwebapplicationcontext), because programs unrelated to the Web do not pass through the Web. XML definition file settings. At present, I have not tried xmlwebapplicationcontext to get the bean definition file. It is faster to use classpathxmlapplicationcontext.
Xmlwebapplicationcontext CTX = new xmlwebapplicationcontext ();
CTX. setconfiglocations (New String [] {"/WEB-INF/applicationcontext. xml ");
CTX. setservletcontext (pagecontext. getservletcontext ());
CTX. Refresh ();
Userdao = (userdao) CTX. getbean ("userdao ");
4. use filesystemresource to read resource RS = new filesystemresource ("D:/tomcat/webapps/test/WEB-INF/classes/applicationcontext. XML "); beanfactory factory = new xmlbeanfactory (RS); userdao = (userdao) factory. getbean ("userdao"); it is worth noting that with filesystemresource, the configuration file must be placed in the direct directory of the project, or the absolute path must be specified, otherwise, an exception that cannot find the file will be thrown. you can use filesystemxmlapplicationcontext to read the definition file by specifying the relative or absolute path of the XML definition file. Method 1: String [] Path = {"webroot/WEB-INF/applicationcontext. XML "," webroot/WEB-INF/applicationcontext_task.xml "}; applicationcontext context = new filesystemxmlapplicationcontext (PATH); Method 2: String Path =" webroot/WEB-INF/applicationcontext *. XML "; applicationcontext context = new filesystemxmlapplicationcontext (PATH); Method 3: applicationcontext CTX = new filesystemxmlapplicationcontext (" classpath: Address "); no Cl Asspath is the current working directory ******************************** **************************************** ***************************** **************************************** * *********** there are multiple methods to obtain class instances managed by the Spring framework, method 1: Save the applicationcontext object code during initialization: applicationcontext AC = new filesystemxmlapplicationcontext ("applicationcontext. XML "); AC. getbean ("beanid"); Note: This method is applicable to independent applications that use the Spring framework. Manually initialize the spring file. Method 2: Use the tool class provided by spring to obtain the applicationcontext object code: Import Org. springframework. web. context. support. webapplicationcontextutils; applicationcontext AC1 = webapplicationcontextutils. getrequiredwebapplicationcontext (servletcontext SC) applicationcontext ac2 = webapplicationcontextutils. getwebapplicationcontext (servletcontext SC) ac1.getbean ("beanid"); ac2.getbean ("beanid"); Note: This method is suitable for B/S systems using the Spring framework, through Serv The letcontext object gets the applicationcontext object, and then obtains the required class instance through it. The difference between the two tools is that the former throws an exception when the acquisition fails, and the latter returns NULL. Method 3: inherit from the abstract class applicationobjectsupport Description: The abstract class applicationobjectsupport provides the getapplicationcontext () method to conveniently obtain applicationcont Ext. During spring initialization, The applicationcontext object is injected through the setapplicationcontext (applicationcontext context) method of this abstract class. Method 4: Inherit from abstract class webapplicationobjectsupport Description: similar to the above method, call getwebapplicationcontext () to obtain webapplicationcontext Method 5: Implement interface applicationcontextaware Description: implement the setapplicationcontext (applicationcontext context) method of this interface, and save the applicationcontext object. During spring initialization, The applicationcontext object is injected using this method. The preceding method is applicable to different situations. Select the appropriate method based on the actual situation. It is worth mentioning that the classes used in the above method in the system are actually tightly coupled with the Spring framework, because these classes know that they are running on the Spring framework, therefore, this type of applications should be minimized in the system so that the system is as independent as possible from the current runtime environment and the desired service provider should be obtained through di. In my opinion, Method 5 is feasible. You can design a tool class to obtain classes in spring. Reduce the intrusion to business code.