Struts

adplus-dvertising
Application-1 : Creating a Simple Web Application with NetBeans IDE in Struts
Previous Home Next

In this chapter, you create a simple Struts application from start to finish. In such application, your message is successfully forward to another page. When your message successfully submit then struts-config.xml find the forward file name and path,, forward your request to that page and your message will be display on that page. 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 First struts application-

  • At least one view component is required in every Application.
  • A subclass of org.apache.struts.action.ActionForm is used to submit the date as application needed.
  • A subclass of org.apache.struts.action.Action class which provide specific processing functionality for the application.
  • A web.xml file is required for calling ActionServlet, TagLibrary and struts-config.xml.
  • A struts-config.xml file is required for updating, forward 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 following steps for develop your first application name as StrutsTest. StrutsTest application contain following page-

  • First View file( or welcome file) name as index.jsp, used for write a message which used to forward
  • Second view file name as welcome.jsp, used to display forward message.
  • 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 in fig.

Step-3: Name your project and click to the next button ==> Next window appear, Add server( Apache Tomcat 6.0.20) then 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 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: Open index.jsp page from your struts application and code it as describe below.

<%--
Document: index.jsp
Description : First Page of Application
--%>
<!-- TagLibrary which automatic configure into web.xml and
used any HTML/JSP within this project -->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html xhtml="true">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><bean:message key="welcome.title"/></title>
<html:base/>
</head>
<body>
  <!-- action= parameter which call Action class,
  for this check your Action mapping in 
struts-config.xml file  -->
<html:form action="/login" method="post">
<h1><bean:message key="welcome.heading" /></h1>
<h2><bean:message key="welcome.message"/></h2>
    <bean:write name="LoginForm" property="error" filter="false" />
<BR>
<!-- Add error to the page  -->
<html:errors property="area"/>
<b><bean:message key="welcome.login.message" /></b>
<BR><html:textarea property="area" rows="5" cols="20" />
<BR><BR>
<html:submit value=" Froward " property="submit" />
<html:reset value=" Reset " property="reset" />
</html:form>
</body>
</html:html>

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

<%--
    Document    : welcomeStruts.jsp
    Description : Success Page of Application
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html xhtml="true">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title><bean:message key="welcome.title" /></title>
    </head>
    <body>
        <h1>Congratulations! Your massage have successfully Forward </h1>
        <ul>
            <p>Your Message: <bean:write name="LoginForm" property="area"/></p>
        </ul>
        <p>Return to <a href="index.jsp"> Home</a> page</p>
    </body>
</html: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.

<!-- web.xml file -->
<?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">
<!-- Description about application -->
<description>Following struts application used only 
		forward the request</description>
<display-name>StrutsTest</display-name>
 <!-- ActionServlet Map Here -->
<servlet>
<description>ActionServlet is work as a backbone of struts,
although no such class(ActionServlet) exist </description>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
 <!-- 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 Map Here -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>

 <!-- First(Welcome) page Map Here -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
 <!-- All Five TagLibrary Map Here -->
<jsp-config>
<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.

<!-- struts-config.xml file -->
<?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>
<!-- Model(Bean) class Map here -->
<form-beans>
 <!-- name="Bean class name" and type="Location of bean class" -->
<form-bean name="LoginForm" type="r4r.co.in.LoginForm"/>
</form-beans>
<global-forwards>
<forward name="welcomestruts" path="welcome.do" />
</global-forwards>
<!-- Action Class Map Here -->
<action-mappings>
<action path="/login" type="r4r.co.in.LoginAction"
name="LoginForm"
scope="request"
input="/index.jsp">
<!-- If Action class return success, then this forward call-->
<forward name="success" path="/welcomeStruts.jsp" />
<!-- If Action class return failure, then this forward call-->
<forward name="failure" path="/index.jsp" />
</action>
</action-mappings>
<!-- ApplicationResource Bundle Map here-->
<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 file--
# -- standard errors --
errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>
# -- validator --
errors.required={0} is required
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=Struts Applications in Netbeans 6.8!
welcome.message= Struts Application, used for forward request
welcome.login.message= Write something here:
#-- UserDefine Error --
error.login.required= <font color="red">Error,
Textarea can't be blank</font>
#-- End of file --

Note:-Now, Major major problem is How to introduction Model and Action Class into struts-config.xml. For such problem NetBeans IDE provide the good solution, it already define the two major class as describe below

Step- 9: Select your package( like we used r4r.co.in ), right click and select Other option( provide at last in the list) as describe below

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

Step- 11: 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
public class LoginForm 
	extends org.apache.struts.action.ActionForm {
    private String area;
//Setter/Getter property of area
public String getArea() {       
		return area;
    }
    public void setArea(String area) {
        this.area = area;
    }
     public LoginForm() {
       super();
   }
    @Override
    public ActionErrors validate(ActionMapping mapping,
		HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
       if (getArea() == null || getArea().length() < 1) {
            errors.add("area", new ActionMessage
				("error.login.required"));
       }
       return errors;
   }

}

Step- 12: 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 r4r.co.in;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class LoginAction extends org.apache.struts.action.Action {
    // forward name="success" path="" //
   private static final String SUCCESS = "success";
   @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.

Note:-For test your Validation click to the forward button without write something, the error display into your page which map into ApplicationResource file

Previous Home Next