Saturday, December 22, 2007

struts2+Spring workflow

1. An initial request goes to the Servlet container (such as Jetty or Resin) which is passed through a standard filter chain.

2. the required FilterDispatcher is called, which in turn consults the ActionMapper to determine if the request should invoke an action.


3. The ActionMapper interface provides a mapping between HTTP requests and action invocation requests and vice-versa.

When given an HttpServletRequest, the ActionMapper may return null if no action invocation request matches, or it may return an ActionMapping that describes an action invocation for the framework to try.

If the ActionMapper determines that an Action should be invoked, the FilterDispatcher delegates control to the ActionProxy.

4. The ActionProxy consults the framework Configuration Files manager (initialized from the struts.xml file).

5. the ActionProxy creates an ActionInvocation, which is responsible for the command pattern implementation. This includes invoking any Interceptors (the before clause) in advance of invoking the Action itself.

6. Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml.

7. The result is then executed, which often (but not always, as is the case for Action Chaining) involves a template written in JSP or FreeMarker to be rendered.


8. While rendering, the templates can use the Struts Tags provided by the framework.

9. All objects in this architecture (Actions, Results, Interceptors, and so forth) are created by an ObjectFactory.

This ObjectFactory is pluggable. We can provide our own ObjectFactory
A popular ObjectFactory implementation uses Spring as provided by the Spring Plugin.

Normally, in struts.xml you specify the class for each Action. When using the default SpringObjectFactory, the framework will ask Spring to create the Action and wire up dependencies as specified by the default auto-wire behavior.


10. Interceptors are executed again (in reverse order, calling the after clause).


11. Finally, the response returns through the filters configured in the web.xml.


N.B:
don't know how to setup simple struts2 project? see simple setup

Monday, December 10, 2007

The 5 stages of grief


1. Denial: The initial stage: "It can't be happening."
2. Anger: "Why ME? It's not fair!" (either referring to God, oneself, or anybody perceived, rightly or wrongly, as "responsible")
3. Bargaining: Now the grieving person may make bargains with God, asking, "If I do this, will you take away the loss?"
4. Depression: "I'm so sad, why bother with anything?"
5. Acceptance: "It's going to be OK."


Kübler-Ross model

Wednesday, December 05, 2007

SCP using java api

same as SFTP example except use ScpClient in place of SFTPClient


ScpClient client = ssh.openScpClient();

// Open the SCP channel
String localFile = "localPath";
String remoteFile = "remotePath";

//
//get method signature
//public void get(java.lang.String localFile,
// java.lang.String remoteFile,
// boolean recursive,
// FileTransferProgress progress)
// throws SshException,
// ChannelOpenException
//

client.get(localFile,remoteFile,true);




syntax highlighted by Code2HTML, v. 0.9.1

SFTP using java api

Librery used SSHTools-J2SSH
Tutorial help from David Hayes

1
2 String userName = "someuser";

3 String password = "somepwd";
4
5 String host = "host_ip";

6 int port = 22;
7
8 String destinationPath = "<your_dest>";

9 String sourcePath = "<your_src>";
10
11 SshClient ssh = new SshClient();

12
13 try{
14 ssh.connect(host, port);

15
16 // Authenticate
17 PasswordAuthenticationClient passwordAuthenticationClient =
18 new PasswordAuthenticationClient();

19
20 passwordAuthenticationClient.setUsername(userName);
21 passwordAuthenticationClient.setPassword(password);

22
23 int result = ssh.authenticate(passwordAuthenticationClient);

24 if(result != AuthenticationProtocolState.COMPLETE){
25

26 throw new FTPException("Login to " + host + ":"

27 + port + " " + userName + "/" + password + " failed");

28
29 }
30
31 // Open the SFTP channel
32 SftpClient client = ssh.openSftpClient();

33 //change local directory where file would be copied
34 client.lcd(destination);
35 // download file

36 client.get(sourceFilePath);
37
38 client.quit();

39 ssh.disconnect();
40
41 }
42 catch(IOException e)

43 {
44
45 // file transfer failed
46 e.printStackTrace();

47 }




syntax highlighted by Code2HTML, v. 0.9.1

Tuesday, December 04, 2007

Writing pdf file using java

Librery used iText

// Step 1: Create an instance of com.lowagie.text.Document:

Document document = new Document();

//Step 2: Create a Writer (for instance com.lowagie.text.pdf.PdfWriter)
//that listens to this document and
//writes the document to the OutputStream of your choice:

PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));

//Step 3: Open the document:

document.open();

//Step 4: Add content to the document:

document.add(new Paragraph("Hello World"));

//Step 5: Closes the document:

document.close();



syntax highlighted by Code2HTML, v. 0.9.1

check other tutorials

Thursday, November 22, 2007

Help Sidr affected people

1. Type 'save' in your cell and send it to 5455
. your 1 single sms will give 15 tk to the cyclone
affected people. it's a joint project of "save the
children" and somewhereinblog.

2. You can also write “help” and send to “1010” from any mobile in Bangladesh.
It’s a joint initiative taken by all the mobile operator in Bangladesh and fully reliable.For each sms taka 10 will be deducted from your account and the total money will be donated for the SIDR affected people.

3. Directly to the Chief Adviser's Relief and Welfare Fund:
Current Account No.33004093 with Sonali Bank, Prime Minister's Office
Branch, Tejgaon, Dhaka, Bangladesh

4. Bangladesh Red Crescent Society
A/C No. 01-1336274-01
Standard Chartered Bank
Dhaka Bangladesh
SWIFT Code: SCBLBDDX

Here is a list of organizations we can send our contributions to:

UNICEF
Save the Children – US

International Federation of Red Cross and Red Crescent Societies

World Vision Web

World Vision Web
BY PHONE 1-888-562-4453 (888-56-CHILD) and donating with the “giving
code” of Bangladesh Cyclone Relief.

CARE Responds to Bangladesh Cyclone - Donate Now

Islamic Relief

Catholic Relief Services

Food for the Hungry

How to donate to "Chief Advisor's Relief and Welfare"
# Method 1
Check/money order/bank draft
Payable to : "Bangladesh Consulate General in New
York"
Memo: For Chief Advisor's Relief and Welfare Fund
Address to send:
211 East 43rd Street, Suite 502
NY 10017

*You will get an acknowledgment receipt from
Bangladesh Consulate General

# Method 2

Money Transfer via Sonali Exchange Co. Inc
Check payable to "Sonali Exchange Co. Inc. USA"
Memo: For chief advisor's relief and welfare fund
Address to send:
211 East 43rd St,
Suite # 1503
NY 10017
Tel: 212-808-0790/212-808-4085

Friday, November 16, 2007

1,100 reported killed in Bangladesh cyclone






Death toll may cross 1,000; all communications, utility services snapped; thousands missing; houses, crops, trees destroyed; lakhs homeless


Bangladesh dated with a nightmare as cyclone Sidr ripped through the southwestern coast late Thursday, killing over 700 people and demolishing houses, crops, vegetables and trees alike along its trail of devastation over an area of thousands of square kilometers.

Packing winds over 220km an hour, the fierce tropical storm roared across the shoreline after it hit landfall at the Khulna-Barisal coast at 7:30pm Thursday, cutting off all communications and utility services across the country.


One of the fiercest cyclones in the history of the land, the Sidr rode on wailing winds, driving rains and tidal surges to wreak havoc for over 14 hours before moving to Asam and Tripura through the Sylhet border, turning into a well-marked low yesterday.

Despite having carried out a commendable evacuation effort, the government last night found itself reeling from shock as the number of deaths and extent of damage continued to increase with every passing hour.

In a rather awkward manner, the food and disaster management ministry told the press in the afternoon that about 233 people were killed but left out death tolls in two most-affected districts--- Borguna and Jhalakathi. However, the same briefing stated that Red Crescent found 118 dead so far in Barguna alone.

But within hours at 12 midnight, an official at the food and disaster management ministry's control room raised the death figure to 700, with maximum 177 killed in Patuakhali. However, quoting unofficial sources, Our Correspondent in Patuakhali, reported death of 490 people.

But finds of newsmen and different private sources till filing of this report early morning today revealed that the death toll is destined to climb up to 1,000 as rescuers and volunteers could not yet reach most of the worst-hit areas.

Meanwhile, no information on causalities could be gathered from numerous remote islands (chars), residents of which mostly turned a deaf ear to government's evacuation alert.

“Tidal waves swept away many people from Dublar Char in Bagerhat”, Red Crescent worker Abul Kashem Dulal told our correspondent in Barisal. Of them, bodies of 17 people could be recovered.

The government could provide shelter for around 15 lakh people in 2168 shelter houses, leaving around 33 lakh people in the coastal areas in vulnerable situation.

Casualties apart, the Patuakhali district also suffered most in the farm sector. “The crop loss should be no less than Tk 497 crore in the seven upazilas,” he said, quoting a rough estimate of a deputy director of agriculture extension department in Patuakhali.

The Patuakhali town went under knee-deep waters as tidal surges 6-7 feet higher than normal ones sped through the locality. At least seven other southern districtsBarguna, Jhalakathi, Pirojpur, Bhola, Madaripur, Barisal and Bagerhat suffered nearly the same fate of Patuakhali.

However, the actual extent of destruction in Bagerhat could not be known till filing of this report as a very few could reach areas like Sharankhola near the worst-hit Sundarbans, the world's largest mangrove forest.

“Hundreds of trees lying on the roads and fields give a picture of massive damage,” said Raphael Palma, communications manager of World Vision Bangladesh, a non-government organisation.

Palma, who yesterday visited Mongla, said the locals are saying they lived through the cyclone of 1988 but it was no match to this cyclone. “The roaring wind was not as devastating as this one.”

The casualties could be much higher if not the local administration warned people about the imminent disaster, he observed.

As per the government count, 44 people died in Bagerhat. But unofficial sources put the number at 133, of which 90 were killed in Sharankhola upazila alone.

The volunteers and rescuers painted an even grimmer picture of the shocking event, which also left thousands injured. Chief Adviser Fakhruddin Ahmed too rushed to some southern districts in an effort to buck up the spirit of cyclone-victims.

But it will take weeks to assess the actual death toll, financial loss and days to reach relief to people who are forced to live overnight under the open sky, rescuers and volunteers said, almost in identical words.

People in lakhs are staying under the open sky with hardly any foods in their possession, thousand remained missing, embankments broke down in many areas, scores of livestock killed, and unknown number of persons was swept away by tidal surges.

However, the devastation could have been much higher if the cyclone, originally predicted to be heading for the shores of Orissa near Paradip, made landfall during the high tide hours at around 3:00am on Friday.

“Had the high tide and cyclone taken place at the same time the damage would have tripled,” said an expert.

According to the midnight update of the government, 177 were killed in Patuakhali, 134 in Pirojpur, 133 in Bagerhat, 78 in Barisal, 35 in Barguna, 32 in Jhlakathi, 25 in Gopalganj, 20 in Bhola, 15 in Shariatpur,12 in Khulna, 10 in Faridpur, four each in Chandpur and Dhaka, three in Sathkhira, one each in Laxmipur, Chittagong, and Jessore.

However, the government briefing in the afternoon stated 19 people were killed in Madaripur, two in Narayanganj, and one each in Noakhali and Chandpur.

full news

Monday, November 12, 2007

Free Rice: Web game provides rice for hunger



WFP food aid being distributed in Somalia - 26/09/2007
The WFP says hunger is the world's number one emergency
An internet word game has generated enough rice to feed 50,000 people for one day, the UN's World Food Programme (WFP) has said.

The game, FreeRice, tests the vocabulary of participants. For each click on a correct answer, the website donates money to buy 10 grains of rice.

Companies advertising on the website provide the money to the WFP to buy and distribute the rice.

FreeRice went online in early October and has now raised 1bn grains of rice.

That is enough rice to feed 50,000 people for one day, the WFP said on Friday.

Read the whole news here
and another here

& keep playing :)

Thursday, September 27, 2007

In Love, if Love be Love, if Love be ours,
Faith and unfaith can ne'er be equal powers:
Unfaith in aught is want of faith in all.

"It is the little rift within the lute,
That by and by will make the music mute,
And ever widening slowly silence all.

"The little rift within the lover's lute
Or little pitted speck in garnered fruit,
That rotting inward slowly moulders all.

"It is not worth the keeping: let it go:
But shall it? answer, darling, answer, no.
And trust me not at all or all in all."

Tuesday, September 25, 2007

Why we hiccup

A little history:
the day i posted this, ridwan was hiccup-ing :D... as the only thing i used to do in office was chatting with ridwan and/or shimi, i felt the strong urge to know why we hiccup :D.
----------------------------------------------------------------------------------


I found this interesting post in bbc news


--------------------------------------------------------------------------
Scientists believe they may be able to explain why people hiccup.

Researchers in France have suggested that it may be linked to evolution and the fact that our ancient ancestors lived in the sea.

They believe it may be a throwback to a time when our ancestors had gills to help them breathe.

The reason why humans hiccup has baffled scientists for hundreds of years, not least because it does not seem to serve any useful purpose.

Sudden contractions
Hiccups are sudden contractions of the muscles used for breathing in.

Just after the muscles start to move, the glottis shuts off the windpipe to produce the characteristic "hic" sound.


Ultrasound scans show that two-month-old babies hiccup in the womb, before any breathing movements appear.

One theory is that the contractions prepare the unborn baby's respiratory muscles for breathing after birth.

Another is that they stop amniotic fluid entering the lungs.

But neither of these ideas fully stands up.

For instance, if hiccups were supposed to keep fluid out of the lungs, it would make more sense for them to involve a cough-like response, not a breath inwards.

This latest theory, originally published in the journal BioEssays and reported in New Scientist magazine, says the key to hiccupping lies in a group of animals for whom combining closure of the glottis and contraction of the "breathing in" muscles does serve a clear purpose.

They are the primitive air breathers, such as lungfish, gar and many amphibians that still possess gills.

These creatures push water across their gills by squeezing their mouth cavity while closing the glottis to stop water getting into their lungs.

A group of scientists led by Christian Straus, at Pitie-Saltpetriere Hospital in Paris believes the brain circuitry controlling gill ventilation has persisted into modern mammals, including humans.

The researchers point to many similarities between hiccupping and gill ventilation in animals such as tadpoles.

Both are inhibited when the lungs are inflated, for example, and by high carbon dioxide levels in air or water.

There must, however, be a reason why hiccupping persists 370 million years after animals started hauling themselves onto the land.

Suckling

Straus and his colleagues suspect the habit has been adapted to a new use - helping mammals learn to suckle.

The sequence of movements during suckling is similar to hiccupping, with the glottis closing to prevent milk entering the lungs.

Allan Pack, an expert in respiratory neurobiology at the University of Pennsylvania, said it was a plausible theory.

But he added: "It's going to be very tough to prove."

The real test will be to look at the specific areas of the brain that control hiccups and suckling, says Straus.

If the theory is correct, most of the nerves cells that are active during suckling should also fire during hiccupping.

---------------------------------------------------------------



And u know, there is a hiccup lovers site :|:|:| , full of memorable (!?!?) hiccup stories

And a band called Hiccup THe Band


And ...... last but not the least, there is a patented device, called "Hic-Cup" for curing hiccups :D

Wednesday, September 12, 2007

here is the deepest secret nobody knows
(here is the root of the root and the bud of the bud
and the sky of the sky of a tree called life;which grows
higher than the soul can hope or mind can hide)
and this is the wonder that's keeping the stars apart

i carry your heart(i carry it in my heart)

Thursday, July 12, 2007

Make a difference

Name: Suraiya Khathun
Father’s Name: Abdul Hakim
School: Umananda Ideal Dhakil Madrasha
Board: Bangladesh Madrasha Education Board
CGPA: A+ (General) English (A), Sociology (A), History Islam (A)
Household income: Father is a poor farmer and day laborer. He has very limited land.
Live from hand to mouth mostly.
Family History: Three brothers and four sisters. She is the youngest one. Brothers
are day laborer and live separately. All sisters are married.


Address: Vill: Umananda, Post: Tabakpur, Thana: Ulipur, Dist.: Kurigram
Contact No: Nur Alam Siddique (Neighbor) 01710144480
General Comments: She is the first girl to get A+ from her school. She studied in
Madrasha since its tuition and other fees are less than schools.
Her father is insisting on continuing at Madrasha but she is
determined to go for college education. She is looking for local
college.
Essay writing: Write briefly about yourself, your aim and if you get a
scholarship how it will help you building your future?
Answer:
My name is Suraiya Khathun. I am a madrasha student. I got passing Dhakil examination
in 2007. My grade point is 5.00. My father is a poor man. He is only earning member of
our family. It is almost impossible to bear my educatinal expenses anymore. If I got a
scholership it will help me to continue my studies. Beacuse my father did not able to bear
my educaiotnal expenses. In future I became a great teacher. So I want to get this
scholarship which help me to reach my goal.

........................................................................................................................................................
& there are lot others like her who have achieved gpa 5 in ssc exam inspite of their financial and social condition. If they could do this much what couldn't they achieve with a little support from us?
Hridoye Bangladesh has taken initiative to help these students to continue their education. Please visit this site and let these gems win.

Monday, July 02, 2007

Migrating from struts1 to struts2

www.denverjug.org/meetings/files/200611_MigratingFromStruts1ToStruts2.pdf
--
Sheetal

struts2+spring+hibernate(part2)

useful links :
a sample code (by me)
struts2+spring workflow
struts2+spring+jpa
struts2 online book
hibernate tutorial
integrating spring,hibernate

struts2 + spring + hibernate

(If u don't how struts2+spring works, see struts2+spring workflow)

What i'm trying do to here:
i have a table named "User" in our database.
now i want to build a web-application using struts2+spring+hibernate
1. to add new user to database and
2. to log in to home page for existing user.

Download sourcecodes

Files (java/xml) i'll create for this:

1. "User" table in database.

2. User.java:
which will be mapped with that "User" table.
3. User.hbm.xml:
that maps User table with User.java.
4. IUserDao.java:
interface for data access object.
5. UserDAOHibernateImpl.java:
which implements IUserDao.java
6. IUserService.java:
interface for service
7. UserServiceImpl.java:
which implements IUserService
8. UserAction.java:
action class for struts2
9. applicationContext.xml:
Register your objects via the Spring configuration.
all the above files and data source will be configured here.
10. struts.xml:
its the configuration file for struts2 (which was struts-config.xml for struts1)
11. output *.jsp files, i've used 3 here:
11.i) addUser.jsp: to add new user in DB
11.ii) login.jsp: to log in existing user
11.iii) hello.jsp: says hello to the user after successful log in.
12. xml files for validation
13. and good old web.xml

jar files we need are same as this example

so now.......Ready... Set... GO!

1.Let, database used is mysql. database name ExampleDB and table name User.


create database ExampleDB;
use ExampleDB;
create table User(
name varchar(20),
id
varchar(20) not null primary key
);





2. write the web.xml file:

In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts framework and handles all requests.

If you don't know how to write web.xml for struts2, see web.xml

In most cases, we can simply use web.xml for struts2-blank template. we just need to add the following lines to configure the Spring listener.

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener

</listener-class>
</listener>



Everything else is same as any other web.xml for struts2.

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

<web-app id="example" version="2.4"
xmlns=
"http://java.sun.com/xml/ns/j2ee"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=
"http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>


<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>

</filter-mapping>

<welcome-file-list>
<welcome-file>/login.jsp</welcome-file>
</welcome-file-list>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener

</listener-class>
</listener>

</web-app>





3.write User.java file that will be used to map the User table.

package com.example.user; 

public class User {

private String id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {

this.name = name;
}
/** * @return Returns the userId. */

public String getId() {
return id;
}

/** * @param userId The userId to set. */
public void setId(String userId) {
this.id = userId;
}

}






4.Now maps the database table with .java file. To do this, write the mapping file, User.hbm.xml :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >


<!--Maps User.java class with User
database table -->


<hibernate-mapping>
<class name="com.example.user.User"

table="User">


<id name="id" column="id" >
<generator class="assigned" />

</id>
<!--
id tag represents the primary key of
database table generator class defines
how key will be generated.
Here we've choose "assigned", that is key will be
assigned before insert.
Other generator classes are:
1.native
2.increment : auto increment the key value
-->


<property name="name" column="name" />

<!--
property tag maps columns other than
the primary key column.
-->


</class>
</hibernate-mapping>



Put all your *.hbm.xml files in com/example/user/hbm folder.

5.Write the Data Access Object that would be used to access database using hibernate.
At first we would write the interface : IUserDao.java

package com.example.user ; 
public interface IUserDao {
public String addUser(User user);
public User findUserById(final String Id);


}

//Now write UserDAOHibernateImpl.java :

package com.example.user;
import org.springframework.orm.
hibernate3.HibernateTemplate;

public class UserDAOHibernateImpl
implements IUserDao
extends HibernateDaoSupport
{


public String addUser(User user){
String success;
try{
getHibernateTemplate().save(user);
success="Welcome !";
}
catch(Exception e){
success="Sorry, user cannot be added";
}
return success;
}

public User findUserById(final String id){

return (User)

getHibernateTemplate().get(User.class, id);
}

}






getHibernateTemplate().save(user) would insert user into the User database table
we've used HibernateTemplate because it provides easy method to do basic queries and also it is thread safe.
get method will return the user object with given id if such an user existed, otherwise null will be returned.

6. Write the service class (it would seem a little redundant at first, but it's the best practice to provide service layer between action and dao class).
Usually database transaction management is applied on this layer.
//Interface for service class:

package com.example.user;

public interface IUserService {
public String add(User user);
public User findById(final String Id);

}

//Service class: UserServiceImpl.java

package com.example.user;
public class UserServiceImpl implements IUserService{

private IUserDao userDao;

public IUserDao getUserDao() {
return userDao;
}
public void setUserDao(IUserDao userDao) {

//userDao will be set by applicationContext.xml

this.userDao = userDao;
}

public String add(User user){
String result=userDao.addUser(user);
return result;
}
public User findById(String Id){
User user=userDao.findUserById(Id);
return user;
}

}





7.At last, now write the action class: UserAction.java
Here our action class will
1.take the user id
2.retrieve user name from database
3.and say " Hello <user name>"
4.add new user

package com.example.user; 

import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext ;


public class UserAction {
private IUserService userService;
private User user;
private String id;
private String name;

/** * Constructor * @param userService */
public UserAction(IUserService userService)
{

this.userService=userService;

// will be set by applicationContext.xml
}
public String execute() {
this.user=

(User)userService.findById(this.id);
String result;
if(user==null){

// returns error if user doesn't exist.

result="User id does not exist";
ActionContext.getContext().
getSession().

put("result", result);
return Action.ERROR;
}
else {
result="";
ActionContext.getContext().
getSession().
put("user", user);

// puts user object in session
return Action.SUCCESS;
}
}
public String signup(){
return Action.SUCCESS;
}
public String addUser(){
String result;
this.user=

(User)userService.findById(id);
if(user==null){
user=new User();
user.setId(this.id);
user.setName(this.name);
result=userService.add (user);
ActionContext.getContext().
getSession().
put("user", user);
}
else{
result="Id already used,
Choose another Id"
;
ActionContext.getContext().
getSession().
put("result",result);

return Action.ERROR;
}
ActionContext.getContext().
getSession().
put("result", result);
return Action.SUCCESS;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}


}



8.Write the jsp files: we will use 3 jsps here
1.login.jsp: take the id from user
2.hello.jsp: say hello
3.addUser.jsp: add a user



login.jsp:
<%@ taglib prefix="s" uri="/struts-tags"%>

<html >
<head>
<title>Log in</title>
</head>
<body>
<h2><s:property value="#session.result"/></h2>
<s:form action="SignIn" validate="true">
<s:textfield label="User Id" name="id" required="true"/>
<s:submit value="Login" />
</s:form>
<a href=" <s:url action="SignUp"/> "> Sign Up As A New User </a>
</body>

</html>
---------------------------------------------------------------
hello.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<html >
<head>
<title>Hello</title>
</head>
<body>
<s:if test="#session.user!=null">
<h2>Hello <s:property value="#session.user.name"/></h2>
</s:if>
</body>

</html>
--------------------------------------------------------------------
addUser.jsp
<%@ taglib prefix="s" uri="/struts-tags"%>
<html >
<head>
<title>Sign Up</title>
</head>
<body>
<s:property value="#session.result"/></h2>
<s:form action="add" validate="true">
<s:textfield label="User Name " name="name" required="true"/>
<s:textfield label="User Id" name="id" required="true"/>
<s:submit value="Submit"/>
</s:form>
</body>

</html>





9. Write the applicationContext.xml file:

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

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">


<!--
- Application context definition
-->
<beans>
<!-- ========================= RESOURCE DEFINITIONS ========================= -->

<!-- Creating a data source connection pool-->

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource ">


<property name="driverClassName">

<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/ExampleDB</value>

</property>
<!-- Provide username and password for mysql -->
<property name="username" value="root"/>
<property name="password" value=""/>



</bean>


<!-- Hibernate SessionFactory -->

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">


<property name="dataSource"><ref bean="dataSource"/></property>
<property name="mappingDirectoryLocations">
<list>

<value>classpath:/com/example/user/hbm</value>
</list>
</property>

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">

org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- show the sql command in console -->
</props>
</property>

</bean>



<!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->

<!--
Data access object: Hibernate implementation.
-->


<!-- with transaction -->
<bean id="hibernateTemplate"

class="org.springframework.orm.hibernate3.HibernateTemplate">

<property name="sessionFactory">
<ref bean="sessionFactory"/>

</property>
</bean>

<bean id="UserDaoImpl" class="com.example.user.UserDAOHibernateImpl">
<property name="hibernateTemplate">

<ref bean="hibernateTemplate"/>
</property>
<!-- set HibernateTemplate in UserDAOHibernateImpl.java class-->
</bean>

<!--
Defination of service targets
-->

<bean id="UserServiceTarget"

class="com.example.user.UserServiceImpl">

<property name="userDao">
<ref bean="UserDaoImpl"/>

</property>
<!-- set IUserDao in UserServiceImpl.java class-->
</bean>


<!--
Definition of Transaction Manager
-->

<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">


<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!--
Base service object
-->


<bean id="Service"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
abstract="true">

<property name="transactionManager">

<ref bean="transactionManager"/>
</property>

<property name="transactionAttributes">
<props>


<prop key="add">PROPAGATION_REQUIRED</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<!-- specifies the methods on which transaction management will be applied-->

</props>
</property>
</bean>

<!--
Children service objects using base service and service
targets
-->


<bean id="UserService" parent="Service">

<property name="target">
<ref bean="UserServiceTarget"/>
</property>

</bean>


<!--
Definition of Action objects
-->


<bean id="userAction"
class=" com.example.user.UserAction" singleton="false">

<constructor-arg>

<ref bean="UserService"/>
</constructor-arg>
<!-- set IUserService in UserAction.java's constructor-->
</bean>

</beans>




syntax highlighted by Code2HTML, v. 0.9.1


10. Last step :) now, write the struts.xml file:


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

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="user" extends="struts-default">


<action name="SignIn" method="execute" class="userAction" >
<result>/hello.jsp</result>

<result name="error">/login.jsp</result>
</action>
<action name="SignUp" method="signup" class="userAction">

<result>/addUser.jsp</result>
</action>

<action name="add" method="addUser" class="userAction">

<result>/hello.jsp</result>
<result name="error">/addUser.jsp</result>
</action>

</package>

</struts>



syntax highlighted by Code2HTML, v. 0.9.1


------------------------------------------------------------------------------------------------
And here's the validation file, just save it under the same folder as the action.
filename should be <action-classname>-<action-name>-validation.xml
For login action, validation filename would be UserAction-SignIn-validation.xml


<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">


<!--
Validation rules for sign in action
-->

<validators>
<field name="id">
<field-validator type="requiredstring">
<message>You must enter user id</message>

</field-validator>
</field>
</validators>



syntax highlighted by Code2HTML, v. 0.9.1



--
Sheetal