Saturday, January 29, 2011

Hibernate 3 and Servlet example

Now lets take an example of Hibernate ORM Framework. We will demonstrate the use of hibernate in our servlets. First let us go through the files which hibernate uses. hibernate.cfg.xml is the first file which contains all the information needed to connect to the database (database name, username, password, etc). The next group of xml files contain information regarding the persistent object to be saved. So each object has its own (mapping)file. In our case we will use the "User" object so it will be named user.hbm.xml .

The project structure that i use :

The Deployable structure :

So first we will create our User Model, lets name it . I have created a package in.codeconnect, so the java files will reside in src/in/codeconnect .

package in.codeconnect;

//User Model
public class User {
private int id;
private String name;
private String password;

//getters and setters
public int getId() {
return id;

public void setId(int id) { = id;
public String getName() {
return name;

public void setName(String name) { = name;

public String getPassword() {
return password;

public void setPassword(String password) {
this.password = password;

It is a simple class for User, having properties id,name,password with their respective getters and setters.

We need a database to store our objects. So we create a database ("application" in my case).
With a table having structure :

-name (VARCHAR)
-password (VARCHAR)
We will be using mysql database so we need jdbc mysql driver (a jar file), which has to be placed in tomcats lib or in the classpath.

Next we create hibernate.cfg.xml file (should be made available in classes directory) :


In above file you specify the uri to the mysql server of the format jdbc:mysql:// where application is the database name, the username and the password. = update will use the current database state as opposed to create which will recreate the structure resulting in loss of data every time you run ur application.

We will now create a mapping file user.hbm.xml which will reside in same directory as above file.

This file contains the mapping information for our objects (Property to Column). Refer to the id property map and you will see generator class "increment" assigned to it for auto increment even though it is not specified in the database.

Now its time to create our servlet HibernateTest to accept our requests. In that we initiate a hibernate session by loading the hibernate config. Next we create our user object and save it using the session. U may get an error related to transaction due to clash with java libs, in that case you need to download jta (jta.jar) library and place it in the classpath/lib. We also retrieve the saved entry from the database and display it.

package in.codeconnect;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateTest extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {


protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String password = request.getParameter("password");
Session session = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

User user = new User();

User userFromDb = (User) session.get(in.codeconnect.User.class,user.getId());
out.println(userFromDb.getName() + " " + userFromDb.getPassword());


We now create web.xml tomcat config file in the WEB-INF dir. The content are as follows :

Deploy the application, start the tomcat server and visit the url with params, and the entry should be added to the database.
eg : http://localhost:8080/HibernateTest?name=Jhonny&password=Bravo

Tuesday, December 14, 2010

Struts 2 example

Lets create a simple struts application that would involve a controller , a model and a view.
The following structure exists for my project :

I have downloaded the struts library and placed the jar files in lib. My codes are under src. The struts only configuration file lies in the src directory. My views are under web.

To get started we need to route our incoming requests to our struts dispatcher, we do it in our web.xml :

Once this is done, we can define our controller that will handle our requests. In my case i have named it MyController and contains :

import com.opensymphony.xwork2.ActionSupport;
public class MyController extends ActionSupport {
private User user;
public User getUser() {
return user;

public void setUser(User user) {
this.user = user;
public String execute() throws Exception {
this.user = new User();
return SUCCESS;

The above controller uses User model that i have defined in :

public class User {
private int id;
private String username;
private String password;

public int getId() {
return id;

public void setId(int id) { = id;

public String getUsername() {
return username;

public void setUsername(String username) {
this.username = username;

public String getPassword() {
return password;

public void setPassword(String password) {
this.password = password;

execute() is the method called when request comes to the controller. In MyController we initialize the User object and set its properties. We can also access this user object from jsp rendered by this controller, we'll c that later. Remember Object getters and setters are necessary for this to work. Controller can return different results, based on which it renders different views. For example if success is returned, required view can be rendered else if error is returned error page can be shown. We define all this in struts.xml that lies in my classspath :

In my case i have defined only one action showuser, which will route this request to MyController which will then return a result. In case of success index.jsp will be rendered, error.jsp otherwise.

Now lets show the user details which were initialized in MyController in our index.jsp :

This will print the user id, username, password on the screen when we try to access http://localhost/showuser

There is one more interesting thing to see over here, the auto wiring feature of struts. If we define Objects in the controller with its getter and setter and then pass the object as parameter in the url its value is automatically assigned to the object. For example if we add a String variable "message" in MyController and define setter and getter over it, we can use the url http://localhost/showuser?message=HelloWorld it will be printed on the page.

public class MyController extends ActionSupport {
private User user;
private String message;

public String getMessage() {
return message;

public void setMessage(String message) {
this.message = message;

Thursday, December 9, 2010

Struts 2, Spring 3, Hibernate - The Big Picture

Today, we will get a java web application running using these three master frameworks -> Struts, Spring and Hibernate. Each one has its own speciality, that overcome some of the drawbacks of the underlying platform.
Spring framework allows you to create and pass objects( java beans) at runtime using constructors or setters rather than doing it implicitly in the host class, the concept being known as Dependency Injection or Inversion of Control (IOC). This makes the classes independent, which indeed helps in testing. Spring also has other components but we wont use it here.
Struts provides a Model View Controller (MVC) framework. It helps in separating your logic from the view. The controllers handle the requests, the views generate output and model represents an entity.
Hibernate lets us save Persistence Java Objects/POJOs into the database and also retrieve them.
All these components have their own configuration xml files.

I will break up this topic into 4 parts, in 3 of them we will see how we can get these components running independently and at last using these into one application.


The IDE i prefer for java is IntelliJ Idea, so the initial project settings may differ based on the IDE you use.
Download Spring 3 Framework here
The structure of the application goes like this :

Extract the Spring archive to a folder, import the jar files in dist folder to the lib folder of your project and make sure they are added to the build path. Actually all files are not required, and in Spring you get the freedom to choose only the components you need. The jar file that i have included are : commons-logging, spring-web, spring-webmvc, spring-beans, spring-context, spring-core, spring-asm, spring-expression. commons-logging jar is needed and can be found in projects/spring-build/lib/ivy of the Spring framework extracted folder. Don't forget to include Java EE library.

The src folder will contain my source, within which i have defined a package in.codeconnect, my java files will go in here.
The web directory contains a sub directory 'pages' where i will keep my views/jsp files.
WEB-INF will contain 2 Spring configuration files : applicationContext.xml and dispatcher-servlet.xml and one server config file : web.xml.

I have created 2 classes in my package :
This is a simple class with getter and setter,that will contain my greeting message :

package in.codeconnect;

public class MessageClass {
private String message;

public String getMessage() {
return message;

public void setMessage(String message) {
this.message = message;

This is the Controller :

package in.codeconnect;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloWorldController implements Controller {
private MessageClass messageObject;

public MessageClass getMessageObject() {
return messageObject;

public void setMessageObject(MessageClass messageObject) {
this.messageObject = messageObject;

public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
ModelAndView modelAndView = new ModelAndView("pages/say_hello.jsp");
return modelAndView;

Note this class has a MessageClass object defined along with its getter and setter. handleRequest() is the function called when request comes to this contoller. Here we create a new view whose jsp is located in /pages with name say_hello.jsp. Then we add a variable that will contain our greeting message using addObject(), whose value will be equal to messageObject's message property.

Lets go through the configuration files.
web.xml is the main file and this is how it will look :

It states that any request coming with .html suffix should be directed to Springs dispatcher, and this is where the action starts.

applicationContext.xml can contain all beans definitions except the controller bean definition.
dispatcher-servlet.xml should basically contain controller bean definition, but anything can go here.

Blank applicationContext.xml :

dispatcher-servlet.xml :

We can see above , we define a bean messageObject of type MessageClass and set its message using "value='Hello World'" (Dependency Injection).Here the setmessage() method of this object will be called to set message value.
Next we define another bean, our controller that will be looked upon when request comes to /sayHello.html . We then specify its messageObject to be equal to the previous bean defined above using 'ref' .

What is in my say_hello.jsp :

So When the application starts, the beans are created and then injected in order of dependency.
You should see Hello World message when page loads in the browser. ${message} is one that was added using modelAndView.addObject().

Tuesday, October 26, 2010

KML in Google Maps API

There are various ways of loading layers over google maps. One way is creating spatial objects and loading it from within the Java Script. If you you do not wish to touch the Java script code an alternative is using KML (Keyhole Markup language) file. Its basically in XML format and some things need to be taken into consideration when writing one, as a single silly mistake can get on your nerves. In this example i have drawn a polygon across a small area.

Below is what you will have in your html :

Object gx holds this KML file . You just have to add it as an overlay. Remember, your kml files have to on some public server and not localhost.
The content of KML is as follows :

In The KML file, the first thing that should be taken care of is namespace or xmlns="" which, if is wrong, Google won't load that kml. Each object can be displayed using Placemark which has a name and the object definition (Polygon in my case). Additionally you can add markers, polyline etc.

Wednesday, September 22, 2010

A simple GPS monitor in j2me with google maps support.

Application without google maps :
This is a simple application that shows the device's current location coordinates on the screen. It can be built in four easy steps -
1)Creating a canvas for displaying results.
2)Starting a new thread so that it doesn't slow down our application.
3)Using Location Provider object to retrieve the coordinates.
4)Displaying the coordinates on the canvas.

MyCanvas a canvas inherited class, which has a paintMe() function that takes 3 parameters, can be called whenever we need to refresh the screen with new data. In this case we are not using google maps so image passed can be anything else or null.

LocationProvider is a class that is used to obtain gps data from the device. Object of this class is initialized by setting it to LocationProvider.getInstance(Criteria) , where Criteria is a class that holds the options for the LocationProvider object. Examples of the options would be horizontal accuracy, vertical accuracy etc. See how these objects are initialized below in the GpsTracker() constructor.

startApp() is the entry point for the MIDlet where we create and start a new thread. run() contains the code for the thread, where we call getLocation() of Locationprovider object which returns Location object. We then retrieve coordinates from the Location object by calling its getQualifiedCoordinates() method.
Once we have the coordinates we can call paintMe() method of MyCanvas to refresh the page. code :

Adding Google Maps to the Application
With one more simple step google map can be displayed on the screen showing your current location. For that you need this file, download it and include it in your project.

Next you need to create an object of type GoogleMaps in you MIDlet, and you can call its retrieveStaticImage(height,width,latitude,longitude,zoom_level,image_format) method which will return the map image.

You can pass this image to paintMe() to draw it on the screen.
If you want to display additional details like marker, path etc on the map, modify and modify the return url in getMapUrl() method.

Saturday, September 18, 2010

Html revisited, with WRT Applications

WRT (Web RunTime) is a powerful platform for developing applications for your nokia cellphones without compromising the simplicity of programing. It takes the simplicity down to the HTML level! yes, if you know to develop a web page you can also build an application with the same skills and efforts. You can see the power of html today -> wonderful interfaces could be build using Html/Css and robust functionalities can be given using Javascript. WRT applications or widgets contain all these three components, and these applications run on nokia S60 3rd edition and above.

Lets create a small WRT application, a Tic Tac Toe game using html,css and standard javascript library. If you wish to add device dependent functionalities like using the camera etc, you have to include additional javascript library provided by nokia.

A WRT installation package has '.wgz' extension and includes five files. First decide a name for your application and create a folder with same name. Then open your favorite editor and create four files in that folder.
1)A html file, can be named anything (index.html in my case).
2)A css file with name of your choice (style.css in my case).
3)A Javascript file with name of your choice (jscript.js in mycase).
4)A Plist file named info.plist where you save the application information.
If you need an icon for your application create one and name it icon.png or with whatever extension.

The index.html code :

The style.css code :

The jscript.js code :

The style.css code :

Note : MainHTML entry should contain the html file name as is within the 'string' tag, and DisplayName should be same as the application name and folder that you created.

The Icon :

The application can be tested by opening the html file in a web browser.

Creating the installation package :
Just add the folder with all these files to a zip archive with same name (application name), next rename the zip file extension to '.wgz' and your package is ready.

Download my package here

Sunday, September 12, 2010

Jquery - Bouncing Box ScreenSaver

This tutorial will show you how to build a jquery screen saver for your site. I got this silly idea when i had to create a 'website offline' or 'website under maintenance' screen and show something more than just some lines of text. This Screen saver contains a box that bounces back n forth on the walls while simultaneously changing its color.The code is very simple and needs no explanation.

Any elements in the html can be easily animated using a simple function in jquery -> animate(). You can change most of the properties of an element, and it will apply a smooth transition to these changes.
animate() takes following arguments :
properties : specify the new properties here.
duration : the time stretch for this animation in miliseconds.
easing : type of animation.
callback : the function to be called when animation completes.


In properties you specify the new properties of the element, like height, width, background etc. The duration is the time deadline within which the animation should complete. The third argument is easing, which is the type of animation desired and includes options like swing (default, gives accelerated effect), linear (constant effect), easeOutBounce (Bouncing effect). In callback we can define what we need to do once the animation is over.
So the complete function looks like this :


The code

Below are some demos :

Bounce Effect :

Linear Effect :

Magnet Effect :