Developing Struts Application With Form Components in the form Page

Developing Struts application With diff. types of form components in the form page:-

Resource of application:-

  1. Details.JSP (form page)
  2. DetailsForm.Java (formbean class)
  3. DetailsAction.Java (action class)
  4. Result.jsp (result page)
  5. Struts-config.xml (Struts config file)

Details.jsp:-

Details From.java:-

 

DetailsAction.java:-

 

Struts-config.xml:-

Result.jsp:-

Deployment Directory

 

  • The select box that allows to select multiple items is called as list box.
  • When items in select box, list box are selected and radio button, check boxes are selected then their labels will not go to server as request parameter values. The values of their respective value attributes will go to server as request parameter values.
  • When check box is not selected, no item of list box is selected then they will not send their request parameters to server. So the related setxxx () methods in form bean class will be not be executed. Whereas the remaining form components send default values (empty Strings) as request parameter values even though they are not filled up with values or not selected.
  • While working with Struts environment of form page having checkbox, list box and of form bean scope is Session scope the following problem may raise. I.e these two components related form bean properties may show selected state values even though they not selected in the form page.

Understanding Form Bean Lifecycle – Struts Tutorial

Understanding FormBean Life cycle:-

Action Servlet calls various methods of formbean class as shown below:-

  • Form page submit its request to StrutsApplication.
  • ActionServlet traps and takes request.
  • ActionServlet uses Struts-config.xml file entries to decide the form bean and Action class to be used to process the request.
  • ActionServlet creates / locates form bean class object.
  • If created, ActionServlet keeps that form bean class object in the specified scope.
  • ActionServlet calls reset (-,-) of our formbean class.
  •  ActionServlet calls setxxx () methods of our form bean class to write the form data of form page to form bean class object.(form bean properties)

ActionServlet calls validate (-,-) of our form class:

If no form validition errors

ActionServlet creates / locators ,  Action class objects and calls, Execute (-,-,-) methods.

If form valadition

ActionServlet transfers the control to input page of Action class to display form validation errors. 

Form component type (form page)      Form bean property type(In form bean class)

  •              Textbox –>String / other primitive’s types
  •              Password –>String / other primitives
  •            Radio buttons –>String / other primitives

        (Grouped) (It allows selecting only one radio button as a time)

  •     Single checkbox –> String / primitives
  •     Multiple checkbox –>String []/primitives [] array

  (Ground) (Same name for all the check boxes they are allow to select multiple check boxes).

  •   Select box / combo box –>String / other primitives.

   (Allow to select only one item at a time)

  •      List box –>String []/primitives [] array

   (It allows to select multiple items at a time)

  • By giving same name for multiple radio button are can group then into single unit buts the end-user can select only one radio button at a time.
  • When multiple check boxes are grouped into a single unit by having same name for all the check boxes they allows to select multiple checkboxes as a time.

Form Validations – Struts Tutorial

Form validations in Struts :-

  • Checking pattern and format of the form date before it is getting used the input values of business logic or request processing logic is called as “FormValidation”.

Example: – checking whether E-mails Id is having. @, symbols are not? Checking whether required fields are typed or not?

  • We can develop form validations logic in two ways:

1) Client side logic

2) Server side logic

  • Verifying whether username and passwords are typed or not comes under form validation logic.
  • Verifying whether username and passwords are correct or not, by chicking against database table under business logic.

Classic java web application:

Form validations are two types:

  1. Server side : Place java code in Servlets Jsp programs before business Logic code or request Processing code.
  2. Client side :   Place javaScript code or VBscript  code.
  • Java Script is given by Netscape organization as a scripting language and it is no way related the programming language java.
  • The technology whose code must be embedded with other technology based program for execution is called as Scripting technology.
  • Java Script code executes along with html code, so javascript is called as scripting technology.
  • In the client side Script code based form validation logic comes to browser window along with form page for execution. Where as server side form validation logic, executes along with server side web resource programs. (Like Servlets, JSPs)
  • Prefer logic working with client side form validations logic (as java script code) because it reduces network round trips b/w browser window and web server. Now a day’s programmers are preferring to add both client side and server side form validations to get the guaranty that form data would be validated by using server side form validation logic, even though client side script code execution is disabled through browser settings.

Client side Form validations :-

  1. Programmatic mode.
  2. Declarative mode.

Server side Form validations :-

  1. Programmatic code.
  2. Declarative code. (Validator plogin)
  • Declarative form validation means working with xml entities to use the readily available form validation logics.
  • Programmatic form validation means developing the form validation logics manually.
  • The Struts software supplied validation plugin can perform both client side and server side form validation in declarations in declarative mode for Struts applications.

Struts Application :

Form validations

Client side:

Programmatic form validations

  • Use java script code explicity inForm page

Declarative form validations

  • Use validator plugin 

Server side:

Programmatic form validations
  • write java code in validate (-,-) of form bean class.
Declarative form validations
  •  Use validator plugin

Note: – when the validator plugin is used for Server side form validations then it generates java code based form validation logic.

Similarly when it is used for client side form validations then it generates javascript based form validation logic.

for to perform form validations in a better way it is recommended to mix-up programmatic form validations with valid plug in based declarative form validations while working with Struts applications.

Parameterized Constructors in form bean & action class of Struts Application

Question:- can I keep only parameterized constructiors in form bean & action class of Struts application?

Answer: Not possible, because programmer never creates objects for form bean, Struts Action classes. ActionServlet creates these objects by using zero argument constructors. If that is not available ActionServlet fails to create the objects of Strut’s Action class, form bean class.

Except spring container the remaining all container and framework s/w like Servlet container, EJB, Struts, JSF, and etc. generally use zero argument constructor to create object for the resources related classes.

Precudure to make JDBC Code of Struts Action Class as Flexible Code to modify

Precudure to make jdbc code of Struts Action class as flexible code to modify:

With respect to StrutsDemoApp2 project of NetBeans IOE:-

Step1: Take extra properties file in the project having the following Jdbc properties.

 

 

 

Step3:- configure above my files.properties file with logical name “file2”

In Struts-config.xml:-

5 jsp taglibraries of Struts Application:-

Html tag library –> gives jsp tags alternate for traditional html tags. Useful to design form pages in Struts App.

Bean tag library –> gives jsp tags to work with form bean properties req, session, application, attributes also useful to deal with properties file.

Logic tag library –> gives jsp to perform conditional and iterationaloperations.

Nested tag library  –> gives jsp to perform nested conditionals, nested iteration operation.

Tiles tag library  –> given to work with layout page of files framework.

Produce to work with Properties file in Struts Application

Produce to work with properties file (resource bundle file) in our struts application to make presentation logic labels as flexible labels to modify:-

With respect struts first application:-

Step1:- keep properties file in WEB-INF / classes folder of 1st application having presentation labels.

                Myfile.properties

                # Presentation logic

  1.                 My.un = <b> login username </b>
  2.                 My.pass = <b> login password </b>
  3.                 My.btn.cap = <b> check Details </b>
  4.                 My.welcome.msg = <font color = red dize =7> welcome to Struts </font>

Note: – in Struts environment properties file must have properties extecsion.

Step2:- configure the above properties file Struts-config.xml file.

In Struts-config.xml                                                              docs \ dtd docs \

After </action-mapping>

<message-resource parameter = “myfile”/> where myfile is the name of the properties file

Step3:- read & use properties file content as labels in jsp program.(register.jsp)

Register.jsp:-

  1.     <% @ taglib uri = “http://Struts.apache.org / tags-html” prefix =”html” %>
  2. <% @ taglib uri = “http://Struts.apache.org / tags-bean” prefix =”bean” %>
  3.        <bean: message key =”my.welcome.msg”/> <br>
  4.             <html: form action =”register” method = “get”>
  5.                 <bean: message key = “my.un”/><html: text property =”username”/> <br>
  6.             <bean: message key = “my.pass”/> <html: password property =”password”/> <br>
  7.                 <html: submit style =”font-size = 20px”>
  8.                <bean: message key =”my.btn.cap”/>
  9.          </html: submit>
  10.       </html: form>

Note: –   properties file can make presentation logic labels as resource labels for the multiple resource of view layer (jsp programs).

  • When Struts project is created in Netbeans it comes with one default properties file having application resources properties. This file will be configured in Struts-config file automatically.
  • If we want use one message of properties file as multiple presentation logic labels in the jsp program generated web pages having small amount of changes then we can design that message in properties file with arguments  {0}, {1}, {3}, {4}.
  • We can supply these argument values from jsp programs by using arg<n> attribute <bean: message> like arg0, arg1, arg2, arg3, & arg4 attributes.

In properties myfile.properties:-

# Presentation logic

  1.                My.lbl = <b> logic {0} </b>
  2.                My.btn.cap = checkDetails

In register.jsp:-

  1.               <html: form action =”register” method = “get”>
  2.               <bean: message key =”my.lbl” argo = “user”/> <html: text property =”username” />
  3.                                                  <br>
  4.      <bean: message key =”my.lbl” argo = “pwd”/> <html: password property =”password” />
  5.                          <br>
  6.      <html: submit>
  7.                <bean: message key =”my.btn.cap”/>
  8.        </html: submit>
  9.         </html: form>

It is recommended to design properties file having maximum of 500 messages for better performance. If needed it is recommended to take the support of multiple properties file in your Struts application.
When multiple property files are there in Struts application then they need to be configured in Struts-config file with logical names.

Example:-

Step1:- prepare multiple properties files as shown below.

WEB-INF / classes \ my file.properties

       # Presentation logic

  1.                                    My.user = <b> logic user </b>
  2.        My.btn.cap = checkDetails.

WEB-INF /classes \app \pi \App.properties

       # Presentation logic

  1.                                    My.password = <b> logic password </b>
  2.        My.welcome.msg = <font color = red size = 4> welcome to struts </font>.

Step2:- Configure both properties files in Struts configuration file with logical names.

In Struts-config.xml

  1.                  <message-resource parameter = “myfile” key = “f1”/>
  2.                  <message-resource parameter = “app.pi.App” key = “f2”/>

F1, f2-> logical means of properties files configuration.

Step3: – Use <bean: message> along with bundle attribute to read messages from multiple properties files.

 Register.jsp

  1. -<%@
  2. -<%@
  3.                          <bean: message key =”my.welcome.msg” bundle = “f2”/><br>
  4.                             <html: form action =”register” method = “get”>
  5.                             <bean: message key =”my.user” bundle = “f1”/><html: text property = “usermame”/>
  6.                        <bean: message key =”my.pass” bundle = “f2”/><html: password property = “password”/>   
  7.                      <html: submit>
  8.                              <bean: message key =”my.btn.cap” bundle = “f1”/>
  9.                      </html: submit>
  10.                    </html: form>
  • To add the additional properties file to the Struts project IDE

    Right click on source package folder -> new -> other  ->other -> properties file -> next

            Filename: myfile ->finish

Note: – this properties file must be configured in Struts config file explicitly.

  • Org.apache.Struts.util.MessageResource class object can represent one properties file of Struts application being from Struts Action class.

Count Number of Requests Coming to Struts based Web Application

Question: How can you count no. of requests coming to struts based web application?

Question: is there any need of developing user defined ActionServlet class?

  1. Since the front controller ActionServlet traps & takes all the request coming to Struts application you think to place the above said request counting logic in ActionServlet. But we cannot do that work bc3 ActionServlet is a predifend servlet.
  • To overcome these problem develop ur own servlet class extending form ActionServlet and configure that servlet class as front controller of struts application.

As shown below:-

Step1:- Develop our own servlet class extending from ActionServlet having counter logic as shown below

Step2:- configure our servlet in web.xml file having extension match url pattern as front controller.

 

Step4:- read & display application attribute value (ServletContext attribute created in step (1)) from all the jsp programs of Struts application.

In register.jsp / success.jsp / failure.jsp:-

Request count is

 

  • A text file which maintains the entries in the form of key = value pairs is called as properties values.

struts file properties values 

  • The standard principle of s/w industry is donot hardcode any values in your java app. That is changeable in the feature. It is recommended to pass such values to app. Form outside the application by taking the support of property file.
  • To make jdbc code as flexible code to modify then it is recommended to take the support of properties file to pass jdbc driver class name, url, dbusor, dbpassword details.
  • Struts application can recognize properties files once they are configured in struts configuration file. We use properties file in struts application in the following areas.

1)      To maintain presentation logic labels and to make them as flexible to modify.

2)      To add I18N (internationalization on struts application) this allows to present labels of the web application in different languages like French, German and etc.

3)      To make Jdbc code of struts Action class as flexible code to modify. (Allows the programmer to maintain Jdbc driver class name, url, dbuser, dbpassword details)

4)      Can maintain form validation related error messeges.

Pass Data from Struts Action class to Result JSP Pages

How to pass data from Struts Action class to result jsp pages?

  • If Struts Action class & its result page are using same req. & response object use request attribute other wise you can use session attribute or application attributes. (servlet context)
  • In every Struts Action class the ActionServlet class is cisible with fixed name “servlet”. (It is predefined instance variable of org.apache.Struts.action.Action).

Example code on passing data from Struts Action class to Result pages.

With respect to first Struts application:-

Step1:- create attributes having data in the execute method.

In execute () method of RegisterAction class.

            Int a = 10;

            Int b =a*a;

            Int c = a*a*a;

      String res1= “how are you”. Substring (1, 5);

     //create attributes to send result to result pages

     Req.setAttribute (“attr1”, new Integer (b)); //req attribute

     Http Session ses = req.getSession ();

   ses.setAttribute (“attr2”, new Integer(c)); //Session attribute

    Servlet context sc. = servlet.getServletContext ();

    sc.setAttribute (“attr3”, rest); //Servset sc attribute.

if (User.eq———-

                   —————–)

Step2:- to do observe how result pages are configure for Struts Action class in Struts configuration file.

         <action path = “/register” type = “app.RegisterAction” name = “rf”>

                <forward name = “success” path = “/success.jsp” redirection = “false”/>

               <forward name = “failure” path = “/failure.jsp” redirection = “true”/>

             <location>

Step3:- write following code in success.jsp / failure.jsp to read the attribute values.

Success.jsp / failure.jsp:-

   <b>attr1 (req) value is : <lb> <% = request.getAttribute (“attr1”) %>

          <br>

   <b>attr2 (ses) value is : <lb> <% = Session.getAttribute (“attr2”) %>

         <br>

<b>attr3 (application) value is : <lb> <% = application.getAttribute (“attr3”) %>

      <br>

</body>

</html>

Note: – failure.jsp cannot give request value where as success.jsp can read all the three attribute values.

  • <bean: write> tag can be to read any scope attribute values.
  • To check whether certain scope attribute is holding null value or not we can use <logic: notEmpty> tag.
  • These 2 tags are available in Struts supplied bean, logic tag libraries.
  • It always recommended to develop jsp programs of web application as java codeless jsp programs.

Developing success.jsp, failure.jsp program as java codeless jsp program while reading attribute values.

Success.jsp / failure.jsp:

  <% @ taglib uri = “http://Struts.apache.org / tags-bean” prefix = “bean” %>

<% @ taglib uri = “http://Struts.apache.org / tags-logic” prefix = “logic” %>

       <html>

          <body>

                 —————-

                  ————–

        </center>

    <b> attr1 (req) value is : </b>

           <logic: notEmpty name = “attr1” scope = “request”>

           <bean: write name = “attr1” scope = “request” format =” “/>

            </ logic: notEmpty>

           <br>

     <b> attr2 (ses) value is : </b>

          <logic: notEmpty name = “attr2” scope = “Session”>

          <bean: write name = “attr2” scope = “Session” format =” ”/>

           </ logic: notEmpty>

           <br>

         <b> attr3 (application) value is : </b>

           <logic: notEmpty name = “attr3” scope = “application”>

           <bean: write name = “attr3” scope = “application” />

            </ logic: notEmpty>

       </body>

      </html>

  • Specifying scope attribute in <logic: notEmpty> & <bean: write> tag is aptional beans when scope attribute is not specifying these tags internally uses page context.findAttribute () to search available of given attributes. This method can search for the given attribute in multiple scopes like page scope, request scope, session scope & application scope.

   <b> attr1 (req) value is : </b>

       <logic: notEmpty name = “attr1” >

           <bean: write name = “attr1” format = “” />

            </ logic: notEmpty>

  • We can use <bean: write> to even read form data from form bean class objects form bean properties.

In success.jsp / failure.jsp:-

<br> <br> <b> the given form page form data is: </b>

    <bean: write name = “rf” property = “username”/>

    <bean: write name = “rf” property = “password”/>

Question: Why scope attribute is given in <action> of Struts-config file to specify form bean class object scope?

Answer: –  When multiple action class are using single form bean to specify that form bean class scope with request to each Struts Action class the scope attribute is given in Action tag instead of in form-bean tag.

<form-beans>

        <form-beans name = “of” type = “app.RegisterForm” />

</ form-beans>

<action-mappings>

        <action path = “/xyz1” type = “MyAction1” name = “rf” scope = “request”>

               ————————

                —————————–

         </action>

   <action path = “/xyz2” type = “MyAction2” name = “rf” scope = “session”> 

              ————————–

                —————————–

     </action>

  </action-mappings>

Note: – from bean class object scope is no way related while choosing attribute scopes to send result data form Struts Action class to result pages.

Question:–  How to display the struts Action class generated result on the form page itself using which request is generated.

With respect to Struts DemoApp1 application

Step1: configure form page (request.jsp) as result page for Struts Action class (RegisterAction)

In Struts-config.xml

      < action path = “/register” type = “app.Register” name = “rf”>

       <forward name = “result” path =”/register.jsp”>

        </action>

Step2: write following code in the execute () of StrutsAction class to store the business logic generated result as requestAttribute values.

In the execute () of RegisterAction class:-

s.o.pm (“in Reg.Action () execute ()”);

        RegisterForm fm = (RegisterForm) form;

        String user = fm.get username ();

        String pass = fm.get password ();

If (user.equals (“Ramu”) && pass.equals (“Jalli”))

     {

          Req.setAttribute (“msg”, “valid credentials”);

     }

Else {

         Req.setAttribute (“msg”, “invalid credentials”);

      }

   Return mapping.findForward (“result1”);

  }

}

Step3: write following code at the end of register.jsp to read & display the requestAttribute value.

   Result is:

<logic: notEmpty name = “msg”>

   <beans: write name = “msg” />

       </logic: notEmpty>

  • To make Struts application interacting with D.b.s/w adds jdbl code in Struts Action class.

Approaches to Work with JSP Tag Library in Java Web Application

There are 2 approaches to work with jsp tag library in our java web application:

Approach1: by using user defined taglib uri

Note: – our StrutsDemoApp1 is using this approach number (1) to work with Struts supplied html tag library.

Approach2: by using fixed taglib uri

Procedure to work with approach (1) based JSP tag libraries utilization:-

1)      Keep tag handler classes related jar files in WEB-INF/lib folder.

2)      Gather tld file of jsp tag library place in web application like WEB-INF folder.

3)      Configure jsp tag library with user defined tag lib uri in web.xml file.

4)      In the jsp programs of web applications specify user defined tag lib uri and start working with the jsp tags of tag library.

  • Every jsp tag library related tld file contains one fixed taglib uri you can collect from the <uri-tag> of that tld file.
  • Struts supplied jsp tag library related fixed taglib uri’s.

Html tag library –> http://Struts.apache.org/tags-html

Bean tag library –> http://Struts.apache.org/tags-bean

Logic tag library –> http://Struts.apache.org/tags-logic

Nested tag library –> http://Struts.apache.org/tags-neated

Tiles tag library –> http://Struts.apache.org/tags-tiles

Procedure to work with jsp tag library based on approach (2):-

1)      Keep jar files is WEB-INF/lib folder which represents tag handler classes & tld files of jsp tag library. (Like Struts-taglib-1.3.8.jar)

2)      Gather fixed tag lib uri form tld file and specify in jsp program then start working with tags of tag library. (The uri’s as shown above)

Register.jsp with uri of Struts supplied html tag library

   Register.jsp

      <%@ taglib uri = http://Struts.apache.org/tags-html prefix = “j” %>

            <j: from action = “register” method = “get” %>

                —–

                —–

         <j: submit value – “checkDetails”/>

       </j: form>

Note: – approach (2) is recommended to use. 

  • When source servlet uses rd.forward () is communicates with destination web resource program directly. The source & destination programs will use some request, response objects.
  • When source servlet program uses response.sendRedirect () it communicates with destination of web resource program by having one network round trip with browser window. So Source & destination programs will not use some request & response objects.

<action path – “/register” type =”app.RegisterAction” name = “rf”>

<forward name = “success” path =”/success.jsp” redirect = “true”/>

<forward name = “failure” path =”/failure.jsp” redirect = “false”/>

  • In the above code redirect = “true” means ActionServlet uses response.sendRedirect() method to transfer control to result page.(success.jsp) that means ActionServlet & result page, Action class & result page will not use same request & response object.
  • Redirect = “false” (default value) ActionServlet uses rd.forward () method to send the control to result page (failure.jsp).this indicates ActionServlet & result page, Action class & result page will use same request & response object.

Note: – ActionServlet & Action class uses same request & response objects irrespective of whether redirect = true/false.

Servlet Recap:-

   Attribute is a logical name that can hold a value; attributes are usefull to pass data from one web resource program to another web resource program.

Servlet Recap 

  • In the above diagram Srv 1, Srv2 & Srv3 are participating in a Servlet chaining so they use same req. & res. Object.
  • Request attribute created in Srv1 program is visible & accessible in Srv2 & Srv3 but not in Srv4.
  • Session attribute created in Srv1 by getting request from browser window bl is visible & accessible if remaining servlet programs only when they get request from same browser window bl.
  • Servlet context attribute created in Srv1 by getting request from browser window bl is visible & accessible if remaining servlet programs irresopnding of the browser window from which they are getting request.

Flow of Execution for Strutsdemoapp1 Application – Struts Tutorial

Flow of execution for StrutsDemoApp1 application:-

a)      Programmer deploys StrutsDemoApp1 Struts App in Tomcat web server.

b)      Servlet container creates ActionServlet class obj during server startup or during deployment of StrutsDemoApp1 application based on <I-O-S> that is enable on ActionServlet

c)       ActionServlet activates Struts-f/m software & also reads, verifies Struts cfg file entries to get ideas on resource of Struts App.

d)      End user launches form page on the browser window by typing their request url—— like http://localhost——-

e)      The action url of form page will be gathered (register)

  • From S-C.xml file “/register” (action path) based StrutsAction class name will be gathered (app.RegisterAction)
  • From there form bean that is linked with RegisterAction (based name = “rf” attribute) will be gathered (app.RegistrForm)
  • ActionServlet creates RegisterForm class obj (formbean class obj) & keeps in session scope.
  • ActionServlet class get xxx () methods on RegisterForm class obj to read default from form bean properties.
  • The default data form bean properties will be assigned to form components (text boxes) as initial

f)       End user files up the form page & submits the form page

g)      Based action url of form page the request url will be generated having register.do in it.

url:  http://localhost: 2020/ StrutsApp1/register.do.

h)      Based on “.do” word in request url ActionServlet traps & takes the request:

i)        ActionServlet uses S-C.xml entries to decide form bean, Action class to process the request based on “register” word of request url it will locate RegisterAction (action class), RegisterForm (form bean)

j)        ActionServlet locates form bean class obj (Register Form) from session scope

k)      ActionServlet calls set xxx () on form bean class obj. & writes the form data of form page to form bean properties.

l)        ActionServlet creates RegisterAction class obj.

m)    ActionServlet calls execute (-,-) of RegisterAction class…..

Success                                                              failure

94–> execute (-,-) <———————— 96

Execute () returns ActionForword class obj. with logical name success (94) / failure (96).

46 —————–> 0 <———————————– 47

Based on ActionForword configuration done in Struts config file the success.jsp / failure.jsp will be taken as result page of RegisterAction class

(99-108) —————–> p <———————– 109-119

Success.jsp                                                                   failure.jsp

End    (q) ß—————————————117 (hyperlink in failure.jsp)

             (r) ß————————————– (4-10) (register.jsp)

                                                                                      (end).