Aspectwerkz-based aop_jsp programming in Java

Source: Internet
Author: User
Tags aop documentation exception handling html form tomcat

I. Overview of AOP programming

Object-oriented programming technology into the mainstream of software development has a great impact on the way software development, developers can visualize the system graphically using a set of entities and the relationships between them, allowing them to design larger, more complex systems with shorter development cycles than before. The only problem with OO development is that it is inherently static and that subtle changes in requirements can have a significant impact on development progress.

Aspect-oriented Programming (AOP) complements and Perfects OO technology, allowing developers to dynamically modify the static OO model and construct a system that grows to meet new requirements, just as objects in the real world change themselves in their lifecycle Applications can also have new features in the development process.

For example, many people presumably have had the experience of using a servlet as an entry point in developing a simple Web application, which is to receive input from an HTML form with a servlet, which is returned to the user after being processed. The servlet at the beginning may be very simple, with only the smallest amount of code that meets the needs of the user. However, with the implementation of the second requirement, such as exception handling, security, logging, and so on, the volume of the code increases to the original 三、四倍-called "second demand" because the basic function of the servlet is to accept and process the user's request, and for this purpose, the log, Mechanisms such as security are not essential.

AOP allows you to dynamically change OO static models without having to modify the original static model or add the code needed to meet the second requirement (actually, even the original source code is not needed). What's even more amazing is that the code that is added later can often be concentrated in one place instead of spreading the code that was later added to the entire model as if using OO alone.

  Second, the basic terminology

Before introducing the AOP development instance, let's look at several standard AOP terms to better grasp the relevant concepts.

  Cross-cutting concern

In the OO model, although most classes have only a single, specific function, they usually share a second requirement with other classes. For example, when a thread enters or leaves a method, we may have to record the log in the class of the data access layer and the class in the UI layer. Although the basic functionality of each class is extremely different, the code used to satisfy the second requirement is essentially the same.

   Advice

It refers to additional code that you want to apply to an existing model. In this case, it refers to the log code to run when a thread enters or exits a method.

   Point-cut

This term refers to an execution point in an application that requires the preceding cross-cutting concern to be used at this execution point. In this case, a point-cut occurs when a thread enters a method, and another point-cut occurs when the thread leaves the method.

   Aspect

The combination of point-cut and advice is called aspect. In the following example, we add a log (logging) aspect by defining a point-cut and giving the appropriate advice.

AOP also has many other features and terminology, such as introduction (Introduction), which introduces interfaces/methods/domains to existing classes-which greatly broadens the imagination of developers. However, this article only introduces some of the most basic features, familiar with the concepts introduced here, you go into the other characteristics of AOP, and see how to use them in your development environment.

  Iii. Existing Framework

The most mature, functionally rich AOP framework of the time ASPECTJ,ASPECTJ has become the standard for most other frameworks to follow. However, ASPECTJ has also come out of an extraordinary step, and its implementation adds new keywords to the Java language. Although the new syntax is not difficult to learn, it means that we have to change a compiler and reconfigure the editor to accommodate the new syntax. In larger development groups, these requirements may be difficult to do because the entire development team will be affected. As the language itself changes, the learning cycle of the development team's introduction of AOP technology to existing projects has been extended.

What we need now is a framework that can be introduced easily and will not have any impact on the original development and construction process. There are more than one framework to meet these requirements, such as JBoss AOP, Nanning, Aspectwerkz (AW). This article uses Aspectwerkz because it is probably the easiest frame to learn, and the easiest to integrate into an existing project.

Created by Jonas Boner and Alexandre Vasseur, Aspectwerkz is one of the fastest and most powerful frameworks at the moment. Although it lacks some of the features of ASPECTJ, it is sufficient to meet the needs of most developers in many situations.

One of the most interesting features of Aspectwerkz is its ability to run in two different modes: Online mode and offline mode. In online mode, AW directly interferes with the underlying class loading mechanism belonging to the JVM, intercepts all class mount requests, and implements instant conversion of bytecode. AW provides a number of options for intervening in the class loading process, plus a wrapper script that replaces the Bin/java command, which automatically generates a set of operational formulations based on the Java version and JVM capabilities. For developers, online mode has many advantages, it can insert into any class loader and generate new classes during class loading. That is, we don't have to manually modify the application's classes, as long as they are deployed in the usual way. However, the online model requires an additional configuration of the application server, which may sometimes be difficult to satisfy.

In offline mode, the build class requires two steps. The first step is to compile with a standard compiler, and the second is to focus-run the Awcompiler compiler in offline mode to handle the newly generated classes. The compiler modifies the bytecode of these classes, inserting advice in the appropriate point-cut, based on the definition of an XML file. The advantage of offline mode is that Awcompiler generated classes can run on any JVM above 1.3, and this is the pattern that is used here, because it does not require any modification to tomcat, and can be copied to most existing projects as long as the construction process is modified slightly.

  IV. Installation

This article will take the example of a simple Web application that is compiled with Ant and deployed on the Tomcat 4+ servlet container. Let's assume that the reader is ready for the above environment, including JVM 1.3+, and Tomcat is set to automatically deploy the application from the WebApps folder and automatically extend the war to the directory (this is the tomcat default operation, so as long as you haven't modified how Tomcat works, The following example can be run directly). We will refer to the installation location of TOMCAT as%tomcat_home%.

⑴ Download the Aspectwerkz from the http://apectwerkz.codehaus.org/and unzip it to the appropriate location. We will refer to this position as%aspectwerkz_home%.

⑵ sets the%aspectwerkz_home% environment variable.

⑶ adds Aspectwerkz to the PATH environment variable, setting set Path=%path%;%aspectwerkz_home%inaspectwerkz

⑷ Download the demo program in this article and put it into the%tomcat_home%webapps folder.

⑸ adds the Aspectwerkz Run-time class to Tomcat's classpath. You can put its jar file into the Web-inflib folder of the sample application, or put it into the%tomcat_home%commonlib.

v. Compiling example application

If you want to delve into the example application of this article, you can undo the war file to extract its contents. You will find a aspectwerkz.xml file under the root directory, and it will be copied to the Web-inf/classes directory when the application is constructed. The servlet and advice source files are in the WEB-INF/SRC directory, and there is also an ant script to build these classes.

Before running this sample program, you will have to compile it later. The following steps are specific:

⑴ in the Command Line window, go to the directory that unlocks the war file.

⑵ enter the following command to invoke the AW compiler: Aspectwerkz-offline aspectwerkz.xml web-inf/classes-cp%tomcat_home%commonlibservlet.jar. If the post compilation goes through, you should see the following output:

(1 s)

Success:web-infclasses

There is an ant task called war in the build file that you can use to recreate the war file.

  Vi. Running the example application

Start (or restart) Tomcat first, and then open http://localhost:8080/demo/in the browser.

When the page is open, you can see an HTML form with two input boxes, one input name, one input email address. Enter some data, then click the button to submit the form, and a page appears showing the contact information and a link to the contact list.

  Seven, Code Analysis

JSP page is not analyzed, now we are not interested in it. Let's look at the Aopservlet code.

package example;

Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
public class Aopservlet extends HttpServlet {
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
person who = new person ();
if (Request.getparameter ("name")!= null) {
Person.setname (
Request.getparameter ("name"));
}
if (Request.getparameter ("email")!= null) {
Person.setemail (
Request.getparameter ("email"));
}
Request.setattribute ("person", person);
RequestDispatcher Rd =request.getrequestdispatcher ("/view.jsp");
Rd.forward (request, response);
}
}

In this example, the servlet's code is as concise as possible, containing only some essential code, such as an object that creates a binding request parameter, but no persistence, no additional imports, and it only implements the most basic operation that the servlet must implement.

However, as required by the documentation, the application must have the object of all person types to be aspect, so add one to the application. To create this aspect, we first create a aspectwerkz.xml file and place the file in the classpath specified directory. The example in this article provides a simple example that you can use to open the view with the editor.

The first part of Aspectwerkz.xml defines the available advice, and we can add any number of advice as needed:

In this fragment, we define a advice called persist, which is of type example. Persistenceadvice. The last attribute defines the advice of the property, where its value is PERJVM, which means that only one instance of the advice is created in each JVM (for more information on deployment patterns, see Aspectwerkz documentation.)

The second part begins to define aspect, which is where we map advice to Point-cut to create aspect.


pattern= "* Example.*servlet.doget (..)" />



Let's analyze this code in one line and one line at a time:

⑴ we created a aspect called a servlet. If necessary, we can create any number of aspect.

⑵ in the second line, we created a point-cut called All, which applies only to methods (type= "method").

⑶ Third line We use a regular expression to specify where to apply the advice. In this example, we point out that the application of the advice condition is that regardless of the type of return value (the first "*"), the name ends with a servlet (*servlet) and contains a Doget method with arbitrary parameters (Doget (..) ) The example package inside the class.

⑷ in line fourth, we told the Aspectwerkz compiler to apply the following advice to all point-cut.

⑸ Here we declare that the advice to be used is persist.

Now that we know how to map point-cut and advice to create a aspect, let's look at an instance of a class that provides a advice. In the mapping file, we registered a example. Persistenceadvice type of advice, the following is the type of source code:

package example;

Import javax.servlet.http.*;
Import org.codehaus.aspectwerkz.advice.*;
Import org.codehaus.aspectwerkz.joinpoint.*;

public class Persistenceadvice extends Aroundadvice {
Public Persistenceadvice () {
Super ();
}
Public Object Execute (final joinpoint joinpoint)
Throws Throwable {
Methodjoinpoint JP = (methodjoinpoint) joinpoint;
Final Object result = Joinpoint.proceed ();
object[] Parameters = Jp.getparameters ();
if (Parameters[0] instanceof HttpServletRequest) {
HttpServletRequest request = (httpservletrequest) parameters[0];
if (Request.getattribute ("person")!= null) {
Person contacts = (person) request.getattribute ("person");
Contactmanager persistent = new Contactmanager ();
String FileName = (Request.getrealpath ("/") + "Contacts.txt");
Persistent.save (contact, fileName);
}
}
return result;
}
}


The first line of the Execute () method is easy to understand, that is, try to shape it to the most specific type, and the second row is perhaps the most important: because we want to run the method and examine the result, we must call proceed (). In the next part, we capture the HttpServletRequest and extract the objects that were put in by the servlet (remember that the Doget () method is already running at the end).

Finally, we create a class called Contactmanager, which has the function of saving the person's data to a text file. In fact, it is also convenient to save data to an XML file, database, or other persistent storage mechanism.

One thing to grasp here is that in the design application or prototyping phase, the servlet does not know what will happen in the future, the second phase of the function can be added at any time, because of this, so we say that the application can learn new capabilities in the development process, later to add new features is very convenient.

"Closing" We experimented with a simple application in the previous example, deploying it to Tomcat and running and testing its functionality in a browser. Although the application itself does not have any practical use, it demonstrates and confirms some very useful concepts. Imagine that you will be able to build prototypes quickly and then introduce cross-cutting concern such as security, logging, persistence, buffering, and so on. Regardless of the size of the original application, you will be able to easily add log functionality to the entire application within 10 minutes!

Hopefully you'll be able to go beyond the simple example of this article to see how you can use AOP techniques in your own projects. It certainly takes a while to familiarize yourself with the concept of AOP, but it will certainly be rewarded for a medium sized project that will save you weeks or less than thousands of lines of duplicate code.

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.