Struts

adplus-dvertising
Application-2 : Creating a Simple Login Application with Struts
Previous Home Next

In this chapter, we have create a very simple Login application, user can be login( provide own detail) which store into JavaBean Class and retrieve into another file. 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.

Now, Following the following steps for develop your second application name as strutsLogin. strutsLogin application contain following page-

  • Four View file name as index.jsp, welcomeStruts.jsp, LoginForm.jsp and success.jsp
  • One JavaBeans file name as LoginForm.java, used for store data as application need.
  • one Action file name as LoginAction.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 new project (Ctrl+shift+N) --> select Java web( from choose Project) --> select web application (from project) and click on Next button, as describe below

Step- 3: Name your project and click to the next button --> Next window appear Add server click Next Button --> Finally, add struts framework 1.3, automatic configure your action class and ApplicationResource( also called resource bundle) , and don't forget to add Struts TLDs ( struts five different Taglibrary) as describe below

Note:-When you click Finish button, NetBeans IDE put and configure everything in place. Next image show below same file open in your IDE which contain five all necessary class required in application.

Step- 4: index.jsp file is automatic configure to global- forward the request to welcomeStruts.jsp file so no need to code that file.

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

<%-- Document: welcomeStruts.jsp
  Description : Second Page of 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">

<h3><bean:message key="welcome.heading"/></h3>
<p><bean:message key="welcome.message"/></p>
<ul>
<p><html:image src="http://r4r.co.in/images/logo.jpg" /> 
Welcome to <a href="http://r4r.co.in"> R4R Tech Soft</a></p>
<BR>
	<!-- Link provide for direct call LoginForm.jsp page -->
<p>Please <a href="LoginForm.jsp"> Sign In</a> ,
to fill the Application Form</p>
</ul>
</body>
</html:html>

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

<%-- Document: LoginForm.jsp
Description : Third Page of Login 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:html xhtml="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LoginForm</title>
</head>
<body style="background-color: white ">
<html:form method="post" action="/login" >
<h1>Struts Login !Login Form</h1>
<html:errors property="name"/>
<br><bean:message key="welcome.name" /> <br>
<html:text property="name" maxlength="14" />
<html:errors property="password"/>
<br><br> <bean:message key="welcome.password" /> <br>
<html:password property="password" maxlength="10" />
<html:errors property="age"/>
<br><br> <bean:message key="welcome.age" /> <br>
<html:text property="age"  maxlength="2" />
<html:errors property="Email"/>
<br><br> <bean:message key="welcome.email" /> <br>
<html:text property="email" />
<br><br> <html:submit property="submit" value=" Login " />
&nbsp;&nbsp; <html:button property="reset" value=" Reset " />
</html:form>
</body>
</html:html>

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

<%--  Document: success.jsp
Description : Fourth Page of Login Application
--%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@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">
<html:html xhtml="true">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success Login</title>
</head>
<body>
<h1>Congratulations! You have successfully logged in </h1>
	<!-- Value retrive form Beans -->
<ul>
<p>Name:<strong> <bean:write name="LoginForm" 
property="name"/></strong> </p>
<p>Password:<strong>  <bean:write name="LoginForm" 
property="password"/> </strong> </p>
<p>Age: <strong>  <bean:write name="LoginForm" 
property="age"/></strong> </p>
<p>E-mail Id: <strong>  <bean:write name="LoginForm" 
property="email"/> </strong> </p>
</ul>
<BR><B>Thanks for registration</B>
<ul>
	<!-- Link provide for direct call index.jsp page -->
<p> Return to <a href="index.jsp"> Home </a> page</p>
</ul>
</body>
</html:html>

Step- 8: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- 9: 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.

<!--Saveasastruts-config.xml-->
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstruts-configPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
<struts-config>
<!--BeanClassmaphere:-->
<form-beans>
<form-beanname="LoginForm"type="com.myapp.struts.LoginForm"/>
</form-beans>
<global-exceptions>
</global-exceptions>
<!--index.jspfileusedthisglobalforwadtofindwelcome
.jsppageformactionclass-->
<global-forwards>
<forwardname="welcome"path="/Welcome.do"/>
</global-forwards>
<!--alltheactionrelativestuffmaphere:-->
<action-mappings>
<actioninput="/LoginForm.jsp"name=
"LoginForm"path="/login"scope="request"type=
"com.myapp.struts.LoginAction">
<forwardname="success"path="/success.jsp"/>
<forwardname="failure"path="/LoginForm.jsp"/>
</action>
<actionpath="/Welcome"forward="/welcomeStruts.jsp"/>
</action-mappings>
	<!--BelowthereValidation,Controllermap:-->
<controllerprocessorClass=
"org.apache.struts.tiles.TilesRequestProcessor"/>
<message-resourcesparameter=
"com/myapp/struts/ApplicationResource"/>
<!--=======Tilesplugin=======-->
<plug-inclassName="org.apache.struts.tiles.TilesPlugin">
<set-propertyproperty="definitions-config"
value="/WEB-INF/tiles-defs.xml"/>
<set-propertyproperty="moduleAware"value="true"/>
</plug-in>
<!--=======Validatorplugin======-->
<plug-inclassName="org.apache.struts
.validator.ValidatorPlugIn">
<set-property property="pathnames"
value="/WEB-INF/validator-rules.xml
,/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>

Step- 10: Open ApplicationResource.properties place in com.myapp.struts package, this file act as resource bundle of application and used to provide the property and validation into application.

#-- ApplicationResource.properties file --
# -- standard errors --
errors.prefix=<LI>
errors.suffix=</LI>
# -- validator --
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
# -- other --
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete.
Details should follow.
errors.token=Request could not be completed. 
Operation is not in sequence.
# -- welcome --
welcome.title= R4R Tech Soft
welcome.heading= Welcome to simple Login 
Application in struts!
welcome.message= [It's easy to create Struts
applications with NetBeans]
welcome.name=Enter your Name:
welcome.password=  Enter your Password:
welcome.age= Enter your Age:(age<10)
welcome.email= Enter your E-mail Id:
#-- Error-- error.password.required=
<font color="red"> Error, Enter your Password</font>
error.name.required=<font color="red">
Error, Enter your Name</font>
error.age.required=<font color="red">
Error, Age must be <10 </font>
error.Email.required=<font color="red"> 
Error, Invalid Email ID( don't used '@@' & '..')</font>
#-- End of file --

Step- 11: Select your package( like we used com.myapp.struts ), right click and select Other option( provide at last in the list).

Step- 12: Now, choose Struts folder, which contain two class Struts ActionForm Bean (Model) and Struts Action (Action) as mention in picture below.

Step- 13: Select Struts ActionForm Bean, a new window appear (describe below)--> Enter your Bean Name and its automatic map into your struts-config.xml file.

// Save as a LoginForm.java
// Program work as a Model Class
 
package com.myapp.struts;
import javax.servlet.http.*;
import org.apache.struts.action.*;
ublic class LoginForm extends org.apache.struts.action.ActionForm {
private String name, password, email;
private int age;
	//Getter/Setter property of parameter
public String getName() {
return name;
}
public void setName(String string) {
name = string;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LoginForm() {
super();
}
@Override
public ActionErrors validate(ActionMapping mapping,
		HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (getName() == null || getName().length() < 1) {
errors.add("name", new ActionMessage("error.name.required"));
}
if (getPassword() == null || getPassword().length() < 1) {
errors.add("password", 
			new ActionMessage("error.password.required"));
}
if (getAge() < 11) {
errors.add("age", new ActionMessage("error.age.required"));
}
if (getEmail() == null || getEmail().indexOf('@') == -1 ||
	getEmail().indexOf('.') == -1 || getEmail().indexOf("@@") != -1
	|| getEmail().indexOf("..") != -1) {
errors.add("Email", new ActionMessage("error.Email.required"));
}
return errors;
}
}

Step- 14: Now, select Struts Action class form the struts folder.

Note:-A new window appear, mention class Name and Action Path( very important parameter, which is used to call Action class form your JSP/Html page), then click finish. All the procedure define below.

Note:-After click finish, new window appear, Provide the Bean Name( which make earlier). For add input resource just click Browser button, another window open which hold all the file of your application, select your file. After add input resource, provide scope detail as a Session or Request depending upon application. If necessary them add attribute and validation Parameter.

// Save as a LoginAction.java
 // Program work as a Action Class
 package com.myapp.struts;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class LoginAction extends org.apache
	.struts.action.Action {
    // forward name="success" path="" 
    private static final String SUCCESS = "success";
    // This is the action called from the Struts framework.
      @Override
    public ActionForward execute(ActionMapping mapping,
		  ActionForm form, HttpServletRequest request,
		  HttpServletResponse response)throws Exception {
        return mapping.findForward(SUCCESS);
    }
}

Run your application:

Note:-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.

Please click to the Sign In link, for registration

For check the validation click to login button without complete all the entery

Previous Home Next