An example of Spring AOP in Web Development - About Struts Framework

xiaoxiao2021-04-07  354

In web development, users' access to web pages is an important part. Take Strust as an example, we need to write related code in the action of an action (usually a function of calling the base class), it is also clear that in each action is a repetitive labor.

If we can automatically call the base class permission check function before the Excute is running, this is undoubtedly a good solution. AOP provides us with such a solution.

The following is an implementation of a simplified example.

First we do an interface:

public interface CheckInterface {public abstract void check (String name); public abstract void excute (String name);} Well, to make a notification following class (Advice): import org.springframework.aop.MethodBeforeAdvice; import java.lang.reflect .Method; import org.apache.log4j.Logger; public class BeforeAdvisor implements MethodBeforeAdvice {private static Logger logger = Logger.getLogger (BeforeAdvisor.class); public void before (Method m, Object [] args, Object target) throws Throwable { IF (Target InstanceOf Checkinterface) {Logger.debug ("IS InstanceOf Checkinterface !!!"); Checkinterface Ci = (Checkinterface) Target; Ci.check ((String) args [0]);}}} in the important Before Parameters: Object Target Introduced Notification Object (ie, the test class interface), method M, Object [] ARGS is the method and parameter of the object being called.

Let's make a Spring bean definition XML file: Spring Quick Start . * Excute. * com.wysm.netstar.test.springaop.CheckInterface < / proty> mypointcutadvisor2 This definition file indicates that ExcuteClass is a monitor object, its Excute method is executed. At the time, BeForeAdvisor will be called.

Finally, test classes: import junit.framework.TestCase; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class SpringTestCase2 extends TestCase {CheckInterface test = null; protected void setUp () throws Exception {super.setUp (); ApplicationContext ctx = new FileSystemXmlApplicationContext ( "src / com / wysm / netstar / test / springaop / aoptest.xml"); test = (CheckInterface) ctx.getBean ( "myCheckClass");} protected void tearDown () THROWS Exception {Super.TearDown ();} public void testexcute () {test.excute ("supervisor");}} Do a base class:

Public Abstract Class BaseClass Implements Checkinterface {

Public BaseClass () {

}

Public void check (string name) {

IF (name.equals ("supervisor"))

System.out.println ("Check Pass !!");

Else {

System.out.println ("No Access Privilegle!");

}

}

}

Do another test class:

Public class excuteclass extends baseclass {

Public excuteclass () {

}

Public void excuters (string name) {

System.out.println ("Excute Here!" Name);

}

}

转载请注明原文地址:https://www.9cbs.com/read-132528.html

New Post(0)