Today im going to try create a simple web application using Apache Velocity. From what is written on its wiki, Apache Velocty is a simple yet powerful Java-based template engine that renders data from plain Java objects to text, xml, email, SQL, Post Script, HTML etc. The template syntax and rendering engine are both easy to understand and quick to learn and implement.
In this example i’m using Velocity 1.7 and Velocity Tools View 2.0, Netbeans 6.9 and Apache Tomcat 6. Im using a simple Servlet acting as Controller, Velocity file with extension .vm as View and a simple ArrayList to mimic ResultSets as the Model.
Lets start with a simple Velocity file
<html> <head> <title>Hello Velocity</title> </head> <body> <h1>Hello World..!!</h1> <br /> ## this is a comment, set variable name with "Edw" value #set( $name = "Edw" ) <h2> $name is using velocity</h2> ## if-else statement #if($name.equals("NotEdw")) <br /> not an Edw #else <br /> Only the Paranoid Survive #end <br /> <br /> <table> <tr> <td>Name</td> <td>Address</td> <tr> ## for each statement to iterate over a collection #foreach($user in $users) <tr> <td>$user.name</td> <td>$user.address</td> <tr> #end </table> ## simple velocity method Today is : $date.medium </body> </html>
i named it index.vm and put it under the Web Pages folder.
Next is creating an xml file, toolbox.xml for registering classes that is needed by Velocity. In this example im only registering a simple DateTool class.
<toolbox> <tool> <key>date</key> <scope>application</scope> <class>org.apache.velocity.tools.generic.DateTool</class> </tool> </toolbox>
Next is a simple javabean
package com.edw.bean; public class User { private String name; private String address; public User() { } public User(String name, String address) { this.name = name; this.address = address; } // other setter - getter }
And a simple Servlet, im using it simply just for Controller function, it forward my requests-responses to index.vm
package com.edw.servlet; import com.edw.bean.User; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; public class VelocityServlet extends HttpServlet { private Logger logger = Logger.getLogger(getClass()); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // simulate a database query List<User> users = new ArrayList<User>(); for (int i = 0; i < 5; i++) { User user = new User("name "+i, "Address "+i); users.add(user); } // set values request.setAttribute("users", users); // get UI RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.vm"); requestDispatcher.forward(request, response); } catch(Exception ex){ logger.error(ex); } } } [/code] And the most important part is web.xml [code language="xml" highlight="10,20,25"] <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- register servlet --> <servlet> <servlet-name>ServletVelocity</servlet-name> <servlet-class>com.edw.servlet.VelocityServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletVelocity</servlet-name> <url-pattern>/velocity.service</url-pattern> </servlet-mapping> <!-- mapping all .vm files to velocity servlets --> <servlet> <servlet-name>velocity</servlet-name> <servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet</servlet-class> <!-- load my toolbox --> <init-param> <param-name>org.apache.velocity.toolbox</param-name> <param-value>/WEB-INF/toolbox.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>velocity</servlet-name> <url-pattern>*.vm</url-pattern> </servlet-mapping> <!-- session timeout --> <session-config> <session-timeout> 30 </session-timeout> </session-config> <!-- welcome file --> <welcome-file-list> <welcome-file>velocity.service</welcome-file> </welcome-file-list> </web-app>
This is my Netbeans project structure
And this is what my browser displayed
In case of anybody asked about my log4j.properties, here is my configuration
# Global logging configuration log4j.rootLogger=DEBUG,stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p %c:%L - %m%n
Well it’s not too difficult isn’t it? (H)
HTTP Status 503 – Servlet velocity is currently unavailable
Hi, thanks for sharing the cncepts, But im getting this exception on trying to load the application in browser. Please tell me the resolutions.
Hi ashwin,
could you please paste here your complete error stacktrace so i could help you.
I think you don’t have servelt-api.jar in your lib.
Hi Mukund,
Servlet-Api.jar is in my tomcat lib folder, so i dont have to include it on my project 🙂
I am getting this error while using your code. Can you help?
Mar 28, 2012 4:39:48 PM org.apache.catalina.core.ApplicationContext log
INFO: Velocity [debug] Null reference [template ‘/index.vm’, line 32, column 9] : $user.name cannot be resolved.
Mar 28, 2012 4:39:48 PM org.apache.catalina.core.ApplicationContext log
INFO: Velocity [debug] Null reference [template ‘/index.vm’, line 33, column 9] : $user.address cannot be resolved.
Hi Mr.Tik, looks like you are not sending bean user to velocity template.
could you please share your sourcecode so i could help you more?
thanks
You should write public getters and setters to the User.java bean:
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
That is what helped me at least.
Yes Markku,
i wrote “// other setter – getter” on the bean class to make my code looks shorter.
Im sorry if it a little bit misleading 🙂
Hi there! Could you please do a tutorial on how to install Apache Velocity please, this tutorial looks so easy to follow, but I cannot figure out how to install Velocity 1.7.
Thank you!
Hi Ray,
it’s actually not too hard, let me write in on this weekend if i have some spare time. Thank you 😀
Edwin, if you could do that I would be forever grateful, I cannot explain how many hours I have spent trying to get a Velocity project set up in Eclipse, I am going insane.
I appreciate all your help Edwin!!
Thank you!!
Edwin can I just say I am using eclipse, velocity 1.7, velocity tools 2.0 and tomcat in eclipse, tom cat 7. I can create a new web app but I have no idea where to put files in the folders for velocity, I feel like I am so close!
Thanks!!!
It was really helpful dude, but u have forgotten to add the getters and setters in User.java, i got when i added them.. well it was really helpful. 😉
It works, Ths.
very useful,thx
Thanks DZ for your comment 😀
Hi, thank you for the good example. Being new to Velocity, the one challenge I had was figuring out which .jar files I needed.
In addition to the core Velocity download, I had to get the velocity-tools_2.0.zip as well (I know you mention it, but I didn’t realize it would be a separate bin download).
In that download are many jars, but here are the ones I needed to add (in addition to the core velocity .jar files) to make this example work in my environment:
velocity-tools-view-2.0.jar
commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-digester-1.8.jar
commons-logging-1.1.jar
Regards
Hi Gene, thank you for your comment.
I hope it would help others too.
Me too! Thanks for advance of this tutorial!
Hi Nikolay,
glad it can helped.
If it were in eclipse, where would you put the vm file? I put it under webpages (webcontent in eclipse) but it seems like they cannot locate it.
hi mk.chan
try putting under your WEB-INF folder, and call your vm file by using
Thanks of a magic way for velocity binding!
Its works, but HOW?
well, there arent so many magics actually, only simple RequestDispatcher to forward your request.
You could also use jsp to try.
an easy and simple sample for Velocity for the beginners, thanks, Selami Ozlu
Thank you Selami,
glad it can help
Great example, thanks..
Jun 08, 2016 10:25:03 AM org.apache.catalina.core.ApplicationContext log
INFO: Velocity [debug] Resource not found for path ‘/index.vm’ – org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource
Help me solve this error
you need to create index.vm first.