Struts and velocity integrate five steps to replace JSP

Source: Internet
Author: User
Tags abstract config contains end html page key version access
JS Struts Recipes's co-author George Franciscus takes you step-by-step through integrating the Velocity template engine into the Struts application. The result is a fast, flexible JSP replacement with all the conveniences you can expect from Struts.
  
Java? Server Page (JSP) technology is so pervasive that people forget that there are other options when creating Web pages. But recently, some developers have turned to the template engine to gain flexibility in JSP. Although you can embed data into HTML using both the JSP and the template engine, each technique has its own way of dealing with it. The Velocity profile is a particularly popular JSP alternative. Velocity provides a gentle learning curve and great ease of use. Developers like its concise syntax, and performance analysis also proves that its performance is beyond the JSP. Velocity is also very easy to integrate into the Struts application.
  
In this article, I'll explain how to integrate and use the Velocity template engine in a Struts application. I will first provide a formula and then expand it gradually. The generated applications combine Struts and Velocity?? A first-class combination, may let you doubt oneself to the JSP loyalty!
  
Download the source code for this article before you start, as well as the Struts, velocity, and velocity kits. Please note that this article assumes that you are familiar with using the Struts framework for MVC programming.
  
   about the template engine
  
Before starting the simple task of integrating Struts and Velocity, let's make sure that you understand the template engine and their role in view generation. The template engine as a whole concept, Velocity as a concrete implementation, their lives outside the HTML. Velocity merges the data into different points in the text body. Text can be text, e-mail, or HTML. Because of this approach, the Velocity template engine is a bit like the mail merge feature of Microsoft Word. Mail merge allows you to easily merge dynamic data, such as names, addresses, and phone numbers, into a letter. In the early days, the organization used this feature to generate large mailing lists and send them to the post office, resulting in spam messages!
  
   What is Velocity?
  
Velocity is a java-based template engine that provides a simple template-based language that can refer to objects in a script-like manner. Velocity facilitates the separation of responsibility among team members: allowing WEB designers to focus on the view (that is, the perception of the page), while Java programmers focus on back-end code. Separating Java code from the page layout makes WEB applications easier to maintain in the future. When Velocity is combined with an MVC framework such as sruts, it becomes a viable alternative to JSP or PHP.
  
In a WEB application, Velocity achieves the same goal as a JSP: it can be used to generate the HTML to be sent before it is sent to the HttpServletResponse OutputStream. One way to use Velocity in a struts application is to write a response inside a struts Action, and then return null Actionforward. While this technique works, it has a serious flaw: the inability to use Struts-config.xml files to abstract responses. Putting the view inside the action means that if you want to modify the response, you must modify the action.
  
Because this technology deprives the best feature of Struts (the ability to abstract the focus from the view), I prefer to point all responses to a servlet, which is responsible for accessing the Velocity template, merging context data, generating a response, and then sending it back to the browser. As you'll learn later, Velocity designers have bundled these steps together: all you have to do is follow me to see how to implement them step-by-step. If you have not yet visited the "Downloads" section, now is the time to visit.
  
   Velocity of five steps
  
Combining Struts with the Velocity template engine is simple and straightforward; in fact, it takes five steps to achieve:
  
1. Place the Velocity JAR in the classpath.
  
2. Modify the Web.xml file so it recognizes the Velocity servlet.
  
3. Place Velocity Toolbox.xml in the Web-inf directory of the application.
  
4. Modify the Struts-config and point its view to the Velocity template instead of the JSP.
  
5. Create a Velocity template for each page that needs to be displayed.
  
I'll demonstrate the integration of Struts and Velocity with a familiar search case. In this example, a simple application allows the user to search for books according to the ISBN number of the book. The results page of the application displays a book that matches the ISBN number.
  
Step 1th: Put the Velocity JAR under the Web-inf/lib.
  
   give up the Struts flag?
  
Now, you might wonder if you need to give up the good Struts tags that used to save you a lot of coding time. If you don't use JSP, then you definitely don't use the JSP tag for Struts! Fortunately, you can use the Velocity tool. Velocity's Struts tool provides all of the familiar struts convenience features, but adds velocity flexibility.
  
If you haven't yet downloaded Velocity, then you need to download it now. Velocity itself is great, but its toolkit can help you do your job better and faster. In particular, the struts tool simulates the struts tag that you used to know. See download the velocity template engine and velocity tool in the downloads section.
  
Note that different times require a slightly different jar. I don't want to make a list of jars here, I just want to suggest that you visit the Velocity's home page (see Resources) and read the installation guide there. Once you've got the jars you need, just put them under the web-inf\lib.
  
Step 2nd: Modify the Web.xml to identify the Velocity servlet
  
The next step is to modify Struts's Web.xml file to identify the velocity servlet and direct all resource requests ending with the. VM to the Velocity servlet, as shown in Listing 1.
  
Listing 1. Modify Web.xml, declaring Velocity servlet
  
<servlet>
<servlet-name>velocity</servlet-name> | (1)
<servlet-class> | (2)
Org.apache.velocity.tools.view.servlet.VelocityViewServlet
</servlet-class>
  
<init-param> | (3)
<param-name>org.apache.velocity.toolbox</param-name>
<param-value>/WEB-INFtoolbox.xml</param-value>
</init-param>
  
<load-on-startup>10</load-on-startup> | (4)
</servlet>
  
<!--Map *.vm files to Velocity-->
<servlet-mapping> | (5)
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
  
Let's take a look at what's going on in Listing 1:
  
(1) declared the velocity servlet and gave it a velocity handle.
  
(2) The class name of the Velocity servlet is declared.
  
The Velocity Servlet accepts the "toolbox" parameter. Toolbox is where you declare the available tools for your application. So, in Listing 1, I did the following work:
  
(3) Tell Velocityservlet where to find the Toolbox configuration.
  
(4) Set the Load-on-startup tag to ensure that the Velocity servlet is loaded at the correct time. Any value greater than or equal to 0 forces the container to mount it by calling the Servlet's init () method. The value placed in the Load-on-startup tag body determines the order of the Init method calls of the different servlet. For example, 0 is called before 1, and 1 is called before 2. Missing tags or negative values allow the servlet container to mount the servlet according to its own selection.
  
(5) A servlet mapping is declared, forcing all resource requests ending with the. VM to be directed to the Velocity servlet. Please note that the <servlet-name> in (5) must match <servlet-name> in (1). Staggered declarations and mappings generate errors in the log.
  
3rd step: Put the toolbox.xml under the Web-inf
  
With Velocity, you can use (or create) a toolbox that contains many tools. The toolbox used to enlist a class contains useful functions that are often used. Fortunately, Velocity provides a number of pre-built tools. Many of the struts tools are also created to simulate the original struts tag. If you find that you need to build your own tools, you are free to build. The toolbox.xml shown in Listing 2 can be found in the Velocity tool download. This file should be placed under the Web-inf with the Velocity JAR.
  
Listing 2. Toolbox.xml
  
<?xml version= "1.0"?>
<toolbox>
<tool>
<key>link</key>
<scope>request</scope>
<class>
Org.apache.velocity.tools.struts.StrutsLinkTool
</class>
</tool>
<tool>
<key>msg</key>
<scope>request</scope>
<class>
Org.apache.velocity.tools.struts.MessageTool
</class>
</tool>
<tool>
<key>errors</key>
<scope>request</scope>
<class>
Org.apache.velocity.tools.struts.ErrorsTool
</class>
</tool>
<tool>
<key>form</key>
<scope>request</scope>
<class>
Org.apache.velocity.tools.struts.FormTool
</class>
</tool>
<tool>
<key>tiles</key>
<scope>request</scope>
<class>
Org.apache.velocity.tools.struts.TilesTool
</class>
</tool>
<tool>
<key>validator</key>
<scope>request</scope>
<class>
Org.apache.velocity.tools.struts.ValidatorTool
</class>
</tool>
</toolbox>
  
4th Step: Modify Struts-config
  
The next step is to modify the Struts-config.xml, pointing to the Velocity view rather than the JSP. The new configuration file is shown in Listing 3.
  
Listing 3. Modified Struts-config.xml for Velocity view
  
<?xml version= "1.0" encoding= "Iso-8859-1"?>
  
<! DOCTYPE Struts-config Public
"-//apache Software foundation//dtd Struts Configuration 1.0//en"
"Http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd" >
  
<struts-config>
<form-beans>
<form-bean name= "Searchform" type= "app. Searchform "/>
</form-beans>
  
<global-forwards>
<forward name= "Welcome" path= "/welcome.do"/>
</global-forwards>
  
<action-mappings>
<action
Path= "/welcome"
Type= "Org.apache.struts.actions.ForwardAction"
parameter= "/PAGES/SEARCH.VM"/> | (1)
  
<action
Path= "/search"
Type= "app. SearchAction "
Name= "Searchform"
Scope= "Request"
input= "/PAGES/SEARCH.VM" > | (2)
<forward name= "Success"
Path= "/PAGES/RESULTS.VM"/> | (3)
</action>
</action-mappings>
</struts-config>
  
Listing 3 looks like a very typical Struts application, only a small difference. The response does not shift the customer to the JSP, but directly to the. vm file (see References 1, 2, and 3 in Listing 3). In most cases, moving a Struts application from JSP to Velocity view requires just a global search to replace the. JSP with a. vm. Everything else can stay the same! The template can also be saved in a location where the JSP was previously saved; all you need to do is use the Velocity command instead of the JSP tag.
  
Step 5th: Create a Velocity template
  
In Listing 4, you can see the Velocity template for the sample application search page.
  
Listing 4. Velocity Template for Search page
  
<HTML>
<HEAD>
<TITLE>Search</TITLE>
</HEAD>
<BODY>
$!errors.msgs () | | (1)
<form method= "POST"
Action= "$link. Setaction ('/search ')" > | (2)
Isbn:<input type= "text" Name= "ISBN" >
<input type= "Submit" value= "submit" Name= "Submit" >
</FORM>
</BODY>
</HTML>
  
Listing 4 is a typical HTML page with no JSP or Struts tags. However, the following elements may not look familiar:
  
(1) Use $!ERRORS.MSGS () to get the error message in the error message queue.
  
(2) Use $link. Setaction ('/search ') to obtain the URL of the search forwarding.
  
This is a success?? The rest of the template looks almost the same as the previously familiar HTML file. Listing 5 shows the template for the application results page.
  
Listing 5. Velocity template for the resulting page
  
<body>
  
<a href= "$link. Setforward (" Searchentry ")" >search again</a> | (1)
  
  
<b>ISBN:</b> $book. isbn<br>| (3)
<b>Title:</b> $book. title<br>| (4)
<b>Author:</b> $book. author<br>| (5)
<b>Price:</b> $book. price<br>| (6)
<b>no pages:</b> $book. pages<br>| (7)
<b>Description:</b> $book. description<br>| (8)
<b>Publisher:</b> $book. publisher<br>| (9)
</body>
  
You can note that listing 5 does not include a JSP tag or a Struts tag. Let's take a look at it in detail:
  
(1) Use the link tool of struts to set the <a> Mark's href as struts forwarding.
  
(2) Access $book Title property.
  
(3) Access $book ISBN property.
  
(4) Access $book Title property again.
  
(5) Access $book Author property.
  
(6) Access $book Price property.
  
(7) Access $book pages property.
  
(8) Access $book Description property.
  
(9) Access $book Publisher properties.
  
   discussion
  
This is all the work of integrating Struts with the Velocity template engine. The surface looks very simple (and really simple), but just think about what makes this integration work?
  
Struts Action mappings can define any view, not limited to JSP. In this article, I just change the action map to a return file that ends with a VM rather than a JSP. I then declared the Velocity servlet and told the servlet container to send the file with the end of the VM to Velocityviewservlet.
  
Velocityviewservlet the Velocity command as an HTML response. In this way, Velocityviewservlet acts as an interceptor for the view response. The Struts controller transfers the view to Velocityviewservlet, which processes the VM files before sending a response to the client. See Resources for more information on integrating the Velocity view into the Struts application.
  
   Concluding remarks
  
As you can see in this article, the integration of Struts and Velocity is simple. It takes five steps to connect everything together. For different engines and scenarios, the advantages of using a template engine instead of a JSP are different. In the case of Velocity, the advantage is simplicity, ease of learning, and better performance.

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.