Use Stripes for Java Web Development

Source: Internet
Author: User

Stripes is an action-based open-source Java web framework designed based on simple and efficient web development guidelines for programmers. This article describes the differences between Stripes and other action-based frameworks such as Struts and the simplicity it provides in Ruby on Rails.

Stripes is an action-based open-source Java web framework designed based on simple and efficient web development guidelines for programmers. Traditional Java web development focuses on implementing its flexibility through Decoupling, but leads to the distribution of multiple configuration files, additional objects, and other resources. These difficulties have resulted in a considerable number of programmers having higher learning time and lower efficiency. The result is that some Java programmers are attracted by some non-Java frameworks: Ruby on Rails or Django. Some Java web frameworks, such as Stripes, are starting to learn their successful experiences from these non-Java frameworks: simple and efficient development. This article describes the differences between Stripes and other action-based frameworks such as Struts and the simplicity it provides in Ruby on Rails.
The process is basically an MVC framework. One major difference between Stripes and other action-based frameworks is that there is no external configuration file. We will see later that Stripes uses annotation and conventions instead of configuration to increase output and reduce clutter.

Write your first Stripe Action (Action)

Now let's start to understand the Stripes framework and understand its operation by creating a Hello World routine. The HelloWorldAction class prompts the user to enter the last name and display them in another View. First, we will compile the controller class.


Public class HelloWorldAction implements ActionBean
{
@ ValidateNestedProperties (
{
@ Validate (field = "firstName", required = true, on = {"hello "}),
@ Validate (field = "age", required = true, minvalue = 13, on = {"hello "})
})
Private Person person;
Private ActionBeanContext context;
@ DefaultHandler public Resolution index ()
{
Return new ForwardResolution ("Hello. jsp ");
}
Public Resolution hello ()
{
Return new ForwardResolution ("SayHello. jsp ");
}
Public void setPerson (String person) {this. person = person ;}
Public String getPerson () {return person ;}
Public void setContext (ActionBeanContext c) {this. context = c ;}
Public ActionBeanContext getContext () {return context ;}}

The Controller class is a POJO (Plain Old Java Object) that implements the ActionBean interface specific to Stripes ). All Stripes collections classes must implement this interface so that the StripesDispatcher servlet can inject an ActionBeanContext object to it when running the service. The ActionBeanContext object allows you to access servlet APIs such as request, response, and servlet context. Most of the time in the Stripes application, these underlying API objects are not read.

The ActionBeanContext class also provides the status of the current action and adds information messages and error messages to the current action. Variables of ActionBeanContext and their read/write methods can be placed in a base class, because all Stripes actions must be implemented.

Other parts of the Controller class are very familiar to any Java programmer. There is a Person object and its read/write method used to read and write the user's name to the view. Although this is just a simple nested object, Stripes can implement more complex and complete data bundling through Java collections, generic support, and subscript attributes. Because Stripes can handle complex data bundling, your Domain objects can be reused at other layers that require them. For example, through Stripes, you can easily collect information about a domain object, and then use other POJO frameworks such as Hibernate or EJB3 to persist it.

There is a Stripes verification annotation on the Person object variable to ensure that the user has entered a name when activating the hello method. If you do not enter these two required variables, the original page is returned and a related error message is displayed. This verification is activated only when the hello event is applied, because the annotation attribute specifies (on = {"hello "}). Stripes also uses the practical default rule to generate an error message based on the verification method and variable name. For example, if the firstName variable of the Person class is not provided at the time of submission, you will see:

Person First Name is a required field.

This message is obtained after the Person. firstName is engraved and read. If necessary, these error messages can be reloaded to provide more custom functions.

There is also an Integer variable age, which is an attribute of the Person object. Stripes first tries to convert the parameter whose life is person. age in the request to the Integer type and bind it to the Person object. After the age variable of the Person object is paid, Stripes verifies whether the Integer value is less than 13. If the user inputs a string rather than an integer, the user obtains the message:

The value (Mark) entered in field Person Age must be a valid number.

If the user inputs an integer smaller than 13, the user will see the message:

The minimum allowed value for Age is 13.

Similarly, we do not need to provide any external configuration files for these error messages. Annotation provides verification in the same location as your variables, making it easier for programmers to locate verification, understand verification content, and maintain changes to verification.

This Stripes action also has two activable methods (called events ). An event is a method with the following features in the ActionBean class:

Public Resolution eventName

Note that the index method is marked as @ DefaultHandler annotation. Because this action contains multiple events, one of which must be specified as the default event. If no event is specified for the URL that calls this action, Stripes searches for the event marked with @ DefaultHandler annotation and runs it.

View)

Now let's add the display layer logic to the Hello World routine. Stripes supports the standard technology of JSP as the display layer by default, but you can also use other display layer technologies, such as FreeMaker. There is nothing new to learn except the tag library of Stripes. Hello. jsp is the initial display, allowing users to enter and submit names.


<% @ Taglib prefix = "stripes" uri = "http://stripes.sourceforge.net/stripes.tld" %>
......
<Stripes: errors/>
<Stripes: form beanclass = "com. myco. web. stripes. action. example. HelloWorldAction"> Say hello t <br> First name:
<Stripes: text name = "person. firstName"/> <br> Age: <stripes: text name = "person. age"/> <br>
<Stripes: submit name = "hello" value = "Say Hello"/>
</Stripes: form>
......

This JSP is easy to read and maintain. The tag used by Stripes for form and input is very similar to the corresponding HTML code. Stripes: form tag contains a beanclass attribute whose value is the complete Class Name of the controller class we defined earlier. We can use the action attribute in stripes: form to replace the beanclass attribute. However, the beanclass attribute makes it easier for you to refactor the Stripes action in the future. If you want to use the action attribute in the stripes: form tag, the method is as follows:


<Stripes: form action = "/example/HelloWorld. action">

There is a stripes: input tag that specifies a property named person. firstName, which is used to pay the stored input value to the firstName variable of the Person object of the controller. Finally, the stripes: submit tag specifies a name attribute to tell the Stripes HelloWorldAction class which event to use.

Now we have submitted the name value to HelloWorldAction, and the rest is to feedback it to the user in another view.


<% @ Taglib prefix = "stripes" uri = "http://stripes.sourceforge.net/stripes.tld" %>
......
<Stripes: errors/>
<H2> Hello {actionBean. person. firstName} your age is {actionBean. person. age} <Stripes: link beanclass = "com. myco. web. stripes. action. example. HelloWorldAction"> Say Hello Again
</Stripes: link>
......

This JSP will read and display the person name information through a reference to the action. To achieve this goal, Stripes automatically adds an actionBean action object in the request attribute for JSTL access. Finally, we use a strips: link tag to create a link that returns HelloWorldAction, so that we can enter different names. We can explicitly create a stripes: link pointing to the index event using the following method:


<Stripes: link beanclass = "com. myco. web. stripes. action. example. HelloWorldAction" event = "index">
Say Hello Again
</Stripes: link>

Because we have used annotation to mark the index method as @ DefaultHandler, Stripes knows which method to execute without the event attribute.

Conventions, no configuration files

Now that we have the Java component, we should configure it, map the action to a URL, and connect it to our two views. Wait! We are using Stripes. We do not need an external configuration file!

Although it sounds like it is not true, it is indeed one of Stripes's most productive features. Stripes uses conventions instead of configuration files to map actions to URLs. We do not need to use an external configuration file to map views to tag names one by one. This means that programmers no longer need to jump in the configuration file to mark the actual source of the name-for example, SUCCESS. There is no need for wiring outside the Java and view components, resulting in better maintainability and productivity.

How does Stripes provide implicit URL ing without configuring every action or external annotation externally? This can be explained from the configuration of Stripes in web. xml and how it establishes URL ing through the practical default method. First, let's take a look at the Servlet filter: StripesFilter. Its default configuration in web. xml is as follows:

 

<Filter>
<Display-name> Stripes Filter </display-name>
<Filter-name> StripesFilter </filter-name>
<Filter-class> net. sourceforge. stripes. controller. StripesFilter </filter-class>
<Init-param>
<Param-name> ActionResolver. UrlFilters </param-name>
<Param-value>/WEB-INF/classes </param-value>
</Init-param>
</Filter>

When the Servlet container is started, StripesFilter initializes its init-param element. The most important init-param element is the ActionResolver. UrlFilters parameter. This parameter tells Stripes where to find the Stripes-related classes. In this example, Stripes will look for all classes under the/WEB-INF/classes directory that implement the ActionBean interface. Each found class and its bound URL will be added to a Map.

Let's take a look at how Stripes handles our HelloWorldAction action as an example. Because the HelloWorldAction class is located under the/WEB-INF/classes directory, it is considered a Stripes servlet. In our example, the complete class name is com. myco. web. stripes. action. example. HelloWorldAction. Then, the complete class name will be translated into a URL binding according to the following rules.

1. Delete the parts that contain www, web, stripes, and action and their previous content. In our example, there are three words above, so we get example. HelloWorldAction.

2. If the class name contains the tail with Action or Bean, delete it. Because our class name ends with Action, we get example. HelloWorld.

3. Replace. With/, we get example/HelloWorld.

4. Finally, add the last suffix (default:. action) to complete URL binding. The final result is example/HelloWorld. action.

Now Stripes finds the ActionBean Class and creates a URL binding for it, and stores it in a java. util. Map <String, Class <? Extends ActionBean>. The key parameter is URL binding, and the value parameter is the class name that implements ActionBean. Below is the Map in our example:

URL binding:/example/HelloWorld. action
ActionBean class: com. myco. web. stripes. action. example. HelloWorldAction

The second component we want to see is how Stripes translates URL binding into the ActionBean class you are working on. This is the role of the Stripes scheduling servlet. The configuration in web. xml is as follows:


<Servlet>
<Servlet-name> StripesDispatcher </servlet-name>
<Servlet-class>
Net. sourceforge. stripes. controller. DispatcherServlet </servlet-class>
<Load-on-startup> 1 </load-on-startup>
</Servlet>
<Servlet-mapping>
<Servlet-name> StripesDispatcher </servlet-name>
<Url-pattern> *. action </url-pattern>
</Servlet-mapping>

A role of StripesDispatcher is to resolve the URL to the ActionBean class of Stripes. When the user activates URL http: // host/uri/example/HelloWorld. during the action, the Stripes scheduling servlet will query and find com. myco. web. stripes. action. example. helloWorldAction class, and instantiate an instance that generates this class. Finally, the index method is activated because it is defined as the default handle in annotation and no event is specified in this URL.

What if we want to directly execute the hello method in HelloWorldAction? The event name should be put in the request parameter like the following URL:

Http: // host/uri/example/HelloWorld. action? Hello = & firstName = Mark & age = 13

Please note that no value is specified for the request Name hello. In this case, StripesDispatcher identifies and maps the request parameter hello and a function with the public Resolution hello () signature in the HelloWorldAction class. This method is cached in another Map for performance during initialization.

We have seen the basics of Stripes and the details about how the framework works if simple actions are created. Through initialization in web. xml, we can avoid using multiple separate XML configuration files to form our display layer. This is very important for the following reasons: first, if you need any changes, you can see a URL and immediately know which class you should check. Second, we don't need any separate tools to help you when your configuration file is too large and unmanageable. By eliminating the configuration file, we no longer need to allocate a lot of metadata to the framework. Finally, we no longer need to maintain each other for an independent component that is used to describe the files that are associated with each other for a moment.

Ajax

Do you want more advanced features? Let's take a look at how Stripes handles Ajax. We will change the previous Hello World routine to use Ajax to call the Stripes action. The source code of this example can be found in the resources in this article. First, modify Hello. jsp to reference the Prototype JavaScript function library. We also need to add a JavaScript function for Ajax calls and change the submit button to add an onclick event for it:


<% @ Taglib prefix = "stripes" uri = "http://stripes.sourceforge.net/stripes.tld" %>
......
<Script src = "{pageContext. request. contextPath}/js/prototype. js" type = "text/javascript">
</Script>
<Script type = "text/javascript">
Function sayHelloAjax (){
Var myAjax = new Ajax. updater ('hello', "<stripes: url beanclass =" com. myco. web. stripes. action. example. helloWorldAction "event =" sayHelloAjax "/>", {method: 'get', parameters: Form. serialize ('helloform ')});
}
</Script>
......
<Stripes: errors/>
<Stripes: form beanclass = "com. myco. web. stripes. action. example. HelloWorldAction" id = "helloForm">
Say hello t
<Br> First name:
<Stripes: text name = "person. firstName"/> <br>
Age: <stripes: text name = "person. age"/> <br>
<Stripes: button name = "helloAjax" value = "Say Hello" onclick = "sayHelloAjax ()"/>
<Div id = "hello"> </div>
</Stripes: form> ......

Stripes: the button has an onclick event that will call the sayHelloAjax method in the HelloWorldAction class and return the result to a div tag named hello. The following is a new method we will introduce in HelloWorldAction:


Public Resolution sayHelloAjax ()
{
Return new ForwardResolution ("SayHelloAjax. jsp ");
}

This method does not work much because Stripes has bound the name content. Therefore, the only responsibility of this method is to forward it to a page segment called SayHelloAjax. jsp. The content of this foliar fragment is as follows:


<H2> Hello {actionBean. person. firstName} your age is {actionBean. person. age }! </H2>

Spring Integration

Stripes also has built-in Spring support. You can automatically add Spring beans to your actions. According to the Stripes style, no external configuration file is required except for the Spring context configuration file. If our Spring configuration file is as follows:


<Bean id = "personService" parent = "abstractTxDefinition">
<Property name = "target">
<Bean class = "com. myco. service. impl. PersonServiceImpl"/>
</Property>
</Bean>

To inject the person service into a Stripes action, you must add a property consistent with the Spring bean name and setter. Stripes provides @ SpringBean annotation to query the correct Spring bean and inject it into the action. The following is an example to be included in the response class:


Private PersonService personService;
@ SpringBeanpublic void setBlogService (BlogService blogService)
{
This. blogService = blogService;
}

This article cannot cover all advanced features of Stripes. However, Stripes has very complete documentation. Stripes also contains a layout manager that is similar to Tiles but does not require an external configuration file. In addition, the interceptor can also be used for various aspects of lifecycle events, file uploads, and so on.

Conclusion

Stripes is a powerful and simple Java web framework. Stripes utilizes the annotation and generic functions of Java 5, so that Java programmers do not need to maintain external configuration files and increase productivity. Stripes can simplify difficult web development and make simple work easier!
 

Related Article

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.