} } }
// field name: password // field name: password
// validator name: requiredstring // validator name: requiredstring if (form.elements['password']) { if (form.elements['password']) { field =
field = form.elements[form.elements['password'];'password'];
var error = "Password is required";
var error = "Password is required";
if (field.value != null && (field.value == ""
if (field.value != null && (field.value == "" || field.value.replace(/^\|| field.value.replace(/^\s+|\s+$/g,"").length == 0)) {s+|\s+$/g,"").length == 0)) { addError(field, error);
addError(field, error);
errors = true;
errors = true;
} } } }
return !errors;
return !errors;
} }
</script>
</script>
</body>
</body>
</html>
</html>
In the above code you can see the JavaScript code and function In the above code you can see the JavaScript code and function
validateForm_doLoginClientSideValidation()
validateForm_doLoginClientSideValidation()which is generated for client side validationwhich is generated for client side validation
V
V alidations alidations using using Struts Struts 2 Annotations 2 Annotations
Validating Struts 2 Login Application using Annotations Validating Struts 2 Login Application using Annotations In this section we are going
In this section we are going to validate our login application using Anto validate our login application using Annotations in Actionnotations in Action class. Our current login application does n
class. Our current login application does not validate the user against the database.ot validate the user against the database.
Instead login name and passwords are validated against the hardcode values (User:
Instead login name and passwords are validated against the hardcode values (User:
Admin
Admin and Password:and Password: Admin Admin) in the actions class.) in the actions class.
Working of the application Working of the application
1.
1. LogLogin pagin page is die is displsplayeayed to takd to take the ie the inputnputs.s.
2.
2. User eUser enters nters user nauser name and pame and passworssword and thed and then clicn clicks on the "ks on the "Login" bLogin" buttonutton.. 3.
3. User vaUser validatlidation is done iion is done in action cln action class and if uass and if user entser enters Admers Admin/Adin/Admin in the usmin in the user er name/password fields, then success pages is displayed. Otherwise the error
name/password fields, then success pages is displayed. Otherwise the error message is displayed on the screen.
message is displayed on the screen.
Steps to develop the application Steps to develop the application Here are simple and easy steps to
Here are simple and easy steps to develop Login page in develop Login page in the using Struts 2 framework.the using Struts 2 framework.
1.
1. Develop Login FormDevelop Login Form
The GUI of the application consists of login form (
The GUI of the application consists of login form (log-in.jsplog-in.jsp) and success) and success message page (
message page (loginsuccess.jsploginsuccess.jsp) .) . The
The log-in.jsplog-in.jsp is used to display the login page is used to display the login page to the user. In our application it to the user. In our application it isis saved in "webapps\struts2tutorial\pages\" folder. Here is the code of
saved in "webapps\struts2tutorial\pages\" folder. Here is the code of log-in.jsplog-in.jsp file:
file:
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<html>
<head>
<head>
<title>Struts 2 Login A
<title>Struts 2 Login Application!</title>pplication!</title>
<link href="<s:url value="
<link href="<s:url value="/css/main.css/css/main.css"/>" rel="stylesheet" type="text/css"/>"/>" rel="stylesheet" type="text/css"/>
</head>
</head>
<body>
<body>
<s:form action="AnnotationAction" method="POST" validate="true">
<s:form action="AnnotationAction" method="POST" validate="true">
<tr>
<tr>
<td colspan="2">
<td colspan="2">
Login Login
</td>
</td>
</tr>
</tr>
<tr>
<tr>
<td colspan="2">
<td colspan="2">
<s:actionerror />
<s:actionerror />
<s:fielderror />
<s:fielderror />
</td>
</td>
</tr>
</tr>
<s:textfield name="username" label="Login name"/>
<s:textfield name="username" label="Login name"/>
<s:password name="password" label="Password"/>
<s:password name="password" label="Password"/>
<s:submit value="Login" align="center"/>
<s:submit value="Login" align="center"/>
</s:form>
</s:form>
</body>
</body>
</html>
</html>
2.
2. The code :The code :
<s:actionerror />
<s:actionerror />
<s:fielderror />
<s:fielderror />
displays action errors and field validation errors.
displays action errors and field validation errors.
3.
3. The codeThe code<s:form action="AnnotationAction" method="POST"<s:form action="AnnotationAction" method="POST"
validate="true">
validate="true"> generates the html form for the application.generates the html form for the application.
The code : The code :
<s:textfield name="username" label="Login name"/>
<s:textfield name="username" label="Login name"/>
<s:password name="password" label="Password"/>
<s:password name="password" label="Password"/>
generates Login Name and
generates Login Name and Password fields.Password fields.
4.
4. The submit button is generated throughThe submit button is generated through<s:submit value="Login"<s:submit value="Login"
align="center"/>
align="center"/> code.code.
The
The loginsuccess.jsploginsuccess.jsp page displays the Login Success message when user ispage displays the Login Success message when user is authenticated successfully. Here is the code of
authenticated successfully. Here is the code of loginsuccess.jsploginsuccess.jsp file:file:
<html>
<html>
<head>
<head>
<title>
<title>Login SuccessLogin Success</title></title>
</head>
</head>
<body>
<body>
<p align=
<p align="center""center"><font color=><font color="#000080""#000080"size=size="5""5">>LoginLogin Successful
Successful</font></p></font></p>
</body>
</body>
</html>
</html>
5.
5.
6.
6. Developing Action class (Developing Action class (using Annotations to using Annotations to validate Login forms)validate Login forms) Now let's develop the action class
Now let's develop the action class to handle the login request. The to handle the login request. The Struts 2Struts 2 framework provides a base ActionSupport class to implement
framework provides a base ActionSupport class to implement commonly usedcommonly used interfaces. In our action class (
interfaces. In our action class ( AnnotationAction AnnotationAction.java.java) we have extended) we have extended ActionSupport
ActionSupport class and imported theclass and imported the
com.opensymphony.xwork2.validator.annotations package com.opensymphony.xwork2.validator.annotations package ..
For validating the login application java script can be added to the jsp page or in For validating the login application java script can be added to the jsp page or in action class, but Struts 2 provides another very easy
action class, but Struts 2 provides another very easy method to validate your formmethod to validate your form fields using annotations in the action class.
fields using annotations in the action class.
Two annotations are needed, Two annotations are needed, 1. The
1. The@Validation@Validation annotationannotation tell Struts that action in this class might need totell Struts that action in this class might need to be validated.
be validated.
2. The
2. The@RequiredStringValidator annotation@RequiredStringValidator annotation is used for the text input to holdis used for the text input to hold a singular value.
a singular value.
Rest of the care is taken by the framework.
Rest of the care is taken by the framework.
Our "
Our "AnnotationActionAnnotationAction" " class is class is saved in the saved in the "webapps\struts2tutorial\W"webapps\struts2tutorial\WEB- EB-INF\src\java\net\roseindia" directoy. Here is the code of
INF\src\java\net\roseindia" directoy. Here is the code of AnnotationActionAnnotationAction.java.java action class:
action class:
In this class we will write the code to validate
In this class we will write the code to validate the login page.the login page.
AnnotationAction
AnnotationAction..javajava package
package net.roseindia;net.roseindia;
import
import com.opensymphony.xwork2.ActionSupport;com.opensymphony.xwork2.ActionSupport;
import
import com.opensymphony.xwork2.validator.annotations.*;com.opensymphony.xwork2.validator.annotations.*;
@Validation
@Validation public class
public class AnnotationActionAnnotationAction extendsextends ActionSupport {ActionSupport {
private
private String username =String username = nullnull;; private
private String password =String password = nullnull;;
@RequiredStringValidator(message="Supply name")
@RequiredStringValidator(message="Supply name") public
public String getUsername() {String getUsername() { return
return username;username;
} }
public void
public void setUsername(String value) {setUsername(String value) {
username = value;
username = value;
} }
@RequiredStringValidator(message="Supply password")
@RequiredStringValidator(message="Supply password")
public
public String getPassword() {String getPassword() { return
return password;password;
} }
public void
public void setPassword(String value) {setPassword(String value) { password = value;
password = value;
} }
public
public String execute()String execute() throwsthrows Exception {Exception { System.out.println(
System.out.println( "Validating login""Validating login"););
if
if(!getUsername().equals((!getUsername().equals( "Admin""Admin") || !getPassword().equals() || !getPassword().equals( "Admin""Admin")){)){
addActionError(
addActionError( "Invalid user name or password! Please try again!""Invalid user name or password! Please try again!"););
return
return ERROR;ERROR;
} } else else{{
return
return SUCCESS;SUCCESS;
} } } } } }
1.
1. Configuring action mapping (in struts.xml)Configuring action mapping (in struts.xml) Now we will create action mapping
Now we will create action mapping in the struts.xml file. Here is the code to in the struts.xml file. Here is the code to bebe added in the struts.xml:
added in the struts.xml:
<action name="LoginAnnotation">
<action name="LoginAnnotation">
<result>/pages/log-in.jsp</result>
<result>/pages/log-in.jsp</result>
</action>
</action>
<action name="AnnotationAction"
<action name="AnnotationAction"
class="net.roseindia.AnnotationAction">
class="net.roseindia.AnnotationAction">
<result name="input">/pages/log-in.jsp</result>
<result name="input">/pages/log-in.jsp</result>
<result name="error">/pages/log-in.jsp</result>
<result name="error">/pages/log-in.jsp</result>
<result>/pages/loginsuccess.jsp</result>
<result>/pages/loginsuccess.jsp</result>
</action>
</action>
2.
2. In the above mapping In the above mapping the action "LoginAnnotation" is used to the action "LoginAnnotation" is used to display the logindisplay the login page and "AnnotationAction" validates the user using action class
page and "AnnotationAction" validates the user using action class (
(AnnotationActionAnnotationAction.java)..java).
3.
3. CSS file (main.css)CSS file (main.css)
This css file is used to enhance the
This css file is used to enhance the presentation of the login form. Thepresentation of the login form. Themain.cssmain.css isis saved into
saved into "\webapps\struts2tutorial\"\webapps\struts2tutorial\css" directory.css" directory.
Here is the code of
Here is the code of main.cssmain.css::
@CHARSET "UTF-8";
@CHARSET "UTF-8";
body { body {
font: 12px verdana, arial, helvetica, sans-serif;
font: 12px verdana, arial, helvetica, sans-serif;
background-color:#FFFFFF;
font: 12px verdana, arial, helvetica, sans-serif;
font: 12px verdana, arial, helvetica, sans-serif;
border-width: 1px;
table.wwFormTable tr td { table.wwFormTable tr td { background-color: #dfd;
}
border-width: 1px 1px 0px;
border-width: 1px 1px 0px;
border-color: black;
/* margin-bottom: 12px; */
/* margin-bottom: 12px; */
} }
#buttonBar {
#buttonBar {
border-width: 0px 1px 1px;
border-width: 0px 1px 1px;
border-style: solid;
#menuContainer {
#menuContainer { float: left;
float: left;
} }
#brandingContainer {
#brandingContainer { float: right:
float: right:
text-align: right;
text-align: right;
} }
Compiling the application Compiling the application To compile the application g
To compile the application go to "\webapps\struts2tutorial\WEB-INF\sro to "\webapps\struts2tutorial\WEB-INF\src" directory andc" directory and type ant command. The ant tool will compile the application for you.
type ant command. The ant tool will compile the application for you.
Adding the link into index.shtml Adding the link into index.shtml Finally we have to add
Finally we have to add the link in the index.html to the link in the index.html to access the login form.access the login form.
<ul>
<ul>
<li><a href="roseindia/LoginAnnotation.action">Action Annotation Example</a></li>
<li><a href="roseindia/LoginAnnotation.action">Action Annotation Example</a></li>
</ul>
</ul>
Output:
Output:
If you click Login button without filling the fields , you will get
If you click Login button without filling the fields , you will get the output pages as :the output pages as :
If you fill only
If you fill only the "Login name" the "Login name" field and field and click Login button without filling theclick Login button without filling the next fields, you
next fields, you will get will get the output pages the output pages as :as :
If you
If you fill fill the the wrong wrong information information and and click the click the Login Login button , button , you you will get will get thethe output pages as :
output pages as :
If you
If you fill fill the the correct information correct information and and click the click the Login Login button , button , you you will will get get thethe output pages as :
output pages as :
Strut
Struts 2 T s 2 T ags ags
In this section we will introduce you with the
In this section we will introduce you with the tags provided along withtags provided along withStruts 2Struts 2 framework. It is necessary to understand all the tags provided along with Struts 2 framework. It is necessary to understand all the tags provided along with Struts 2 framework. In this page we will have listed all the
framework. In this page we will have listed all the Struts 2 TagsStruts 2 Tags and in subsequentand in subsequent sections we will provide you the examples
sections we will provide you the examples of the these tags in detail.of the these tags in detail.
The Struts 2 Tags can be divided into two types:
The Struts 2 Tags can be divided into two types:
•
• Struts Generic TagsStruts Generic Tags
The struts generic tags are used to control the execution flow when pages are The struts generic tags are used to control the execution flow when pages are rendered. Another use of struts generic tags are data extraction.
rendered. Another use of struts generic tags are data extraction.
Further Generic Tags are classified into
Further Generic Tags are classified intoControl TagsControl Tags andandData TagsData Tags.. Control Tags:
Control Tags: The Control Tags are used The Control Tags are used for flow control, such if, else andfor flow control, such if, else and iterate.
iterate.
Here are the list of Control Tags:
Here are the list of Control Tags:
* if
Data Tags: The Data Tags are used for data manipulation or creation, such asThe Data Tags are used for data manipulation or creation, such as bean, push, and i18n.
bean, push, and i18n.
Here are the list of Data Tags:
Here are the list of Data Tags:
* a
• Struts UI tagsStruts UI tags
Struts UI Tags are mainly designed to use the
Struts UI Tags are mainly designed to use the data from your action/value stack or data from your action/value stack or from Data Tags. These tags are used to display the data on the HTML page. The from Data Tags. These tags are used to display the data on the HTML page. The UI tags are driven by templates and themes.
UI tags are driven by templates and themes.
Struts UI Tags are of two types Form Tags and
Struts UI Tags are of two types Form Tags and Non - Form tags.Non - Form tags.
Form Tags are as follows:
Form Tags are as follows:
* autocompleter
Non-Form UI Tags are:
Non-Form UI Tags are:
* actionerror
The main difference between
The main difference betweenStruts Generic TagsStruts Generic Tags andand Struts UI TagsStruts UI Tagsare:are:
•
• The generic tags simply output some content The generic tags simply output some content directly from the tag while the UIdirectly from the tag while the UI tags uses templates and often group the output together with theme
tags uses templates and often group the output together with theme