You are on page 1of 37

STRUTS

Struts is a open source framework from apache software foundation (ASF)


Struts framework is web framework which will help the web developer. to Develop a web based
application with low cost and within less time.
Struts frame work was implemented based on the following design pattern
Front controller design pattern
MVC design pattern
Struts frame work was implemented based on the following web technologies
JSP

AS

RP

FN
LN
Skill A
B
Gender M
F

ActionServlet

RequestProcessor

Register

Presentation Layer

Controller Layer

Class HelloBean extends ActionForm


{
String Fname;
String Lname;
---- ---- --Presentation Layer
Set method
Get method
}

Action class
Execute(AM,AF,HS
Req,HSRes)
{
a) Collect the
incoming
data
b) Interact with
model
c) Process
results
d) Forward
same to JSP

Model

JDBC
DAO
EJB
Hibernate
WebServices

Mysql
Model Layer

Presentation layer may contains


JSPs
Struts Custom tags
Property file
Form-beans

We need two components: ---- Struts-Config.xml


Web.xml

First Struts Example


Files required: -----Patni Confidential

I. postproblem.jsp
II. ProblemAction.java

III. ProblemForm.java
IV. problemstatus.jsp

V. web.xml
VI. jlc.xml

postproblem.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html><body><h1>post your problem</h1>
<html:form action="/post.do">
<table><tr><td>Problem Title</td>
<td><html:text property="title"/></td></tr>
<html:select property="priority">
<html:option value="High">High</html:option>
<html:option value="Medium">Medium</html:option>
<html:option value="Low">Low</html:option>
</html:select></td></tr>
<tr><td>Problem Description</td>
<td><html:textarea property="description"/>
</td></tr>
<tr>
<td><html:submit value="post"/></td></tr></table></html:form>
</body></html>
problemstatus.jsp
<h1>problem is posted successfully
package com.jlc.dev;
ProblemForm.java
import org.apache.struts.action.*;
public class ProblemForm extends ActionForm
{
private String title;
private String priority;
private String description;
public void setTitle(String title)
{
this.title=title;
}
public String getTitle()
{
return this.title;
}
public void setPriority(String priority)
{
this.priority=priority;
}
public string getPriority()
{
return this.priority;
}
public void setDescription(String description)
{
this.description=description;
}
public string getDescription()
{
Patni Confidential
return this.description;
}
}

ProblemAction.java
package com.jlc.dev;
import org.apache.struts.action.*;
import javax.servlet.http.*;
public class ProblemAction extends Action
{
public ActionForward execute(ActionMapping am,ActionForm af,HttpServletRequest
req,HttpServletResponse res)
throws Exception
{
ProblemForm pf=(ProblemForm)af;
string t=pf.getTitle();
String p=pf.getPriority();
String d=pf.getDescription();
System.out.println(t);
System.out.println(p);
System.out.println(d);
return am.findForward("problemstatus");
}
}
jlc.xml
<struts-config>
<form-beans>
<form-bean name="pform" type="com.jlc.dev.ProblemForm"/>
</form-beans>
<action-mappings>
<action path="/post" name="pform" type="com.jlc.dev.ProblemAction"
scope="request" validate="true" input="/postproblem.jsp">
<forward name="problemstatus" path="/problemstatus.jsp"/>
</action>
</action-mappings>
</struts-config>

Web.xml

Patni Confidential

<web-app>
<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/jlc.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>

<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load_on_startup>1</load_on_startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

devSupport

build.xml

src
tlds
java

com
jlc

lib

web
Web.xml
Jlc.xml
*.xml

Struts-html.tld
Struts-bean.tld
problemstatus.jsp Struts-logic.tld
postproblem.jsp Struts-tiles.tld
Struts-nested.tld
Struts-template.tld
*.jsp
*.tld

dev
ProblemAction.java
ProblemForm.java

Struts.jar
Servlet-api.jar
Jsp-api.jar
MySql.jar
Commons-beanUtils.jar
Commons.collection.jar
Commons.digester.jar
Commons.logging.jar
Commons.fileuploader.jar
Commons.validate.jar
Jakarta-oro.jar
Struts-legacy.jar
Common-lang.jar
*.jar

Struts flow
After developing the struts application and deploying it is the server & when you start the server then following
things will happened:------------ Container initializes(read the data) the web.xml

Patni Confidential

When container is reading the data from web.xml container checks all the servlets configured if they
contain <load-on-startup> tag then the container try to load the servlet into the main memory . In our case
we are configuring only one servlet called ActionServlet with <loadon-startup> tag Because of this
container loads the ActionServlet into the memory, instance will be created and then init() method will be
called.
Inside the init() method they implement the code using SAX parser to read the data from struts
configuration time(to file which you are passing as init parameter) once init() method is completed , all
the data from struts configuration file will be loaded into main memory. If any problem happened while
passing the xml documents error will be located/reported to log file and may not allow tomcat startup.
//every xml must be validated
When you send the request to PostProblem.jsp to display that in the browser following things will happened: ---1) 1st request will be given to ActionServlet
2) ActionServlet receive the request and then delegate the request to request processor.
3) Upon receiving the request, request processor starts processing the request by doing the following things
Incoming request uri(form tag action attribute value) will be compared against path
attribute value of action tags configure in action mapping .
if the mapping action is not found. Then the error message (500)called cannot retrieve
mapping for the action/post99 it will be display to client.
If the matching action is found then its name attribute value will be taken
With that name RP (request processor) verifies all the form-bean configured to check any
form bean tag name is mapping with. If no names is matching with the given name then
error message called cannot retrieve definition for from bean PForm will be display to
the client.
If it(form-bean definition) is found then its types attribute value will be taken which is
nothing but form bean java class fully qualified name. form bean java class will be
verified if it is not found then error message called Exception creating bean of class
com.jlc .dev problem from 99 which will you not provided.
If the class is found then it will be loaded and it will be instantiated and initialized.
The form- bean object will be stored in the given scope (value of scope of scope attribute)
The requested JSPs display to the client (PostProblem.jsp)
If the scope is request then in form-bean java class ,for each request one instance will be created and
initialized .
But if you dont specify the scope then the default scope session is taken . in this case for every request
only one instance of form-bean java class is created and default value will be initialized to this object.
The name of the attribute in JSP and in form-bean java class should be same.
When you are writing the uri for the JSP to display it in the browser .after hitting it then you are
sending one request to this JSP.
When user click on submit button after entering the value in the fields then following things will happened :--- Request will be submitted to ActionServlet
ActionServlet delegates the request to request processor .
Request processor identify the corresponding action for the incoming request .
RP(Request processor) identify the form bean-name and then its type.
RP retries or creates the form-bean object(creating in case of scope request otherwise retrieve).
RP Populate the clients submitted into form bean object.
RP takes the types of the action (Action class name)
Patni Confidential

Action class will be instantiated if request is coming to that Action class at the 1 st time otherwise
already created instance will be retrieves from application scope(for many users and many browser)
RP invokes the execute() method by passing the follow four parameter: --------------

ActionMapping
ActionForm
ActionHttpRequest
ActionHttpResponse

Code inside the execute() method interacts with the model component and gets the result after processing the
results action forward object will be returned by the execute() method to request processor(RP).
RP takes the returned action forwarded object(which is associated with forward name) and identify the
corresponding forward in struts configuration files
RP takes the path (Jsp) specified for the identified forward and the same (JSP)will be forwarded to the
client
When you are developing web based application using servlet and JSP and using MVC front controller design
patter you can get the following results:-----------1) Code duplication problem
2) Presentation layer components and controller layer component will be tightly coupled
3) Maintenance problem
Flow chart: --------Plz see back side
(e) Retrieve or create the form-bean object.
(f) populate the client submitted into form-bean object.
(h) retrieve or create the Action class object.
Form-bean is specific to unique user. In this we can keep the data in any scope like session, request
but not in application.
But in Action class the object will be kept in the Application scope by default because it has only
one instance for all the users (many request).
Hence in this class if any instance are there then that is common to each users.

Without struts
Login.jsp
UN

LoginAction
JLC
Controller
Servlet

PW
Submit

Home Page

java class+jdbc
DAO+jdbc
Hibernate

Some Action

Some Action

DAO+Hibernate
EJB
Web Services
Model Layer

Web.xml

Business Layer
Patni Confidential

DB
server

EIS layer

14-JUN-2008

Controller Layer
Presentation Layer

persistence Layer

With struts
Model layer
ActionServlet
UN

LoginAction

RP

Raman

Action

PW
Submit

Home Page

Any model
Component

Web.xml

StrutsConfig.xml

DB
server

Controller Layer
EIS layer

Presentation Layer

Comparission
When you are implementing request without struts then you need to update the controller servlet many
time with many if condition which leads to a complicated controller logic inside the controller servlet and
is unmanageable and error prone.
you need to hard code the jsp name inside the jsp in the case of non struts application where as JSPs
name will be centralized in the struts configuration file. This reduces lots of maintenances.
In the case of non struts application you need to hard code the JSPs inside the action class when you
creating the RequestDispatcher where as in the case of struts application JSPs name will be centralized
in StrutsConfiguration file to reduce the maintenance .
In the case of nonstruts application developer is responsible to collect the data from incoming request.
Sometimes developer may feel complexity on collecting the data from complicated JSP form. Where as in
struts application RequestProcessor does this work and gives the data in the simple java-Bean object.
In the case of non-struts application developer are responsibility to implement the custom tag for useful
scenario whereas In the case of struts application already custom tag is implemented by apache so
developer can use directly.
In the case of non-struts application mapping the flow of application is a complicated issue. This is solved
in struts. In struts already apache has implemented ActionServlet and RequestProcessor which is dealing
with mainly flow of the application (controller logic)
In the case of non-struts application they is no support for internationalization (I 18 N) application
developer has to implement the code for this support .whereas in case of struts application built in support
is there for internationalization (I 18 N)
Patni Confidential

What is the use of action mapping?


Why I have to use struts to develop web based application?
Can I give duplicate value for the <load-on-startup>?
Questions
Can I give 0 (zero) value for the <load-on-startup>?
Can I give - (negative) value for the <load-on-startup>?
What are the difference between JAR and WAR?
What are the use of debug and detail init parameters?
What will happen when I am not providing <load-on-startup> for action servlet?
Can I configure the filters for the struts application?
When action servlet will be instantiated?
How many instance of action servlet will be created?
Can I replace the action servlet with my own servlet called jlc action servlet?
When request processor class will be instantiated?
How many instances of request processor will be created?
Can I replace request processor class with my own class called jlc request processor?
How many instances of action class will be created?
How many instances of form bean class will be created?
14-JUN-2008
Can I take my own name for the struts configuration file?
What is the default value of scope attribute in the action tag?
What is the default value of validate attribute in the action tag.
Questions
What is the responsibility action servlet?
What are the responsibility of the request processor class?
It is minatory to use *.do as URL pattern in action servlet can I use *.jlc?
What are the design pattern used in the struts?
What is the use of debug and detail init parameters providing in action servlet configuration?
Can I take same url pattern for multiple servlet?
Can I change the name of web.xml to jlc.xml?
Mainly struts frame work deals with two layers: ----- Presentation layer
Controller layer

Presentation layer
Struts presentation layer contains the following listed components
JSP/HTML
Struts tag libraries
Message bundles
form-Beans
JSP/HTML:--------When you are developing JSPs you can use all the JSP elements, JSTL tags, EL statements
and struts custom tags.
Struts tag libraries: ----- Apache has implemented various custom tags and categories as follows: --------- Struts html tag libraries
Struts Bean tag libraries
Struts Logic tag libraries
Struts Tiles tag libraries

HTML tag libraries


Patni Confidential

<html:button>
<html:cancel>
<html:submit>
<html:reset>
<html:text>
<html:textarea>

<html:javascript>
<html:file>
<html:checkbox>
<html:select>
<html:option>
<html:password>

<html:hidden>
<html:link>
<html:error>
<html:form>
<html:radio>

Bean tag libraries

<bean:write>
<bean:message>
<bean:parameter>
<bean:cookie>
<bean:include>

<bean:define>
<bean:forward>
<bean:size>
<bean:page>
<bean:header>

<logic:notMatch>
<logic:redirect>
<logic:iterate>
<logic:equal>
<logic:notEqual>
<logic:lessThan>
<logic:meassageParent>
<logic:forward>

Logic tag libraries

<logic:empty>
<logic:notEmpty>
<logic:parent>
<logic:notParent>
<logic:lessEqual>
<logic:greaterThan>
<logic:greaterEqual>
<logic:match>

Message Bundle: ---- It is nothing but simple property files which contains key value pairs.
Property files will be used to achieve the internalization (I 18 N)
Following piece of code show that how to use the property files: -----<html:form action=------some action--------->
<bean:message key=label.Search.sid/>
<html:text property=sid/><br>
<html:submit value=show/>
<html:form>

Search.jsp

Enter Sid

Show

ApplicationResources.properties
label.Search sid=<font color=bluesize=4> Enter Sid</font>
Application Resources hi.properties
Label.Search.sid=Enter(in hindi)
form-bean is a simple java-bean class which contains private field and public set, get method form-bean is a
container of the data which stores the client submitted values.
Patni Confidential

When you writing the form bean that must be the subclass of one of the following:--------

ActionForm
DynaActionForm
ValidatorForm
ValidatorActionForm
DynaValidatorActionForm

Following is the life cycle of the form-bean: ------------------Browser

Invokes
execute()

Forward to
input JSP

No Error

If Error Found

Calls validate()

ActionServlet

Populates the data


into form-bean
object

RequestPro
cessor
Retrieve or create
form-bean object

Calls reset()

life cycle of the form-bean


You can divide the form beans into two types: ----------- Static form
Dynamic form
Static form: ------- following three are the static forms
ActionForm
ValidatorForm
validatorActionForm
When you are using the static form you need to do the following things :-------

You need to write a java class by extending one of the above static forms.
You need to declare the fields same as JSP forms.
You need to write the set/get methods for all the fields.
You need to override the following reset method.

Patni Confidential

public void reset(actionMapping am,HttpServletRequest req)


{
}
You need to override the following validate method
public ActionErrorsValidate(actionMapping am,HttpServletRequest req)
{
}
Note: ------

reset() method will be used to assign the default values to form fields.
Validate() method will be used to apply the validation rule on client submitted data.
When you are using action for your form-bean then you should override the validate() method.
When you are using validatorForm and validatorFormAction as a super class then you can use
validationFrameWork for the form validation instead of overriding validate() method.

Dynamic form: ----------- following three are the Dynamic forms.


DynaActionForm
DynavalidatorForm
DynavalidatorActionForm
When you are using DynaActionForm you need to do the following: ------- Write the field declaration inside the struts configuration file(No need to write java class with private field
and set/get method)
DynamicForm will be reset automatically to default values(No need to override reset method)
Dynamic forms will use validation framework for the form validations (No need to override the validate
method)
Example

Form
<html:form action=/login>
Username:<html:text property=uname/><br>
Password : <html:password property=pwd/><br>
<html:submit value=login/>
</html:form>

Using ActionForm
[I]
Public LoginForm extends ActionForm
{
String uname;
String pword;
//set/get method
Public void reset)actionMapping am,HttpServletResponse res)
Patni Confidential

{
Uname=sri
Pword=null;
}
publicActionErrorValidate(ActionMapping am,HSR req)
{------------------------}
[II]

Struts-config.xml
<form-bean name=/form type=com.jlc.LoginForm/>

[III]

In Action
LoginForm lf=(loginForm)af;
Un=lf.getUname();
Pw=lf.getPword();

Using DyanaActionForm
In strutsConfig.xml
<form-bean name=lform type=org.apache.struts.action.DynaActionForm>
<form-property name=uname initial=sri/>
<form-property name=pword type=java.lang.string/>
</form-bean>
In Action
DynaActionForm df=(DynaActionForm)af
Un=df.get(uname).toString();
Pw=df.get(pword.toString();

Controller layer
Struts controller layer has the following three components: ------- ActionServlate
RequestProcessor
ActionClass

Action class

Action class is the end for the controller layer and it has client for business component and model layer
component.
Action class which you are implementing may be the subclass of one of the following nine classes: -------------1) Action
4) MappingDispatchAction
7) SwitchAction
2) DispatchAction
5) IncludeAction
8) LocaleAction
9) DownloadAction
3) LoookUpDispatchAction
6) ForwardAction

Patni Confidential

Using Action
[1]

login.jsp

in struts-Config.xml

<html:form action=/login.do
------------- -------- -----</login:form>

<action-mapping>
<action path=/login
name=lform
type=com.jlc.loginAction
---- ----- ---- ----- />

public class LoginActionextends Action


{
public A.F execute(-,-,-,-)
{
--- ---- ----- -------- ----------}}

[II] reg.jsp
<html:form action=/register.do
<action path=/register
name=rform
type=com.jlc.RegisterAction
---- ----- ---- ----- />
</action-mapping>

------------- -------- -----</login:form>

public class RegisterActionextends Action


{
public A.F execute(-,-,-,-)
{
--- ---- ----- -------- ----------}}

Using DispatchAction
[1]

login.jsp

in struts-Config.xml

<html:form action=/login.do?
method=login>
------------- -------- -----</login:form>

<action-mapping>
public class StudentAction extends DispatchAction
<action path=/login
{
name=lform
public A.F login(-,-,-,-)
type=com.jlc.StudentAction
{
parameter=method
---- ----- ---- ----- />
--- ---- ----- -------- ----------}}

[II] reg.jsp
<html:form action=/register.do?
Method=register>
------------- -------- -----</login:form>

public class StudentAction extends DispatchAction

<action path=/register
name=rform
type=com.jlc.StudentAction
Parameter=method
---- ----- ---- ----- />
</action-mapping>

{
public A.F register(-,-,-,-)
{
--- ---- ----- -------- ----------}}

Action class V/S DispatchAction class


When you are using Action class you need to

When you are using DispatchAction

Patni Confidential

write multiple java class for multiple


requirements.
When you are using Action class presentation
layer components (Jsp) and controller layer
component are loosely coupled and validation
errors.

Class you can write the single java class


for the multiple requirement with
multiple methods.
When you are using Dispatch action
class Jsp and action class will be tightly
coupled which gives the maintenance.

Handling the Exceptions and validation Errors in struts


Consider the following requirement: ----------

Enter Sid
AS

99999

RP

Display
Search.jsp

Validation error on input data


Field is required: ---------StudentID is required
Sid format must be SD111 (start with SD and ..)
When exception is raised StudentId not found

Example

StudentAction
extends
DispatchAction
{
A.F search(-,-,-,-)
{
Sid=------;
Sto=getInfoById(sid
)
If(sto==null)
{
Throw new Student
FoundException()
}
Else
{
Req.setAttribute(ST
O,sto)
}
-- ---- ----- ---}
}

<html:form action=/search.do?method=search>
Enter SID<br>
<html:text property=sid/>
<html:errors property =sid/>
// This is display errors message in JSP
<html:errors>

www.jlcindia.com
Steps to handle the exception in struts: ------------Patni Confidential

Student
model
JDBC

MySql

At the following in the JSP to populate (display) the error


<html:errors/>
<html:form action=/search.do?method=search>
Enter SID<br>
<html:text property=sid/>
<html:errors property =sid/>
// This is display errors message in JSP
<html:errors>
<br>
<html:submit value=display/>
<html:form>
Write the user defined exception class
package com.jlc;
public class studentNotFoundException extends Exception
{
}
Write one key value pairs inside the ApplicationResources.property file.
Errors.sid.notFound=<font color=red size=4>StudentIdNotFound</font>
Write the following Exception in struts configuration file
<action path=/search name=sform parameter =method type=com.jlc.studentAction
scope=request validate=true>
Input=search.jsp>
<forward name=ok path=/result.jsp/>
<exception type=com.jlc.StudentNotFoundException path=/search.jsp
key=error.sid.notfound/>
</action>
Inside the action class write the following code to throws the Exception .
Throw new StudentNotFoundException()
Steps to handle the validation Errors from input data: ---------- Write the <html:error> tag in the Jsp to display the error message.
Write the following entry in the ApplicationResources.property
Errors.sid.required=<font color=red size=4>
Student id is Required</font>
Errors.sid.format=<font color=red size=4> Student Id format is incorrect</font>
Insure the validation are not disabled.
Validate attribute of action tag must be true.(by default it is always true)
Insure that input JSPs is specified using input attribute of action tag.
<action path=--------------
----- --------Validate=true
// according to above 3rd and 4th step
Input=/search.jsp>
Override the validate() method in the form-bean java class(in the case of not using validation framework)
public class searchForm extends ActionForm
{
String sid;
Patni Confidential

//set/get methods
public void reset(ActionMapping am,HttpServletRequest req)
{
sid=null;
}
public ActionErrors validate(ActionMapping am,HttpServletRequest req)
{
Action Errors errors=new ActionErrors();
if(sid==null|| sid.length()==0)
{
error.add(sid,newActionError(errors.sid.required));
}
else
if(!sid.start with(SD)||sd.length()!=5)
{
errors.add(sid,newActionError(Errors.sid.format));
}
return errors;
}

Use case required for the web support application role wise
User use cases

Register
Login
Add problem
Add address
Update Address
Update problem
View all problems
View problem by date
View answer for the problem
Logout

Develop use cases

Register
login
View all problems
Add answer to problem
Update answer
Logout

Manager or team leader use cases

Register
Login
View all problems
View all developers
Assign problem to developer
View problem statusPatni Confidential
View the developer status
Logout

Admin use cases

Login
View all users
View users by amount
View all developers
View developers by amount
Disable the developer account.
View developers by company.
Logout

Diagram: ----

17/06/2008

http://localhost:9999/ds/user/login.jsp

Jlc dev support TM

D
Please enter email Id

Account Login

Your
password
has been
sent to your
email.

Username
Password
Submit
Login
New user signup
I cant access my account

A
B

D
----------------------------

B
First Name
Last Name
Email
Phone
DOB
Username
Password
E

Register

WELCOME -------------------------------------- -----

Change password
Update your data
Bank account info
Address
Post problem
View all problem
View problem by date
Update problem
View all answer for problem
Logout

Welcome to
Dev Support

Get login.jsp
Home.jsp

Example
1) login.jsp

Files required
8) jlc-dev.xml
Patni Confidential

16) DAOFactoryImp.java

2)
3)
4)
5)
6)
7)

forgotpassword.jsp
fps.jsp
register.jsp
home.jsp
LoginForm.java
ForgotPasswordForm.java

9) Application.properties
10) UserAction.java
11) web.xml
12) LoginFailedException.java
13) RegistrationFailedException.java
14) UserNotFoundException.java
15) DAOFactory.java

17) UserDAO.java
18) JdbcUserDAO.java
19) JdbcUtil.java
20) UserTo.java
21) UserIdGenerator.java
22) User table

login.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld"
<td><html:password property="password"/></td>
prefix="html"%>
<td><html:errors property="password"/></td
<html>
</tr>
<body>
<tr>
<h1>Account Login</h1>
<td align="center" colspan="2">
<h3><html:errors/></h3>
<html:submit value="Login"/>
<html:form action="/loginsubmit.do? method=login"> </td>
<table>
</tr>
<tr>
</table>
<td>UserName</td>
</html:form>
<td><html:text property="username"/></td>
<html:link forward="signup"> New User
<td><html:errors property="username"/></td>
Signup</html:link><br>
</tr>
<html:link forward="forgotpassword"> I can't access
<tr>
my account</html:link>
<td>Password</td>
</body>
</html>
forgotpassword.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld"
prefix="html"%>
<html>
<body>
<h1>Password Assistance</h1>
<h3>
<html:errors/>
</h3>
<html:form action="/fpsubmit.do? method=forgot">
<table>
<tr>
<td>Enter Email ID</td>
<td>

<html:text property="email"/>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<html:submit value="Give My Password"/>
</td>
</tr>
</table>
</html:form>
</body>
</html>
home.jsp

<%@ taglib uri="/WEB-INF/struts-html.tld"


prefix="html"%>
<html>
<body>
<h1>Account Login</h1>
<h3><html:errors/></h3>

<td>Password</td>
<td><html:password property="password"/></td>
<td><html:errors property="password"/></td
</tr>
<tr>
<td align="center" colspan="2">
Patni Confidential

<html:form action="/loginsubmit.do? method=login">


<table>
<tr>
<td>UserName</td>
<td><html:text property="username"/></td>
<td><html:errors property="username"/></td>
</tr>
<tr>

<%@ taglib uri="/WEB-INF/struts-html.tld"


prefix="html"%>
<html>
<body>
<h1>New Account</h1>
<h3>
<html:errors/>
</h3>
<html:form action="/registersubmit.do?
method=register">
<table>
<tr>
<td>First Name</td>
<td>
<html:text property="fname"/>
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<html:text property="lname"/>
</td>
</tr>
<tr>
<td>Email</td>
<td>
<html:text property="email"/>
</td>
</tr>
<tr>
<td>Phone</td>
<td>

<html:submit value="Login"/>
</td>
</tr>
</table>
</html:form>
<html:link forward="signup"> New User
Signup</html:link><br>
<html:link forward="forgotpassword"> I can't access
my account</html:link>
</body>
</html>

register.jsp
<html:text property="phone"/>
</td>
</tr>
<tr>
<td>Dob</td>
<td>
<html:text property="dob"/>
</td>
</tr>
<tr>
<td>UserName</td>
<td>
<html:text property="username"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<html:password property="password"/>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<html:submit value="CreateAccount"/>
</td>
</tr>
</table>
</html:form>
</body>
</html>
fps.jsp

<h1>your password has been sent to your mail id</h1>


Application.properties
Patni Confidential

errors.login.username.required=<font color=red size=4>Username is required</font>


errors.login.username.length=<font color=red size=4>Username length must be ranging from 5-10
characters</font>
errors.login.password.required=<font color=red size=4>Password is required</font>
<struts-config>
errors.login.password.length=<font
color=red size=4>Password length must be ranging from 6-12
<form-beans>
characters</font>
<form-bean
name="loginform" type="com.jlc.dev.forms.LoginForm"/>
errors.fpf.email.required=<font color=red size=4>Email id is required</font>
errors.fpf.email.email=<font
color=red size=4>Invalid Email id</font>
<form-bean
name="fpform" type="com.jlc.dev.forms.ForgotPasswordForm"/>
exceptions.login.failed=<font color=red size=4>Invalid Username or password ID</font>
exceptions.register.failed=<font
size=4>Register Failed,Try Again</font>
<form-bean
name="registerform"color=red
type="org.apache.struts.action.DynaActionForm"/>
exceptions.fp.notfound=<font
size=4>No User found with given email ID</font>
<form-property
name="fname"color=red
type="java.lang.String"/>
<form-property name="lname" type="java.lang.String"/>
<form-property name="email" type="java.lang.String"/>
<form-property name="phone" type="java.lang.String"/>
jlc-dev.xml
<form-property name="dob" type="java.lang.String"/>
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
</form-bean>
<form-bean name='tmpform" type="org.apache.struts.action.DynaActionForm"/>
</form-beans>
<global-forwards>
<forward name="signup" path="/register.jsp"/>
<forward name="forgotpassword" path="/forgotpassword.jsp"/>
</global-forwards>
<action-mappings>
<action path="/loginsubmit" name="loginform" type="com.jlc.dev.actions.UserAction"
parameter="method" scope="request" validate="true"
input ="/login.jsp">
<exception type="com.jlc.dev.exceptions.LoginFailedException"
key="exceptions.login.failed" path="/login.jsp"/>
<forward name="home" path="/home.jsp"/>
</action>
<action path="/registersubmit" name="registerform" type="com.jlc.dev.actions.UserAction"
parameter="method" scope="request" validate="true"
input ="/register.jsp">
<exception type="com.jlc.dev.exceptions.RegistrationFailedException"
key="exceptions.register.failed" path="/register.jsp"/>
<forward name="login" path="/login.jsp"/>
</action>
<action path="/fpsubmit" name="fpform" type="com.jlc.dev.actions.UserAction"
parameter="method" scope="request" validate="true"
input ="/forgotpassword.jsp">
<exception type="com.jlc.dev.exceptions.UserNotFoundException"
key="exceptions.fp.notfound" path="/forgotpassword.jsp"/>
<forward name="fpstatus" path="/fps.jsp"/>
</action>
<action path="/loginsubmit" name="tmpform" type="com.jlc.dev.actions.UserAction"
parameter="method">
<forward name="login" path="/login.jsp"/>
</action>
</action-mappings>
Patni Confidential
<message-resources parameter="com.jlc.dev.Application"/>
</struts-config>

Web.xml
<servlet>
</init-param>
<servlet-name>action</servlet-name>
<init-param>
<servlet<param-name>detail</param-name>
class>org.apache.struts.action.ActionServlet</servlet<param-value>3</param-value>
class>
</init-param>
<init-param>
<load-on-startup>0</load-on-startup>
<param-name>config</param-name>
</servlet>
<param-value>/WEB-INF/manish.xml</param<servlet-mapping>
value>
<servlet-name>action</servlet-name>
</init-param>
<url-pattern>*.do</url-pattern>
<init-param>
</servlet-mapping>
<param-name>debug</param-name>
</web-app>
<param-value>3</param-value>
DAOFactory.java

DAOFactoryImp.java

package com.jlc.dev.dao;
public abstract class DAOFactory
{
public static DAOFactory getDAOFactory()
{
return new DAOFactoryImp();
}
public abstract UserDAO getUserDAO();
}

package com.jlc.dev.dao;
public class DAOFactoryImp extends DAOFactory
{
public UserDAO getUserDAO()
{
return new JdbcUserDAO();
}
}

ForgotPasswordForm.java
package com.jlc.dev.forms;
import javax.servlet.http.*;
import org.apache.struts.action.*;

this.email=null;
}
public ActionErrors validate(ActionMapping
am,HttpServletRequest req)
Patni Confidential

public class ForgotPasswordForm extends ActionForm


{
String email;
public void setEmail(String email)
{
this.email=email;
}
public String getEmail()
{
return this.email;
}
public void reset(ActionMapping
am,HttpServletRequest req)
{

{
ActionErrors errors=new ActionErrors();
if(email==null||email.length()==0)
{
errors.add("email",new
ActionError("errors.fpf.email.required"));
}
else if(email.indexOf('@')==-1)
{
errors.add("email",new
ActionError("errors.fpf.email.email"));
}
return errors;
}
}

User_table
Create table user_table(user_id char(10) primary key,firstName char(10), lastName char(10),email
char(17),phone long, DOB char(17),username char(15),password char(15));
JdbcUserDAO.java
package com.jlc.dev.dao;
con=JdbcUtil.getMysqlConnection();
import java.sql.*;
ps=con.prepareStatement('select 8 from user-table
import com.jlc.dev.to.*;
where username=? and password=?");
import com.jlc.dev.util.*;
ps.setString(1,un);
import com.jlc.dev.exceptions.*;
ps.setString(2,pw);
public class jdbcUserDAO implements UserDAO
ResultSet rs=ps.executeQuery();
{
public void addUser(UserTo uto) throws Exception
if(!rs.next())
{
{
Connection con=null;
throw new LoginFailedException();
PrepareStatement ps=null;
}
try
}
{
finally
con=JdbcUtil.getMysqlConnection();
{
ps=con.prepareStatement("insert into user_table
JdbcUtil.cleanup(ps,con);
values(?,?,?,?,?,?,?,?)");
}
ps.setString(1,uto.getUserId());
}
ps.setString(2,uto.getFname());
public void forgotPassword(String em)throws
ps.setString(3,uto.getLname());
Exception
ps.setString(4,uto.getEmail());
{
ps.setLong(5,uto.getPhone());
Connection con=null;
ps.setString(6,uto.getDob());
PrepareStatement ps=null;
ps.setString(7,uto.getUserName());
try
ps.setString(8,uto.getPassword());
{
int x=ps.executeUpdate();
con=JdbcUtil.getMysqlConnection();
if(x==0)
ps=con.prepareStatement("select password from
{
user_table where email=?");
throw new RegistrationFailedException();
ps.setString(1,em);
}
ResultSet rs=ps.executeQuery();
Patni Confidential

}
finally
{
JdbcUtil.cleanup(ps,con);
}
}
public void verifyUser(string un,String pw)throws
Exception
{
Connection con=null;
PreparedStatement ps=null;
try
{
LoginFailedException.java

RegistrationFailedException.java

package com.jlc.dev.exceptions;
public class LoginFailedException extends Exception
{

if(rs.next())
{
System.out.println("send the mail");
}
else
{
throw new UserNotFoundException();
}
}
finally
{
JdbcUtil.cleanup(ps,con);
}
}
}

package com.jlc.dev.exceptions;
public class RegistrationFailedException extends
Exception
{
}

JdbcUtil.java
return con;
}
import java.sql.*;
public static void cleanup(Statement st,Connection con)
{
public class JdbcUtil
try
{
{
public static Connection getMysqlConnection()
if(st!=null)
{
{
Connection con=null;
st.close();
try
}
{
if(con!=null)
Class.forName("com.mysql.jdbc.Driver");
{
con=DriverManager.getConnection("jdbc:mysql://loca con.close();
lhost/manish","root","manish");
}
}
}catch(Exception e)
catch(Exception e)
{
{
e.printStackTrace();
e.printStackTrace();
}
}
}
}
package com.jlc.dev.util;

LoginForm.java
package com.jlc.dev.forms;
import javax.servlet.http.*;
import org.apache.struts.action.*;

public ActionErrors validate(ActionMapping


am,HttpServletRequest req)
{
ActionErrors errors=new ActionErrors();
Patni Confidential

public class LoginForm extends ActionForm


{
String username;
String password;
public void setUserName(String username)
{
this.username=username;
}
public String getUserName()
{
return this.username;
}
public void setPassword(String password)
{
this.password=password;
}
public String getPassword()
{
return this.password;
}
public void reset(ActionMapping
am,HttpServletRequest req)
{
this.username=null;
this.password=null;
}
package com.jlc.dev.actions;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.actions.*;

if(username==null||username.length()==0)
{
errors.add("username",new
ActionError("errors.login.username.required"));
}
else if(username.length()<5||userlength()>10)
{
errors.add("username",new
ActionError("errors.login.username.length"));
}
if(password==null||password.length()==0)
{
errors.add("password",new
ActionError("errors.login.password.required"));
}
else
{
if(password.length()<6||password.length()>12)
{
errors.add("password",new
ActionError("errors.login.password.length"));
}
return errors;
}
}
UserAction.java
import com.jlc.dev.to.*;
import com.jlc.dev.dao.*;
import com.jlc.dev.util.*;
import com.jlc.dev.forms.*;

public class UserAction extends DispatchAction


{
UserDAO udao=null;
public UserAction()
{
udao=DAOFactory.getDAOFactory().getUserDAO();
}
public ActionForward login(ActionMapping am,ActionForm af,HttPServletRequest req,HttPServletResponse res)
throws Exception
{
LoginForm lf=(LoginForm)af;
String un=lf.getUsername();
String pw=lf.getPassword();
udao.verifyUser(un,pw);
HttpSession ses=req.getSession();
ses.setAttribute("UN",un);
return am.findForward("home");
}
public ActionForward register(ActionMapping am,ActionForm af,HttPServletRequest req,HttPServletResponse res)
throws Exception
Patni Confidential

{
DynaActionForm df=(DynaActionForm)af;
String fn=df.get("fname").tostring();
String ln=df.get("lname").tostring();
String em=df.get("email").tostring();
Long ph=(Long)df.get("phone");
String dob=df.get("dob").tostring();
String un=df.get("username").tostring();
String pw=df.get("password").tostring();

UserTo uto=new UserTo();


uto.setUserId(UserIdGenerator.getNextUserId());
uto.setFname(fn);
uto.setLname(ln);
uto.setemail(em);
uto.setPhone(ph.longValue());
uto.setDob(dob);
uto.setUserName(un);
uto.setPassword(pw);
udao.addUser(uto);
return am.findForward("login");

}
public ActionForward forgot(ActionMapping am,ActionForm af,HttPServletRequest req,HttPServletResponse res)
throws Exception
{
ForgotPasswordForm fpf=(ForgotPasswordForm)af;
string em=fpf.getEmail();
udao.forgotPassword(em);
return am.findForward("fpstatus");
}
public ActionForward logOut(ActionMapping am,ActionForm af,HttPServletRequest req,HttPServletResponse res)
throws Exception
{ package com.jlc.dev.util;
HttpSession
ses=req.getSession();
import java.sql.*;
if(ses!=null)
public class UserIdGenerator
{ {
ses.inValidate();
public static String getNextUserId()
} {
return
am.findForward("login");
String
uid=null;
} Connection con=null;
} PreparedStatement ps=null;
UserDAO.java
try
{
package com.jlc.dev.dao;
con=JdbcUtil.getMysqlConnection();
import com.jlc.dev.to.*;
ps=con.prepareStatement("select max(user_id) from user_table");
public interface UserDAO
ResultSet rs=ps.executeQuery();
{
if(rs.next())
public void addUser(UserTo uto) throws Exception;
{
public void verifyUser(String un,String pw)throws Exception;
String id=rs.getString(1);
public void forgotPassword(String em)throws Exception;
int x=Integer.parseInt(id.substring(3));
}
x=x+1;
uid="UID"+x;
}
else
UserIdGenerator.java
{
uid="UID00001";
}
}catch(Exception e)
{
System.out.println(e);
}
finally
{
JdbcUtil.cleanup(ps,con);
}
return uid;
Patni Confidential
}
}

UserNotFoundException.java
package com.jlc.dev.exceptions;
public class UserNotFoundException extends Exception
{
}
UserTo.java
package com.jlc.dev.to.*;
public class UserTo
{
String userid;
String fname;
String lname;
String email;
String phone;
String dob;
String username;
String password;
public void setDob(String dob)
{
this.dob=dob;
}
public String getDob()
{
return dob;
}

public String getLname()


{
return lname;
}
public void setEmail(String email)
{
this.email=email;
}
public String getEmail()
{
return email;
}
public void setPhone(String phone)
{
this.phone=phone;
}
public String getPhone()
{
return phone;
Patni Confidential

public void setUserId(String userid)


{
this.userid=userid;
}
public String getUserId()
{
return userid;
}
public void setFname(String fname)
{
this.fname=fname;
}
public String getFname()
{
return fname;
}
public void setLname(String lname)
{
this.lname=lname;
}

home.jsp

}
public void setUserName(String username)
{
this.username=username;
}
public String getUserName()
{
return username;
}
public void setPassword(String password)
{
this.password=password;
}
public String getPassword()
{
return password;
}

Tiles framework
Dev support

header.jsp

menu.jsp
welcome.jsp
footer.jsp

Change password
Update account
Post problems
Update problems
View all problems
View problems by date
View answer 4 problems
Logout

Welcome to JLC

Welcome to JSP

Dev support

* all right reserved

home.jsp
<table>
<tr>
<td colspan=2><jsp:include page=/home.jsp/>
</td>
</tr>
<tr>
<td width=20%<jsp:include page=/welcome.jsp/>
</td>
</tr>
<tr>
<td colspan=2><jsp:include page=/footer.jsp/>
</td>
</tr>
</table>
Patni Confidential

Above JSP is one solution to reuse the code in this JSP we are including four different JSPs:------- header.jsp
menu.jsp
footer.jsp
welcome.jsp
These four jsps are implemented separately and we will reuse this JSP in other JSP this kind of implementation
gives some problems.
Problem I :------- in this JSPs name are hard coded within the JSP.In future if the JSP
name are modify. you need to rename all other dependent JSP, this gives you
maintenance problem.
Problem II:------- when you design a layout or template with required styles, colors etc
you cant reuse the templates. you cant reuse the layout with above implementation
.you should use the template related code in all the JSPs.
To solve the above problem apache has introduced tiles framework.
Tiles framework can be integrated easily with web framework like struts, JSF etc.
Tiles framework is a separate framework which you have to integrate with other frame work explicitly.

Steps to integrate and use tiles framework with struts framework


Enable the tiles framework in struts framework by writing the following plug-in tag in
StrutsConfiguration file :----------<plug-in className=org.apache.struts.tiles.TilesPlugin>
<set property property=definitions-config value=WEB-INF/tiles.xml/> // here name of the xml file will be any thing

</plug-in>
Design the layout JSP which you want to use across the application.
Example :--------jlclayout.jsp
<%@ taglib uri=/WEB-INF/struts.tiles.tld prefix=tiles%>
<tiles:insert attribute=JLCHeader/></td>
<tiles:insert attribute=JLCMenu/></td>
<tiles:insert attribute=JLCBody/></td>
<tiles:insert attribute=JLCFooter/></td>
Write one definition in tiles.xml document for the home page and one more definition for password
change.
Example :-----<definition name=base path=/jlclayout.jsp>
<put name=JLCHeader value=/header.jsp/>
<put name= JLCMenu value=/menu.jsp/>
<put name= JLCFooter value=/footer.jsp/>
</definition>
<definition name=HomeDef extends=base>
<put name=JLCBody value=/welcom.jsp/>
</definition>
<definition name=CpDef extends=base>
<put name=JLCBody value=/cp.jsp/>
Patni Confidential

</definition>
Include the tiles definition in the JSPs
< %@taglib uri=/WEB-INF/struts-tiles.tld prefix=tiles%>
<tiles:insert definition=HomeDef/>
<tiles:insert definition=CpDef/>
Design the remaining JSPs required
Header.jsp
Footer.jsp
Menu.jsp
Welcome.jsp

Validation framework

(Not a part of struts framework)

When you are developing struts based application you may need to implement some code to validate the
input (incoming) data.
This we achieve by overriding validate() method and implemented the validation code inside the validate()
method
When you are developing multiple JSPs forms we need to overwrite validate() method multiple times
,sometimes you need to write same code repeatedly in every validate() method this gives the code
duplication.
This code duplication happens globally be cause every developer in every company has to write the
validation code to verify the input data.
To avoid this problem and to simplify the validation handling, Apache has introduced validation
framework.
Validation framework is not a part of struts frame work.
It should be integrated into the struts explicitly.
In validation framework apache has implemented some validation code for commonly requirement as
Listed below: --------------1)
2)
3)
4)
5)
6)
7)

required
minlength
maxlength
range
byte
float
double

8) email
9) date
10) credit card
11) short
12) integer
13) long

All the above validations are implemented in two ways: -------- Client side validation
Server side validation
Based on your requirement, you can invoke either client side validation or server side validation or
both.
Apache has implemented java script code for client side validation and java code for the server side
validation .
You can see the java script code implemented by apache and java class implemented inside the xml
file called validator_rules.xml.
Patni Confidential

Steps to integrate and use validation framework in struts framework

Write the following plug-in tag inside the struts configuration file to enable the validation framework in
struts.
<plug-in className=org.apache.struts.validator.validatorPlug-in>
<set property property=pathnames value=WEB-INF/validator-rules.xml,/WEB-INF/myvalidations.xml/>

</plug-in>
Write the jsp with form and decide the validations you wont to do on the fields and invoke the client side
validation or server side validation.
Example :------Cp.jsp
<html:form action=/passwordCharge>
<html:password property=cpword/><br>
<html:password property=cnpword/><br>
<html:submit value=change my password/>
<html:form>
<html:errors/>
Enable server side validation

<html:javaScript/>
display validation errors

client side validation

Write the following inside the struts configuration file.


<form-bean name=cpform type=org.apache.struts.validator..DynaValidatorForm>
<form-property name=cpword type=java.lang.string/>
<form-property name=cnpword type=java.lang.string/>
<form-property name=cnpword type=java.lang.String/>
</form-bean>
<action path=/password change name=cpform type=com.jlc.Action validate=true input=cp.jsp/>

Make sure that validator-rules.xml document is available in WEB-INF folder.

Identify the following modification.


actionFrame execute(-,-,-,-)
{
DynaValidatorForm dvf=( DynaValidatorForm)af;
Cp=dvf.get(cpword).toString();
----------------- -------------}
Add the following tags to myValidation.xml by specifying the validation required for the individual fields
of the cpform.
Example :---------<form-validation>
<formset>
<form name=cpform>
<field property=cpword depends=required>
<arg0 key=Current Password resource =flase/>

Patni Confidential

</field>
<field property=npword depends=required>
<arg0 key=cp.np/>
</field>
<field property=cnpword depends=required>
<arg0 key=cp.cnp/>
</field>
</form>
</formset>
</form-validation>

In application.properties
Errors.required={0} is required
Cp.np=new Password
Cp.cnp= Confirm new Password.

Example of validation using tiles framework


registerHome.jsp
Dev Support

Header.jsp

Registration form
Username
Password
Email
register.jsp

DOB
Phone
Credit card no.
Register

Footer.jsp

All right reserve

rajivsh101@gmail.com

How to write the custom Validation using validation framework in struts


Step I:---- Assume the field called UID in the form and also add <html:errors> to display the error
message
<tr>
</td>
<td>UserID</td>
<td>
<td>
<html:errors property=UserID/>
<html:text property =UserID/>
</td>
Step II:----- Add the validation tags inside validator-rules.xml for your custom validation.
<validator name=useridFormat classname=com.jlc.dev.JLCFieldchecks
Method =validateUseridFormat
Patni Confidential

methodParams=java.lang.object,org.apache.commons.validator.field,
org.apache.struts.action.ActionErrors,javax.servlet.http.HttpServletRequest depends=
msg=errors.useridFormat>
</validator>
Step III:------- Add one message in Application.properties file related to the custom validation.
Example :---errors.useridFormat=<font color=red size=4>{0} is invalid format(ex UID=1234)</font>
Step IV:------- Write the java class with the required method which is going to handle the corresponding
validation.
Example :------JLCFieldChecks.java
Step V:-------- Specify the implemented custom validation for the userid in myValidation.xml.
Example :----------<field property =userid depends=required,useridFormat
Arg0 key=UserID resource=false/>
</field>

register.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld"
prefix="html"%>
<html>
<body>
<h1>Register Form</h1>
<html:form action="/regsubmit">
<table>
<tr>
<td>User Id</td>
<td><html:text property="userid"/></td>
<td><html:errors property="userid"/></td>
</tr>
<tr>
<td>UserName</td>
<td><html:text property="username"/></td>
<td><html:errors property="username"/></td>
</tr>
<tr>
<td>Password</td>
<td><html:text property="password"/></td>
<td><html:errors property="password"/></td>
</tr>
<tr>
<td>Email</td>
<td><html:text property="email"/></td>
<td><html:errors property="email"/></td>
</tr>

<tr>
<td>DOB</td>
<td><html:text property="dob"/></td>
<td><html:errors property="dob"/></td>
</tr>
<tr>
<td>Phone</td>
<td><html:text property="phone"/></td>
<td><html:errors property="phone"/></td>
</tr>
<tr>
<td>CreditCard</td>
<td><html:text property="cc"/></td>
<td><html:errors property="cc"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<html:submit value="Register"/>
</td>
</tr>
</table>
</html:form>
</body>
</html>

Patni Confidential

<%@ taglib uri="/WEB-INF/struts-tiles.tld"


prefix="tiles"%>
<html>
<body>
<table>
<tr height="15%">
<td height="15%">
<tiles:insert attribute="jlcheader"/>
</td>
</tr>
Footer.jsp

jlclayout.jsp
<tr height="70%">
<td height="70%">
<tiles:insert attribute="jlcbody"/>
</td>
</tr>
<tr height="15%">
<td height="15%">
<tiles:insert attribute="jlcfooter"/>
</td>
</tr>
</table>
</body>
</html>

<font color="red" size="3">All &copy;Rights Reserved,&reg;devSupport&tm;.2008</font>


reghome.jsp
<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles"%>
<tiles:insert definition="regdef"/>
loghome.jsp
<%@ taglib uri="/WEB-INF/struts-tiles.tld"
prefix="tiles"%>
<tiles:insert definition="logdef"/>
Application.properties
errors.required=<font color=red size=4>{0}is required</font>
error.email=<font color=red size=4>{0}is invalid(ex.sd@sd.com)</font>
errors.creditcard=<font color=red size=4>{0}is invalid(must contains 16 digits)</font>
errors.date=<font color=red size=4>{0}is invalid format(ex.DD/MM/YY)</font>
errors.minlength=<font color=red size=4>{0}length must be minimum {1}
characters</font>
errors.maxlength=<font color=red size=4>{0}length must be maximum {2}
characters</font>
errors.range=<font color=red size=4>{0}length must be ranging from {1} to {2} </font>
errors.integer=<font color=red size=4>{0}is invalid</font>
errors.useridformat=<font color=red size=4>{0}is invalid format(ex.UID-1234)</font>
mytiles.xml

<tiles-definitions>
<definition name="basedef" path="/jlclayout.jsp">
<put name="jlcheader" value="/header.jsp"/>
<put name="jlcbody" value=""/>
<put name="jlcfooter" value="/footer.jsp"/>
</definition>
<definition name="regdef" extends="basedef">
<put name="jlcbody" value="/register.jsp"/>
</definition>
Patni Confidential

<definition name="logdef" extends="basedef">


<put name="jlcbody" value="/login.jsp"/>
</definition>
</tiles-definitions>
jlc.xml
<struts-config>
<form-beans>
<form-bean name="regform" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="userid" type="java.lang.String"/>
<form-property name="username" type="java.lang.String"/>
<form-property name="password" type="java.lang.String"/>
<form-property name="email" type="java.lang.String"/>
<form-property name="dob" type="java.lang.String"/>
<form-property name="phone" type="java.lang.String"/>
<form-property name="cc" type="java.lang.String"/>
</form-bean>
</form-beans>
<global-forwards>
<forward name="loghome" path="/loghome.jsp"/>
</global-forwards>
<action-mappings>
<action path="/regsubmit" name="regform"
type="com.jlc.dev.RegisterAction"
validate="true" input="/reghome.jsp"/>
</action-mappings>
<message-resources parameter="com.jlc.dev.Application"/>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEBINF/myvalidations.xml"/>
</plug-in>
<plug-in className="org.apache.struts.tiles.TilesPlugIn">
<set-property property="definitions-config" value="/WEB-INF/mytiles.xml"/>
</plug-in>
</struts-config>
</plug-in>

Web.xml
<servlet>
<servlet-name>action</servlet-name>
<servletclass>org.apache.struts.action.ActionServlet</servletclass>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/manish.xml</paramvalue>
</init-param>

<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>

Patni Confidential

<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>

</servlet-mapping>
</web-app>

myvalidation.xml
<form-validation>
<formset>
<form name="regform">
<field property="userid"
depends="required",useridformat">
<arg0 key='User ID" resource="false"/>
</field>
<field property="username"
depends="required,minlength,maxlength">
<arg0 key="UserName" resource="false"/>
<arg1 key="${var:minlength}" resource="false"/>
<arg2 key="${var:maxlength}" resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>4</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>7</var-value>
</var>
</field>
<field property="password"
depends="required,minlength,maxlength">
<arg0 key="Password" resource="false"/>
<arg1 key="${var:minlength}" resource="false"/>
<arg2 key="${var:maxlength}" resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>4</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>7</var-value>
</var>
</field>

<field property="email"
depends="required",email">
<arg0 key='Email ID" resource="false"/>
</field>
<field property="dob" depends="required",date">
<arg0 key='DOB" resource="false"/>
<var>
<var-name>datePattern</var-name>
<var-value>dd/mm/yyyy></var-value>
</var>
</field>
<field property="phone"
depends="required,integer,intRange">
<arg0 key="phone" resource="false"/>
<arg1 name="intRange" key="${var:minlength}"
resource="false"/>
<arg2 name="intRange" key="${var:maxlength}"
resource="false"/>
<var>
<var-name>minlength</var-name>
<var-value>99</var-value>
</var>
<var>
<var-name>maxlength</var-name>
<var-value>9999</var-value>
</var>
</field>
<field property="cc"
depends="required,creditCard">
<arg0 key='Credit Card Number" resource="false"/>
</field>
</form>
</formset>
</form-validation>

RegisterAction.java
package com.jlc.dev;
import java.util.Date;
import org.apache.struts.action.*;
import org.apache.struts.validator.DynaValidatorForm;
import javax.servlet.http.*;
public class RegisterAction extends Action
{
public ActionForward execute(ActionMapping

DynaValidatorForm df=(DynaValidatorForm)af;
String un=df.get("username").toString();
String pw=df.get("password").toString();
String em=df.get("email").toString();
String dob=df.get("dob").toString();
String ph=df.get("phone").toString();
String cc=df.get("cc").toString();

Patni Confidential

am,ActionForward af,HttpServletRequest
req,HttpServletResponse res)
throws Exception
{

System.out.println(un);
System.out.println(pw);
System.out.println(em);
System.out.println(dob);
System.out.println(ph);
System.out.println(cc);
return am.findForward("loghome");
}
}

JlcFieldChecks.java
package com.jlc.dev.validator;
import javax.servlet.http.*;
import org.apache.commons.validator.*;
import org.apache.struts.action.*;
public class JlcFieldChecks
{
public static boolean validateUseridFormat(Object bean,ValidatorAction va,Field field,ActionErrors
errors,HttpServletRequest req)
{
String uid=request.getParameter('userid");
try
{
if(uid!=null||uid.length()!=0)
{
String p1=uid.substring(0,4);
String p2=uid.substring(4);
if(p1.equals("UID-"))
{
int id=Integer.parseInt(p2);
if(p2.length()==4)
{
return true;
}
else
{
errors.add("userid",new ActionError("errors.useridformat"));
return false;
}
}
else
{
errors.add("userid",new ActionError("errors.useridformat"));
return false;
}
}
}catch(Exception e)
register.jsp
{
jlclayout.jsp
errors.add("userid",new ActionError("errors.useridformat"));
Footer.jsp
return false;
}
reghome.jsp
return false;
loghome.jsp
}
}

Application.properties
mytiles.xml
jlc.xml
Web.xml
Confidential
Patni
myvalidation.xml
RegisterAction.java
JlcFieldChecks.java

Files required

Patni Confidential