JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Java Database Application with Apache Velocity

April 1, 2011 by Krishna Srinivasan Leave a Comment

Java Database Application with Apache Velocity

Introduction to Apache Velocity

Please Refer the article Spring with Apache Velocity

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

Introduction to JDBC

JDBC stands for Java DataBase Connectivity. The JDBC API helps us to develop Java applications with data base connection. We can use any database like Oracle,MySql,MSAcess etc..

For developing JDBC Applications we have to depend many APIs from the package java.sql. There are certain steps to do this.

The steps are:

  1. Loads a DriverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”)
  2. Connects to the databaseConnection con = DriverManager.getConnection(“jdbc:odbc:dsn”, “username”, “password”)
  3. Executes SQLStatement statmt = con.createStatement( );

    ResultSet rs = statmt.executeQuery(“SELECT * FROM ProductTable”);

  4. Retrieves the resultswhile(rs.next( )) {

    System.out.println(rs.getString(“pid”))

Example :JDBC Application with Apache Velocity

The application is using a Java file to retrieve the data from the database and the output is rendering with the help of a Velocity page.The java file uses an Arraylist to store the data from the resultset and the data is then add to the Velocity Context.Later the data is retrieving from the VelocityContext in the file Extract .vm page. The Database used in this example is Apache Derby.The below list contains all the related files and library details.

The files are :

[code]JDBCVelocityDemo.java
Extract.vm(Velocity file)
Derby database table Product with the fields product_ID,purchase_cost,..
Libraries: velocity-tools-view-1.4.jar ,velocity-dep-1.5.jar, velocity-tools-view-1.4.jar,derby.jar
Editor support :Netbeans 6.5 or above or any other java editor [/code]

JDBCVelocityDemo.java

[code lang=”java”]/**
*
* @author Rasmi_G
*/
import java.io.StringWriter;
import java.io.Writer;
import java.sql.*;
import java.util.*;
import org.apache.velocity.*;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
public class JDBCVelocityDemo {
static HashMap map;
public static void main(String[] args) throws Exception {
VelocityEngine ve = new VelocityEngine();
ve.init();
try {
//Derby database url
String url= "jdbc:derby://localhost:1527/sample";
//Database connection details with the username and password
Connection conn = DriverManager.getConnection(url,"app","app");
Statement stmt = conn.createStatement();
ResultSet rs;
//the product is table in the Derby Sample database
rs = stmt.executeQuery("SELECT * FROM PRODUCT");
String id ;
String cost1;
ArrayList list = new ArrayList();
//Retrieving the data and storing into a List in the form of map
while ( rs.next() ) {
map = new HashMap();
id = rs.getString("product_ID");
cost1=rs.getString("PURCHASE_COST");
map.put("Pid", id);
map.put("cost",cost1); }
list.add(map);
int count=list.size();
ArrayList l=new ArrayList();
l.add(list.get(count-1));
//For Loading the velocity page
Properties p = new Properties();
//loading the template engine path
p.setProperty("file.resource.loader.path", "D:/Learning Materials/2010-2011/AllDemoWorkFolder/Test11/src/java");
//Storing the data in the Velocity Context
VelocityContext context = new VelocityContext();
context.put("prdList", l);
//Initialize velocity run time engine through method init()
Velocity.init(p);
Template t = Velocity.getTemplate("Extract.vm");
StringWriter writer = new StringWriter();
//merge() is a method of the Template class.
//The usage of merge() is for merging the VelocityContext class object to produce the output.
t.merge(context, writer);
System.out.println(writer.toString());
}
conn.close();
catch (Exception e) {System.err.println("Exception");
System.err.println(e.getMessage());
}
}
}[/code]

Extract.vm

[code]The Details Are:
#foreach( $prd in $prdList )
Product id: $prd.Pid
Purchase Cost: $prd.cost
#end[/code]

After developing this application

  1. Start the Derby Database Server
  2. Compile and execute the JDBCVelocityDemo.java
  3. The contents in the Extrac.vm will display as the output.

The output :

[code]The Details Are:

Product id: 980001
Purchase Cost: 1095.00

The Details Are:

Product id: 980005
Purchase Cost: 11500.99

The Details Are:

Product id: 980025
Purchase Cost: 2095.99
[/code]

Conclusion

The article gives an introduction to JDBC and Apache Velocity .It contains a JDBC example which uses Apache velocity template engine for displaying the output page. Also this article gives an idea about how to develop this example and required libraries needed for this application.

Filed Under: Java Tagged With: Apache Velocity, Java

Spring with Apache Velocity

March 9, 2011 by Krishna Srinivasan Leave a Comment

Introduction

Spring is an open source framework, created by Rod Johnson. We can develop many kinds of applications using Springwhich includes basic java programs and enterprise applications. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling. Spring supports integration with Struts, WebWork, Apache velocity , Hibernate, JDO, TopLink, EJB, RMI, JNDI, JMS, Web Services, etc. This article assumes that readers has the sufficient knowledge on Spring Framework. If you are beginner looking for basic concepts on Spring Framework, please read Introduction to Spring Framework.

also read:

  • Spring Tutorials
  • Spring 4 Tutorials
  • Spring Interview Questions

Apache Velocity is a Java Template Engine which is one of the Jakarta projects . Templates are processed and but they are not compiled. It is ASF-licensed s/w. Velocity is a good alternate to Java Server Pages (JSPs) and is used to generate web pages, Java source code and other output from templates. It is useful for generating source code and reports. We can integrate Velocity as a view with Struts 2.0 , Spring frameworks etc. It supports better separation of code and design ,no compilation into Java code and also there is no embedded Java code. For details please visit http://velocity.apache.org/.

Spring’s Web MVC Framework

Spring Web MVC framework is to develop Spring Web applications and also it allows integration with other Web MVC frameworks and different View technologies like Velocity , Freemarker,etc. Spring MVC is based on DispatcherServlet that receives requests and delegates to the appropriate controllers. For details please visit http://www.springsource.com.

Apache Velocity

Apache Velocity Velocity is 100% Pure Java based template language .We can run Velocity on Java 1.3 or above versions. Apache Velocity current release is 1.7.
When compares with JSP, Velocity is easy to test, also no need of a Servlet container.It supports better separation of code and design ,no compilation into Java code and also there is no embedded Java code.

Velocity Language Elements are:
Statements,Directives,References,Comments

Sample code :

[code lang=”html”]
<html><body>
##This is a Velocity Application

<br>
#set( $message = " Hello World " )
$message

</body>
</html>
[/code]

The above example will give the output HelloWorld

In the above example :

##This is a Velocity Application is a comment.

#set( $message = ” Hello World ” ) is a statement

set is a directive

$message is a reference

Spring integration with Velocity

Spring supports the separation of view technologies from the rest of the MVC framework. For example we can use Velocity or XSLT in the place of JSPs. For this kind of integration with other views we need to configure for ViewResolver in Spring-servlet.xml file.
The view resolver for JSP is InternalResourceViewResolver. Incase of velocity we have to configure with org.springframework.web.servlet.view.velocity.VelocityViewResolver.

The software tools required for this example are as below:

  • NetBeansEditor 6.9.1,JDK1.6
  • Spring MVC jars
  • velocity-tools-view-1.4.jar ,velocity-dep-1.5.jar, velocity-tools-view-1.4.jar

The below example demonstrates how to use the velocity as the output view in a Spring Application. This is developed as a Netbeans Webapplication Project and it contains the files Input.jsp ,Result.vm, SumController.java,dispatcher-servlet.xml,web.xml.When we executes this spring application the Input.jsp will load .

This application is a Sum webapplication ,which can calculate the sum of two integer numbers and the output is dipalying using a velocity.The configurations of Spring MVC and Velocity integration is present in the dispatcher-servlet.xml.The sumcontroller class is the actual controller class,which contains the the model and view.In this example , the model logic is for finding the sum of two numbers and the view page is Result.vm.Also we need to add all the necessary libraries for this application.The details about the libraries are already present in the article .

Input.jsp

[code lang=”html”]
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
<head>

</head>

<body bgcolor="yellow">
<h1><b> Sum Application</b></h1>
<hr>
<br>

Please Enter the Input
<br>

<form action="sum.htm">
<table>
<b> <tr><td>First no: </td><td> <input type="text" name="no1"/></td></tr></b>
<br><br>
<b><tr> <td>Second no: </td><td><input type="text" name="no2"/></td></tr></b>
<br></table>
<input type="submit" value="SUM"/>
</form>
</body>
</html>

[/code]

Result.vm

[code lang=”html”]
<html>
<head>
<title>Output Page</title>
</head>
<body bgcolor="pink">
<h1><B> <center> The OutPut is: </center></B></h1>

<big> <center> ${sum}</center></big>
</body>
</html>
[/jaa]

<strong>dispatcher-servlet.xml</strong>

[code lang="xml"]
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="urlMapping">

<property name="mappings">
<props>

sumController</prop>
</props>
</property>
</bean>

<bean id="sumController" />
<bean id="velocityConfig"
>

<property name="resourceLoaderPath" value="/"/>

</bean>

<bean id="viewResolver"

p:prefix="/WEB-INF/rasmi-jsp/"
p:suffix=".vm" />

</beans>
[/code]

SumController.vm

[code lang=”java”]import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class SumController extends AbstractController {

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest requs, HttpServletResponse repns) throws Exception {
int n1=Integer.parseInt(requs.getParameter("no1"));
int n2=Integer.parseInt(requs.getParameter("no2"));
int s1=0;
s1=n1+n2;

return new ModelAndView("Result", "sum", s1);
}
}[/code]

web.xml

[code lang=”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">

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>Input.jsp</welcome-file>
</welcome-file-list>
</web-app>
[/code]

Exceute the application in any browser

Output

Conclusion

This article gives the basic idea about Spring framework and Apache Velocity .It contains an example which is a Spring Webapplication,which is for finding the sum of two integer numbers .All the necessary files and other informations for developing this example is specified in the article.The main idea of this example is how to do the integration of Apache Velocity and Spring.The dispatcher-servlet.xml contains all the necessary configurations for ViewResolver and VelocityConfigurer. I think this article will help you for developing similar kinds of examples in spring.

also read:

  • Spring Books
  • Introduction to Spring Framework
  • Introduction to Spring MVC Framework

If you have any questions on the spring framework  please post it in the comments section. Also search in our website to find lot of other interesting articles related to the spring framework. There are some interesting articles about spring framework, interview questions, spring and hibernate integration,etc.
If you would like to receive the future java articles from our website, please subscribe here.

Filed Under: Spring Framework Tagged With: Apache Velocity, Spring MVC

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved