Struts

adplus-dvertising
Application-3 : Creating a Simple onLineDraw Application with Struts
Previous Home Next

In this chapter, we have create a very simple onLineDraw application with struts. 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 Third application name as onLineDraw. onLineDraw application contain following page-

  • Four View file name as index.jsp, welcomeStruts.jsp, Register.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 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.

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

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

<%--Document: welcomeStruts.jsp
Description : Second Page of onLineDraw 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" %>
<%@ taglib uri="http://struts.apache.org/tags-logic"
prefix="logic" %>
<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">
<logic:notPresent name="org.apache.struts.action.MESSAGE"
scope="application">
<div  style="color: red">
ERROR:  Application resources not loaded -
- check servlet container
logs for error messages.
</div>
</logic:notPresent>
<html:form action="/check" method="post">
<h1><bean:message key="welcome.heading"/></h1>
<p><bean:message key="welcome.message"/></p>
<ul>
<b>For participation into onLine draw, Age must be above 17</b>
<p><bean:message key="welcome.age" /><BR>
<html:errors property="Age" />
<html:text property="age" />
</p>
<p>
<html:submit property="submit" value=" Submit " />
&nbsp;&nbsp;<html:cancel property="cancel" value=" Cancel " />
</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 : Third Page of onLineDraw 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>Register Page</title>
</head>
<body>
<html:form action="/register" method="post">
<h1>For taking part in onLine draw, please register yourself</h1>
<b>Please don't leave any block empty</b>
<ul>
<p>
<bean:message key="welcome.username" /><BR>
<html:errors property="UserName" />
<html:text property="userName" maxlength="12"/>
<BR><BR> <bean:message key="welcome.password" /><BR>
<html:errors property="Password" />
<html:password property="password" maxlength="10"/>
<BR><BR> <bean:message key="welocme.name" /> <BR>
<html:errors property="name" />
<html:text property="name" maxlength="15"/>
<BR><BR> <bean:message key="welcome.address" /> <BR>
   <html:errors property="Address" />
<html:textarea property="address" rows="5" cols="15"/>
<BR><BR> <bean:message key="welcome.number" /> <BR>
 <html:errors property="Number" />
<html:text property="number" maxlength="13"/>
</p>
<p>
<html:submit property="submit" value=" Register " />
&nbsp;&nbsp;<html:button property="reset" 
value=" Reset " />
</p>
</ul>
</html:form>
</body>
</html:html>

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


<%--  Document: success.jsp
Description : Fourth Page of onlineDraw 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>
<%-- page refresh within 10 sec and search for the URL --%>
<meta http-equiv="refresh" content="10; URL=index.jsp">
<title>Success Page</title>
</head>
<body>
<h1>Congratulations! You detail successfully submit </h1>
<b> Please check your detail below: </b>
   <ul>
<p> Username:<strong> <bean:write name="RegisterForm" 
property="userName" /></strong></p>
<p> Password:<strong> <bean:write name="RegisterForm" 
property="password" /></strong></p>
<p> Name:<strong> <bean:write name="RegisterForm" 
property="name" /></strong></p>
<p> Address:<strong> <bean:write name="RegisterForm" 
property="address" /></strong></p>
<p> Phone/Mobile No:<strong> <bean:write name="RegisterForm" 
property="number" /></strong></p>
</ul>
<ul><B>
Thanks for Registration, our team will contact u soon
</B>

<p> Return to <a style=" cursor: auto;color: green" 
<a href="index.jsp"> home </a> Page </p>
or wait for 10 sec page automatic redirect to the 
<a style="color: green"> home </a> page
</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.

<!-- Save as a struts-config.xml -->
<?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>
<form-bean name="CheckForm" 
type="com.myapp.struts.CheckForm"/>
<form-bean name="RegisterForm"
type="com.myapp.struts.RegisterForm"/>
</form-beans>
<global-exceptions>
</global-exceptions>
<!-- index.jsp file used this global forward to 
find welcome.jsp page form action class -->
<global-forwards>
<forward name="welcome"  path="/Welcome.do"/>
</global-forwards>
<!-- all the action relative stuff map here:-->
<action-mappings>
<action input="/welcomeStruts.jsp" name="CheckForm"
path="/check" scope="session" type=
"com.myapp.struts.CheckAction">
  <forward name="success" path="/Register.jsp" /> 
  <forward name="failure" path="/welcomeStruts.jsp" />
</action>
<action input="/Register.jsp" name="RegisterForm"
path="/register" scope="session" type=
"com.myapp.struts.RegisterAction">
  <forward name="success" path="/success.jsp" /> 
  <forward name="failure" path="/Register.jsp" />
</action>
<action path="/Welcome" forward="/welcomeStruts.jsp"/>
</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: 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
# -- 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 onLineDraw Application!
Struts Application
welcome.message=It's easy to create Struts applications
with NetBeans.
welocme.name=Enter your name:
welcome.password=Enter your password:
welcome.username= Enter your userName:
welcome.address=Enter your Address:
welcome.age=Please Enter your Age:
welcome.number=Enter your phone/Mobile no:
#---- Error--
error.Age.required=<font color="red"> 
Error, Age must be < 17 </font>
error.name.required=<font color="red"> 
Error, Enter your Name</font>
error.UserName.required=<font color="red">
Error, Enter your UserName</font>
error.Password.required=<font color="red">
Error, Enter your Password</font>
error.Address.required=<font color="red"> 
Error, Enter your Address</font>
error.Number.required=<font color="red"> 
Error, Enter your Number</font>
#-- End of file --

Step- 9: Now, Add bean class into struts-config.xml, since in this Application two different data is store into different Bean, so two different bean class required.

First bean class name as CheckForm.java, which contain data of welcomeStruts.jsp page.

// Save as a CheckForm.java
 //package com.myapp.struts;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
public class CheckForm extends org.apache.
struts.action.ActionForm {
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int i) {
        age = i;
    }
    public CheckForm() {
        super();
    }
     // This is the action called from the Struts framework.
     //@return
         @Override
    public ActionErrors validate(ActionMapping mapping,
	HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (getAge() < 18) {
            errors.add("Age", new ActionMessage("error.Age.required"));
        }
        return errors;
    }

Second bean class name as RegisterForm.java, which contain data of Register.jsp page.

// Save as a RegisterForm.java
 //package com.myapp.struts;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.*;
public class RegisterForm extends org.apache
.struts.action.ActionForm {
private String userName, password, name, address;
   private int number;
   public String getName() {
       return name;
   }
     public void setName(String string) {
       name = string;
    }
    public int getNumber() {
       return number;
   }
   public void setNumber(int i) {
       number = i;
   }
   public String getUserName() {
       return userName;
   }
    public void setUserName(String userName) {    
        this.userName = userName;
   }
public String getPassword() {
       return password;
   }
public void setPassword(String password) {
       this.password = password;
   }
public String getAddress() {
       return address;
   }
public void setAddress(String address) {
       this.address = address;
   }

  public RegisterForm() {
       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 (getUserName() == null || getUserName().length() < 1) {
           errors.add("UserName", new ActionMessage
		   ("error.UserName.required"));
       }
          if (getPassword() == null || getPassword().length() < 1) {
           errors.add("Password", new ActionMessage
		   ("error.Password.required"));
       }
       if (getPassword().length() < 1) {
           errors.add("Address", new ActionMessage
		   ("error.Address.required"));
       }
       if (getNumber() < 1) {
            errors.add("Number", new ActionMessage
			("error.Number.required"));
       }
       return errors;
   }
}

Step- 10: Since Application contain two different bean class hence also contain two corresponding Action class

First Action Class name as a CheckAction.java ,which is call by the checkForm.java

// Save as a CheckAction.java
//package com.myapp.struts;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class CheckAction 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.
// @return
// @Override
    public ActionForward execute(ActionMapping mapping, 
	ActionForm form,
            HttpServletRequest request, 
			HttpServletResponse response)
           throws Exception {
       return mapping.findForward(SUCCESS);
   }
}

Second class name as a RegisterAction.java, which is call by RegisterForm.java

// Save as a RegisterAction.java
//package com.myapp.struts;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class RegisterAction extends org.apache.
struts.action.Action {
    /* forward name="success" 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 {
        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.

Previous Home Next