Beginning Apache Velocity : Creating A Simple Web Application
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); } } }
And the most important part is web.xml
<?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?
29 Comments
ashwin
about 9 years agoHTTP 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.
Replyedwin
about 9 years agoHi ashwin, could you please paste here your complete error stacktrace so i could help you.
Mukund
about 9 years agoI think you don't have servelt-api.jar in your lib.
edwin
about 9 years agoHi Mukund, Servlet-Api.jar is in my tomcat lib folder, so i dont have to include it on my project :)
Mr.Tik
about 9 years agoI 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.
Replyedwin
about 9 years agoHi 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
Markku
about 9 years agoYou 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.
edwin
about 9 years agoYes Markku, i wrote "// other setter - getter" on the bean class to make my code looks shorter. Im sorry if it a little bit misleading :)
ray
about 9 years agoHi 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!
Replyedwin
about 9 years agoHi Ray, it's actually not too hard, let me write in on this weekend if i have some spare time. Thank you :D
ray
about 9 years agoEdwin, 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!!
Replyray
about 9 years agoEdwin 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!!!
ReplyOkashi
about 9 years agoIt 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. ;-)
Replyaoaoxiong
about 9 years agoIt works, Ths.
ReplyDZ
about 8 years agovery useful,thx
Replyedwin
about 8 years agoThanks DZ for your comment :D
Gene
about 8 years agoHi, 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
Replyedwin
about 8 years agoHi Gene, thank you for your comment. I hope it would help others too.
Nikolay
about 7 years agoMe too! Thanks for advance of this tutorial!
edwin
about 7 years agoHi Nikolay, glad it can helped.
mk.chan
about 8 years agoIf 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.
Replyedwin
about 8 years agohi mk.chan try putting under your WEB-INF folder, and call your vm file by using [code]request.getRequestDispatcher("/WEB-INF/index.vm");[/code]
Nikolay
about 7 years agoThanks of a magic way for velocity binding! Its works, but HOW?
Replyedwin
about 7 years agowell, there arent so many magics actually, only simple RequestDispatcher to forward your request. You could also use jsp to try.
Selami Ozlu
about 7 years agoan easy and simple sample for Velocity for the beginners, thanks, Selami Ozlu
Replyedwin
about 7 years agoThank you Selami, glad it can help
Koray Tugay
about 6 years agoGreat example, thanks..
ReplyRahul
about 5 years agoJun 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
Replyedwin
about 5 years agoyou need to create index.vm first.