Welcome to Srini's blog

Tuesday, September 21, 2010

VMWare-tools installation in Linux/Windows VMs

Before yesterday I tried to install VMWare-tools in windows/linux VMs in my local VMserver. It is very simple and easy to do. In this post I will explain this procedure step by step with screen shots.

Windows : Installing VMware-tools in windows VM is very simple. Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will prompt you warning message . Click Ok. Before doing above things open console view of the VM. Now you will see prompt on console as see pic-2. Read the instructions carefully and finish the installation.

Pic-1

Pic -2


Linux[GUI] : Installing VMware-tools in Linux GUI is also very simple. Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will propmt you warning message . Click Ok. Before doing above things open console view of the VM. Now you will see prompt on console as see pic-3. Click on VMwaretools...rpm. Read instructions carefully and finish the installation.

Pic-3

Linux [Text mode] :Installing VMware-tools in Linux text mode is little bit difficult compare to GUI. Follow the steps carefully.
Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will prompt you warning message . Click Ok.Open the console view and proceed as below.
1. First mount the CDROM using cmd mount /dev/cdrom /mnt .
2. Check whether it is mounted or not using cmd ll /mnt, If it is mounted correctly then you will see file VMwareTools-4.0.0-208167.tar.gz.
3. Create temporary dir to proceed installation from here .. mkdir /tmp/vmtools
4. Go to /tmp/vmtools.
5. Untar /mnt/VMwareTools-4.0.0-208167.tar.gz in /tmp/vmtools by run the cmd tar -xzvf /mnt/VMwareTools-4.0.0-208167.tar.gz. Now you will find one dir named vmware-tools-distrib.
6. In vmware-tools-distrib dir you will find one perl script file named vmware-install.pl. Run the perl script file. here 2 ways to proceed. If you run the script using cmd
a. perl vmware-install.pl --default : it will install without asking any further confirmation from you.
b. perl vmware-install.pl : This cmd will start install and ask your confirmation for each step. Read each confirmation and proceed[Simply say yes for all].

Friday, September 17, 2010

Adding favicon to Blog

A favicon is a small image, measuring 16×16 pixels. It is short form of favorite Icon, and which is displayed on the browser tabs just left side of your blog/website title. Favicon can act as symbol of your websites. Today i added favicon to my blog. In this post, I’ll explain how to add a favicon to your blog.

1. First you must create your own icon for your Blog using available free favicon generators. (Note: It must be in 16*16 in size).
a. Dynamic drive
b. Favicon Generator
c. Degraeve.

2. Upload the .ico file to your online storage location (ex. Flickr, picasa, photobucket.. etc). If your online storage not supported to upload .ico files then generate .png file(16x16) using adobe photoshop.

3. After upload, you can see what you uploaded. Now copy the image location by right click on the image and select [copy image location ( For Firefox), Copy Image URL ( for Crome), Copy Image Address ( For Opera).

4. Now open Your Blogger Account, On your Dashboard, Select your Blog –-> Layout or Design –-> Edit HTML, Backup your Template. (Note: It’s very important to backup), Now Find < head> tag and paste the following code before </ head> tag.
< link href='http://favicon_img.png' rel='shortcut icon' type='image/png' ./>

Replace favicon_img.png with copied your image location url.

5. Save the template.

Now refresh your blog page and see your favIcon.

Wednesday, September 15, 2010

Appanapalli Tour -- Boat ride on Godavari

Last weekend I experienced a great.. horrible ... exiting ... and risky journey in river godavari. I planned to visit appanapalli for lord venkateswara swami darshanam , Actually my naming ceremony held in this place about 22 years ago. Myself and my nephew nagendra started @ my home on Sunday morning. We reached 'Taatipaka' which is 10KM far from appanapalli around 10AM, We caught auto from here to reach dest.

Before 5KM to dest auto driver stopped and told us due to floods in river godavari all surrounding areas are submerged, So catch boat from here and go to temple. This is really un expected and feared to journey on boat in godavari. First 10 min we r in dailamo, But almost we crossed 80 KM to reach this place, we need to travel one more 5KM on boat. Atlast we stepped into boat with co-pilgrims.. .... wooohhhh ..1 hour journey in boat on heavy floating godavari .... its really horrible and at the same time exiting movements ... This is really un-expected traveling which I had never experienced in my early life.These boats are human powered rowboats, because of journey towards/between the coconut trees motor boats are not used here.


Atlast we reached temple @ 12PM and had bath in river godavari with my shaved head. Due to lunch hours temple closed , So meanwhile we had free meal and had darshnam @ 2:30 PM. We returned back on same boat. After reached roadway I feel like 90% of my return journey completed eventhough I need to travel 80 KM more. Uhhhh .. I reached home @ 8:00 PM and caught Gowtami superfast train to reach Hyd.

Thursday, September 9, 2010

Festivals weekend

Hello bloggers, I am wishing you a very colorful and joyful weekend with festivals Ramzan and Vinayaka Chaturdhi. I am going to my home village today to celebrate these occasions. After a long time myself and venky will travel in same train. If possible this weekend I am planning to goto 'Appanapalli' to Lord balaji darshanam. Appanapalli is a pilgrimage village which is located 35KM far from Amalapuram. Hope this weekend will make my days as special and colorful to me.

Integrating hibernate to java web application

This post is continuation to my last post "Sample web application using struts framework". In this post we will see how to integrate hibernate to our sample web application .

Application : My application is simple login page with server side validation and verify the login details from DB and render success/failure page. I used Mysql as DB.

Step 1 : Setup in Eclipse:
=================
Please create the setup as specified in previous post and add the following additional things.
1. Additional sub folder structure
A. Create src dir structure
i. Login/src/com/srini/model
ii. Login/src/com/srini/model/hbm
iii. Login/src/com/srini/hibernate
iv. Login/src/com/srini/db

2. Addtional Files needs to be create
i. hibernate.cfg.xml [Login/src/com/srini/webapp/WEB-INF/classes]
ii. Login.java [Login/src/com/srini/model]
iii. Login.hbm.xml [Login/src/com/srini/model/hbm]
iv. HibernateSessionFactory.java [Login/src/com/srini/hibernate]
v. mysql_users.sql [Login/src/com/srini/db].
vi. mysql_dbscript.sql [Login/src/com/srini/db]
vii. LoginAction [Login/src/com/srini/action] -- This class is modified

3. Additional Dependency jars :
i. asm.jar
ii. cglib-2.1.jar
iii. dom4j-1.6.jar
iv. ehcache-1.1.jar
v. hibernate3.jar
vi. jaxen-1.1-beta-4.jar
vii. jta.jar
viii. mysql-connector-java-3.1.12-bin.jar

4. Modify 'server.xml' file : This is to specify your DB details and add docBase so that when you hit the url http://localhost:8080, it will automatically run your web application. Add the Context tag to server.xml file in tomcat conf dir. Add the following code with in Host tag . Modify the context path to your server path.

The configuration looks like

<Context path="" docBase="C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/login" privileged="true" antiResourceLocking="false" antiJARLocking="false"> <Resource name="jdbc/struts" auth="Container" type="javax.sql.DataSource" maxActive="100" minIdle="10" maxIdle="30" maxWait="10000" username="struts" password="struts" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1/struts?useUnicode=true&characterEncoding=utf8&autoReconnect=true" logAbandoned="true" validationQuery="SELECT 1" removeAbandoned="true" testOnBorrow="true" testWhileIdle="true" timeBetweenEvictionRunsMillis="10000" minEvictableIdleTimeMillis="180000" removeAbandonedTimeout="60" /> </Context>

5. Modify 'login-build.xml' file : Modify ant build script slightly to add hibernate related changes.
i. Add new target 'copy.hbm.files '.
<target name="copy.hbm.files" >
<copy todir="${build}/${name}/WEB-INF/classes/com/srini/model/hbm">
<fileset dir="${login.src.root}/src/com/srini/model/hbm">
<include name="*.xml"/>
</fileset>
</copy>
</target>

ii. Add new target to dependents list in compile target.
<target name="compile" depends="init, copy.login.webapp, copy.hbm.files" >
iii. Add additional jars to classpath.

Step 2 : Each file description and code inside the file :
============================================
1. hibernate.cfg.xml : Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column.

The configuration looks like

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/struts?useUnicode=true&characterEncoding=utf8&autoReconnect=true</property>
<property name="hibernate.connection.username">struts</property>
<property name="connection.password">struts</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/srini/model/hbm/Login.hbm.xml"/>
</session-factory>
</hibernate-configuration>


I think you are already knew the first 6 properties. If 'show_sql' property is 'true' then it will write all SQL statements to console. <mapping resource="com/srini/model/hbm/Login.hbm.xml"/> property is the mapping for our login_details table.

2. Login.java : This is model class to map table.
package com.srini.model;

/**
* @author srinut096@gmail.com
*
*/
public class Login {

private int id;
private String name;
private String password;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

3. Login.hbm.xml : This file is used to map Login Object to the login_details table in the database.

The configuration looks like

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.srini.model">
<class name="Login" table="login_details">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<property name="name" type="string" column="name"/>
<property name="password" type="string" column="password"/>
</class>
</hibernate-mapping>


The hibernate-mapping element is the root element. The class element is used to map the Java class with the database table. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute of the class element. The id element is used to create the primary key. The name attribute of the id element refers to the property in the Login class and the column attribute refers to the column in the login_details table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type and vice versa. The generator element within the id element is used to automatically generate the primary key values. When the class attribute of the generator element is set to native, hibernate picks either identity, sequence or hilo algorithm depending upon the capabilities of the underlying database. The property element is used to link a property in the Java class to a column in the database table.

4. HibernateSessionFactory.java : This class helps in creating the SessionFactory from the Hibernate configuration file(it automatically pick up the hibernate.cfg.xml file from WEB-INF dir of web application).

package com.srini.hibernate;

import java.util.logging.Logger;

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

/**
* @author srinut096@gmail.com
*
*/
public class HibernateSessionFactory {
private static final SessionFactory sessionFactory;
private static Logger log = Logger.getLogger(HibernateSessionFactory.class.getName());

static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
log.severe("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}


The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread. Here the static singleton pattern is used to instantiate the SessionFactory.

5. mysql_users.sql : script to create user, db in mysql.
DROP DATABASE IF EXISTS struts;
DELETE FROM mysql.user WHERE User='struts';
FLUSH PRIVILEGES;
CREATE DATABASE IF NOT EXISTS struts CHARACTER SET utf8;
GRANT ALL PRIVILEGES ON msp.* to `struts`@`127.0.0.1` IDENTIFIED BY 'struts' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON struts.* to `struts`@`localhost` IDENTIFIED BY 'struts' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON struts.* to `struts`@`%` IDENTIFIED BY 'struts' WITH GRANT OPTION;
use struts;


6. mysql_dbscript.sql : script to create db schema.
USE struts;
--
-- Table structure for table login_details
--

DROP TABLE IF EXISTS login_details;
CREATE TABLE login_details (
id bigint(20) NOT NULL auto_increment,
name varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY login_key (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO login_details VALUES (1,'srini','pass123');


7. LoginAction.java : This class is modified slightly to add logic to get data from DB and compare form values with DB values and forward respective pages.
package com.srini.action;

import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.srini.form.LoginForm;
import com.srini.hibernate.HibernateSessionFactory;
import com.srini.model.Login;

/**
*
* @author srinut096@gmail.com
*/
public class LoginAction extends Action {

/* forward name="success" path="" */
private final static String SUCCESS = "success";
private final static String FAILURE = "failure";
private static Logger log = Logger.getLogger(LoginAction.class.getName());
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
log.severe("Username in Action: " + loginForm.getUserName());

Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
Login loginDetails = null;
ActionForward forward = null;
try {
transaction = session.beginTransaction();
Query query = session.createQuery("from Login where name = ?");
//if (values != null) {
//for (int i = 0; i < logins =" query.list();" logins ="=" logindetails =" (Login)logins.get(0);" logindetails ="=" forward =" mapping.findForward(FAILURE);" forward =" mapping.findForward(SUCCESS);" forward =" mapping.findForward(FAILURE);">


The first call to the HibernateSessionFactory.getSessionFactory().openSession() method begins the session. The session.beginTransaction() method is used to start a new transaction. The session.createQuery() method is used to create a query object which helps in retrieving the persistant objects. Here we use Hibernate Query Language (HQL). "from Login where name=?" returns a the login details matched to name in the login_details table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list of login details.

Now run the application in any standard browser

1. Start Tomcat
2. http://localhost:8080
3. Enter the name and password and click login button. It will check the name in DB and returns success/failure page.

Wednesday, September 8, 2010

Sample web application using struts framework

Hello all yesterday I tried to build a simple java web application using struts and hibernate from scratch using tomcat webserver. I would like to explain step by step procedure here.

I am assuming you are already familiar with java, struts, hibernate theoretically. If not please take a low level view of all these. All my setup is build in Eclipse IDE. I wrote an ant script to build and deploy my application, So that we can directly run the build script to build/deploy the web application.

Required Tools
1. Tomcat 5.5
2. Eclipse IDE
3. Dependecy jars

About Application : My application is simple login page with server side validation and verify the login details from DB and render success/failure page. In this post i will explain how to build sample web application using struts, later post i will tell about hibernate integration to this application. I used HTML form, JSP for UI and servlets for business logic and also used beans.

Step 1 : Setup in Eclipse
====================
1. Goto File --> New --> Project
2. Select Java --> java project
3. Name the project as 'Login'
4. Click Finish.

5. Create folder structure as follows
A. Create src dir structure
i. Login/src/com/srini/action
ii. Login/src/com/srini/form
B. Create webapp dir structure
i. Login/src/com/srini/webapp
ii. Login/src/com/srini/webapp/jsp
iii. Login/src/com/srini/webapp/WEB-INF
iv. Login/src/com/srini/webapp/WEB-INF/lib
v. Login/src/com/srini/webapp/WEB-INF/classes/resources

6. Files needs to be create are
i. web.xml [Login/src/com/srini/webapp/WEB-INF]
ii. struts-config.xml [Login/src/com/srini/webapp/WEB-INF]
iii. LoginAction.java [Login/src/com/srini/action]
iv. LoginForm.java [Login/src/com/srini/form]
v. login.jsp [Login/src/com/srini/webapp/jsp]
vi. success.jsp [Login/src/com/srini/webapp/jsp]
vii. failure.jsp [Login/src/com/srini/webapp/jsp]
viii. MessageResources.properties [Login/src/com/srini/webapp/WEB- INF/classes/resources]
ix. login-build.xml [Login]
x. login-build.properties [Login]

7. Dependency jars : Please download following jars from net. I don't hv an option to upload here.
i. antlr.jar
ii. commons-beanutils.jar
iii. commons-collections.jar
iv. commons-digester.jar
v. commons-logging.jar
vi. commons-validator.jar
vii. jakarta-oro.jar
viii. jsp-api.jar
ix. servlet-api.jar
x. struts.jar

Step 2 : Each file description and code inside the file
===========================================
1.web.xml : This file has all the configuration information which we have defined for our web application. The configuration information includes the index file, the default welcome page,the mapping of our servlets including path and the extension name...etc.

ActionServlet is the central component of the Struts controller. This servlet extends the HttpServlet. This servlet basically performs two important things.
1. When the container gets start, it reads the Struts Configuration files and loads it into memory in the init() method.
2. It intercepts the HTTP request in the doGet() and doPost() method and handles it appropriately.

The configuration looks like

<?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>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>jsp/login.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>


2.struts-config.xml : The name of the struts configuration file can be configured in the web.xml file. This file is placed under the WEB-INF directory of the web application. This file has all the information about many types of Struts resources and configures their interaction.

This configuration looks like

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="LoginForm" type="com.srini.form.LoginForm"/>
</form-beans>

<global-forwards>
<forward name="welcome" path="/Welcome.do"/>
</global-forwards>

<action-mappings>
<action input="/jsp/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.srini.action.LoginAction">
<forward name="success" path="/jsp/success.jsp" />
<forward name="failure" path="/jsp/failure.jsp" />
</action>
<action path="/Welcome" forward="/jsp/welcomeStruts.jsp"/>
</action-mappings>

<message-resources parameter="resources/MessageResource"/>
</struts-config>


This file is used to associate paths with the controller components of your application., known as Action classes like <action input="/jsp/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.srini.action.LoginAction">. This tag tells the Struts ActionServlet that whenever the incoming request is http://localhost/login.do, then it must invoke the controller component LoginAction. Above, you can see that we have written .do in the URL. This mapping is done to tell the web application that whenever a request is received with the .do extension then it should be appended to the URL.

3. LoginAction.java : The execute method contains the business logic of the application. Here first we typecast the ActionForm object to LoginForm, so that we can access the form variables using the getter and setter methods. If the user name and password is same then we forward the user to the success page else we forward to the failure page.
package com.srini.action;

import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.srini.form.LoginForm;

/**
*
* @author srinut096@gmail.com
*/
public class LoginAction extends Action {

/* forward name="success" path="" */
private final static String SUCCESS = "success";
private final static String FAILURE = "failure";
private static Logger log = Logger.getLogger(LoginAction.class.getName());
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
log.severe("Username in Action: " + loginForm.getUserName());

if(loginForm.getUserName().equals(loginForm.getPassword())) {
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}


4. LoginForm.java : Inside the validate method, we check whether the user name and password is entered. If not the corresponding error message is displayed to the user. The error messages are configured in the Message.properties file.
package com.srini.form;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
* @author srinut096@gmail.com
*/
@SuppressWarnings("serial")
public class LoginForm extends org.apache.struts.action.ActionForm {

private String userName = null;

private String password = null;

/**
*
*/
public LoginForm() {
super();
// TODO Auto-generated constructor stub
}

/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param request The HTTP Request we are processing.
* @return
*/
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (userName == null || userName.length() < password ="=" username =" userName;" password =" password;">


5. login.jsp : We use Struts HTML Tags to create login page. The form has one text field to get the user name and one password field to get the password. The form also has one submit button, which when clicked calls the login action. <html:errors /> tag is used to display the error messages to the user.
<%--
Document : login
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>

<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<div style="color:red">
<html:errors />
</div>
<html:form action="/Login" >
User Name :<html:text name="LoginForm" property="userName" />
Password :<html:password name="LoginForm" property="password" />
<html:submit value="Login" />
</html:form>
</body>
</html>


6. success.jsp :
<%--
Document : success
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login Success. Welcome <bean:write name="LoginForm" property="userName"></bean:write></h1>
</body>
</html>


7. failure.jsp :
<%--
Document : failure
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div style="color:red">
<h1>Invalid user name <bean:write name="LoginForm" property="userName"></bean:write></h1>
</div>
</body>
</html>



8. MessageResources.properties : This file contains the error messages. The key "error.userName.required" is used in the validate function to add a new error. Since the error messages are configured in a seperate properties file they can be changed anytime without making any changes to the java files or the jsp pages.
error.userName.required = User Name is required.
error.password.required = Password is required.


9. login-build.xml : Ant build script to build the login.war
<?xml version="1.0" encoding="UTF-8"?>
<project name="Login2" default="build.war" basedir=".">
<property file="login-build.properties"/>
<property name="name" value="login2" />
<property name="build" value="${login.src.root}/build" />
<property name="war" value="${build}/war" />
<property name="source" value="${login.src.root}/src" />
<property name="lib" value="${login.src.root}/webapp/WEB-INF/lib" />

<!-- ********************************************************************** -->
<!-- Deploy war -->
<!-- ********************************************************************** -->
<target name="deploy.war" depends="build.war" >
<delete file="${login.server.root}/${name}.war" />
<delete dir="${login.server.root}/${name}" />
<copy todir="${login.server.root}">
<fileset dir="${war}">
<include name="${name}.war"/>
</fileset>
</copy>
</target>

<!-- ********************************************************************** -->
<!-- build war -->
<!-- ********************************************************************** -->
<target name="build.war" depends="compile" >
<war warfile="${war}/${name}.war" webxml="${build}/${name}/WEB-INF/web.xml">
<fileset dir="${build}/${name}">
<include name="**/**" />
</fileset>
</war>
</target>

<!-- ********************************************************************** -->
<!-- Compilation -->
<!-- ********************************************************************** -->
<target name="compile" depends="init, copy.login.webapp" >
<javac srcdir="${source}" destdir="${build}/${name}/WEB-INF/classes" debug="${javac.debug}">
<classpath refid="class.path"/>
</javac>
</target>

<path id="class.path">
<fileset dir="${lib}">
<include name="antlr.jar"/>
<include name="commons-beanutils.jar"/>
<include name="commons-collections.jar"/>
<include name="commons-digester.jar"/>
<include name="commons-logging.jar"/>
<include name="commons-validator.jar"/>
<include name="jakarta-oro.jar"/>
<include name="jsp-api.jar"/>
<include name="servlet-api.jar"/>
<include name="struts.jar"/>
</fileset>
</path>

<!-- ********************************************************************** -->
<!-- Initialization -->
<!-- ********************************************************************** -->
<target name="init" >
<delete dir="${build}" />
<mkdir dir="${build}/${name}/WEB-INF/classes"/>
<mkdir dir="${war}" />

</target>

<!-- ********************************************************************** -->
<!-- Copy struts webapp dirs -->
<!-- ********************************************************************** -->
<target name="copy.login.webapp" >
<copy todir="${build}/${name}">
<fileset dir="${login.src.root}/webapp">
<include name="**/**"/>
<exclude name="META-INF/**"/>
</fileset>
</copy>
</target>


10. login-build.properties : properties for ant build script
# ********************************************************
# Customize this one with your own root directory
# ********************************************************
login.src.root=C:/E-Folder/struts_workspace/login

login.server.root=C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps
# ********************************************************
# compilation
# ********************************************************
java.home = C:/Program Files/Java/jdk1.6.0
javac.deprecation = off
javac.nowarn = off
javac.debug = on
javac.optimize = off
jndi.prefix = java:comp/env/


Now run the application in any standard browser

1. Start Tomcat
2. http://localhost:8080/Login/login.do