Struts

adplus-dvertising
Application- 8 : Creating a Login Application with DynaActionForm in Struts
Previous Home Next

In this chapter, you create a very simple application for the purpose of Calculated Day in a week with Struts from start to end. For each piece of the application, we show you the code and then explain the code. This application design in NetBeans IDE- 6.8 with Struts 1.3.

Requirement for your struts application-

  • At least one view component is required in every Application.
  • A subclass of ActionForm is used to submit the date as application needed.
  • A subclass of Action class which provide specific processing functionality for the application.
  • A web.xml file is required for calling ActionServlet and struts-config.xml.
  • A struts-config.xml file is required for updating and mapping the update.

Let's Start the application, this application provide a good understanding how struts framework works and also understanding the development of Struts applications

Now, Following the some steps for develop your first application name as computeDay. computeDay application contain following page-

  • Three View file name as index.jsp, register.jsp and success.jsp
  • One JavaBeans file name as computeForm.java, used for store data as application need.
  • one Action file name as computeAction.java, used for provide specific processing functionality.
  • Two XML file name as web.xml and struts-config.xml file, used for provide control, mapping and validation in application.

Step- 1 : Start your IDE ( NetBeans 6.8 with struts 1.3).

Step- 2 : Open a new project( Crtl+Shift+N), name it , add server( Apache Tomcat 6.0.20 ), then add struts framework 1.3 , and don't forget to add Struts TLDs.

When you click Finish button, your NetBeans IDE configure everything in place and project open in your IDE.

Step- 3: Open index.jsp page, from your struts application and code it as describe below.

<%--  Document : index.jsp
Description  : First Page of DynaFormLogin Application--%>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean"
prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" 
prefix="html" %>
<html:html lang="true">
<head>
<meta http-equiv="Content-Type" content="text/html
; charset=UTF-8">
<title><bean:message key="welcome.title"/></title>
<html:base/>
</head>
<body style="background-color: white">
<html:form action="/login" >
<h3><bean:message key="welcome.heading"/></h3>
<p><bean:message key="welcome.message"/></p>
<html:errors />
<ul>
<table border="0" cellspacing="4" cellpadding="4">
<tbody>
<tr>
<td><bean:message key="welcome.userName"/></td>
<td><html:text property="LoginName" size="25"
maxlength="15" /></td>
</tr>
<tr>
<td><bean:message key="welcome.password"/></td>
<td><html:password property="LoginPassword" size="25"
maxlength="15" /></td>
</tr>
<tr>
<td align="center"><html:submit value=" Check Login " />
</td>
<td align="center"><html:reset value=" Reset " />
</td>
</tr>
</tbody>
</table>
</ul>
<ul>
<hr size="+2" width="80%" style="color: blue">
<BR>
<p><font face="Arial"> New User please regiset
yourself first by
<html:link style="cursor: auto;color: green" 
forward="register"> Click Here</html:link></font></p>
</ul>
</html:form>
</body>
</html:html>

Step- 4: Open register.jsp page from your struts application and code it as describe below.

<%--  Document : register.jsp
Description  : Second Page of DynaFormLogin
Application--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://struts.apache.org/tags-html"
prefix="html" %>
<%@taglib uri="http://struts.apache.org/tags-bean" 
prefix="bean" %>
<html>
<head>
<meta http-equiv="Content-Type" 
content="text/html; charset=UTF-8">
<title>Register Page</title>
</head>
<body>
<html:form action="/register">
<h1><bean:message key="welcome.heading" /></h1>
<html:errors />
<table border="0" cellspacing="4" cellpadding="4">
<tbody>
<tr>
<td><bean:message key="welcome.userName" /></td>
<td><html:text property="RegUserName" size="25" 
maxlength="15" /></td>
</tr>
<tr>
<td><bean:message key="welcome.password" /></td>
<td><html:password property="RegPassword" size="25"
maxlength="15" /></td>
</tr>
<tr>
<td><bean:message key="welcome.name" /></td>
<td><html:text property="RegName" size="25" 
maxlength="15" /></td>
</tr>
<tr>
<td><bean:message key="welcome.number" /></td>
<td><html:text property="RegNumber" size="25" 
maxlength="15" /></td>
</tr>
<tr>
<td><bean:message key="welcome.email" /></td>
<td><html:text property="email" size="25" 
maxlength="25" /></td>
</tr>
<tr>
<td align="center"><html:submit value=" Register " /></td>
<td align="center"><html:reset value=" Reset " /></td>
</tr>
</tbody>
</table>
</html:form>
</body>
</html>

Step- 5: Open success.jsp page from your struts application and code it as describe below.

<%--  Document : success.jsp
Description  : Third Page of DynaFormLogin
Application--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="http://struts.apache.org/tags-bean" 
prefix="bean" %>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Success Page</title>
</head>
<body>
<h2>Congratulations! You have successfully logged in </h2>
<b> Your Detail here:</b>
<ul>
<table border="0" cellspacing="4" cellpadding="4">
<tbody>
<tr>
<td> UserName:</td>
<td><b><bean:write name="RegisterForm" 
property="RegUserName" /></b> </td>
</tr>
<tr>
<td> Password:</td>
<td><b><bean:write name="RegisterForm" 
property="RegPassword" /></b> </td>
</tr>
<tr>
<td> Name:</td>
<td><b><bean:write name="RegisterForm"
property="RegName" /></b> </td>
</tr>
<tr>
<td> Number:</td>
<td><b><bean:write name="RegisterForm"
property="RegNumber" /></b> </td>
</tr>
<tr>
<td> Email-ID:</td>
<td><b><bean:write name="RegisterForm"
property="email" /></b> </td>
</tr>
</tbody>
</table>
</ul>
<ul>
<p>Return to <a style="cursor: auto" 
href="index.jsp">home page</a></p>
</ul>
</body>
</html>

Step- 6: Open web.xml file place in WEB-INF folder, this file is used to map the ActionServlet( work as backbone of application, every Action, Validation and ActionForm class control by this class) , struts-config.xml file, welcome file and five different TagLibrary.

<!-- Save as a web.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
<!-- ActionServlet map here, however you can't find 
this class within the project but it work as a backbone
of the project -->
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action
.ActionServlet</servlet-class>
<!-- Your struts-config.xml file map here-->
<init-param>
    <param-name>config</param-name>
    <param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
    <param-name>debug</param-name>
    <param-value>2</param-value>
</init-param>
<init-param>
    <param-name>detail</param-name>
    <param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
    </servlet>
<!-- Action class map with URL -->
    <servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <session-config>
<session-timeout>
    30
</session-timeout>
    </session-config>
<!-- Welcome file map here: -->
    <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <jsp-config>
<!-- All the Tag Library which used with in the project -->
<taglib>
    <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-bean.tld
    </taglib-location>
</taglib>
<taglib>
    <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-html.tld
    </taglib-location>
</taglib>
<taglib>
    <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-logic.tld
    </taglib-location>
</taglib>
<taglib>
    <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-nested.tld
    </taglib-location>
</taglib>
<taglib>
    <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
    <taglib-location>/WEB-INF/struts-tiles.tld
        </taglib-location>
</taglib>
    </jsp-config>
</web-app>

Step- 7: Open struts-config.xml file place in WEB-INF folder, this file is used to map Model class, Exception class, Validation class, Action class( Action class further choose View class) and ApplicationResource class

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation
//DTD Struts Configuration 1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
  <!-- DynaActionForm is flexible dynamic sets of properties -->
<form-bean name="RegisterForm" type="org.apache
.struts.action.DynaActionForm" >
<form-property name="LoginName" type="java.lang.String" />
<form-property name="LoginPassword" type="java.lang.String" />
<form-property name="RegUserName" type="java.lang.String" />
<form-property name="RegPassword" type="java.lang.String" />
<form-property name="RegName" type="java.lang.String" />
<form-property name="RegNumber" type="java.lang.Integer" />
<form-property name="email" type="java.lang.String" />
</form-bean>
</form-beans>
<global-exceptions>
</global-exceptions>
<global-forwards>
<!--  file call by <http:link forward /> -->
<forward name="register" path="/register.jsp"/>
</global-forwards>
 <!-- All Action class, Bean class,
 Forward Action  map here-->
<action-mappings>
<action input="/register.jsp" name="RegisterForm" 
path="/register" scope="session"
type="r4r.struts.RegisterAction">
<forward name="success" path="/index.jsp"/>
<forward name="failure" path="/register.jsp"/>
</action>
<action input="/index.jsp" name="RegisterForm" 
path="/login" scope="session" type="r4r.struts.LoginAction">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/index.jsp"/>
</action>
</action-mappings>
<controller processorClass="org.apache.struts
.tiles.TilesRequestProcessor"/>
<message-resources parameter="com/myapp/struts
/ApplicationResource"/>
<!-- ========== Tiles plugin ==========-->
  <plug-in className="org.apache.struts.tiles.TilesPlugin" >
<set-property property="definitions-config"
value="/WEB-INF/tiles-defs.xml" />
<set-property property="moduleAware" value="true" />
</plug-in>
<!-- ========= Validator plugin ========== -->
<plug-in className="org.apache.struts
.validator.ValidatorPlugIn">
<set-property
property="pathnames"
value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>

Step- 8: Now introduce Bean class into struts-config.xml file, Since in this application we used DyanActionForm which provide dynamic bean property in struts application, so no need to define another class for bean. As we mention the property into DyanActionForm into struts-config.xml file and call there property with in appliccation by making instance of DynaActionForm.

Step- 9: Since, application contain two different JSP page, hence two Action( or execute method) class required. So, the class are-

First class named as a RegisterAction.java, which call by register.jsp page.

/* Save as a RegisterAction.java */
package r4r.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.DynaActionForm;
public class RegisterAction extends org.apache
.struts.action.Action {
/* forward name="" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
/* This is the action called from the Struts framework.
 * @return
 */
@Override
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionErrors errors = new ActionErrors();
//Make the instance of DynaActionForm Here
DynaActionForm actionForm = (DynaActionForm) form;
/* ---- Call the property from DynaActionForm ---- */
String RegUserName = (String) actionForm.get("RegUserName");
String RegPassword = (String) actionForm.get("RegPassword");
String RegName = (String) actionForm.get("RegName");
String email = (String) actionForm.get("email");
int RegNumber = (Integer) actionForm.get("RegNumber");
/*----- Set up validation into register.jsp page -- */
if (RegUserName == null || RegUserName.length() < 1) {
errors.add("RegUserName", new ActionMessage("error.userName"));
}
if (RegPassword == null || RegPassword.length() < 1) {
errors.add("password", new ActionMessage("error.password"));
}
if (RegName == null || RegName.length() < 1) {
errors.add("RegName", new ActionMessage("error.RegName"));
}
if (email.equals("") || email.indexOf('@') == -1 ||
email.indexOf('.') == -1
|| email.indexOf("@@") != -1 || email.indexOf("..") != -1) {
errors.add("email", new ActionMessage("error.email"));
}
if (RegNumber == 0) {
errors.add("RegNumber", new ActionMessage("error.RegNumber"));
}
//Save the specified error messages in HTTP request attribute
saveErrors(request, errors);
if (errors.isEmpty()) {
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}

Second class named as a LoginAction.java ,which call by index.jsp page.

/* Save as a LoginAction.java */
package r4r.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.DynaActionForm;
public class LoginAction extends org.apache
.struts.action.Action {
/* forward name="" path="" */
private static final String SUCCESS = "success";
private static final String FAILURE = "failure";
/* This is the action called from the Struts framework.
 * @return
 */
@Override
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionErrors errors = new ActionErrors();
//DynaActionForm call here
DynaActionForm actionForm = (DynaActionForm) form;
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
/* --- index.jsp page property ---  */
String LoginName = (String) actionForm.get("LoginName");
String LoginPassword = (String) actionForm
.get("LoginPassword");
/* --- Register.jsp page property ---  */
String RegUserName = (String) actionForm.get("RegUserName");
String RegPassword = (String) actionForm.get("RegPassword");
/*----- Set up validation into index.jsp page -- */
if (LoginName == null || LoginName.length() < 1) {
errors.add("RegUserName", new ActionMessage("error.userName"));
}
if (LoginPassword == null || LoginPassword.length() < 1) {
errors.add("password", new ActionMessage("error.password"));
}
//Save the specified error messages in HTTP request attribute
saveErrors(request, errors);
if (errors.isEmpty()) {
flag1 = true;
} else {
flag1 = false;
}
//Match the Data from two different Pages
if (LoginName.equals(RegUserName)) {
flag2 = true;
} else {
errors.add("userMatch", new ActionMessage("error.userMatch"));
if (errors.size() != 0) {
saveErrors(request, errors);
}
}
if (LoginPassword.equals(RegPassword)) {
flag3 = true;
} else {
errors.add("passMatch", new ActionMessage("error.passMatch"));
if (errors.size() != 0) {
saveErrors(request, errors);
}
}
//Checking flags condition
if (flag1 == true && flag2 == true && flag3 == true) {
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}

Run your application:

Now your application is complete, so now start run your application. Start your server( which you embedded when configure our struts application), then right click your application and click upon Run option or open your welcome( index.jsp) page and press shift+F6.

Previous Home Next