Java/J2EE/Struts

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

A Full Struts Application

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /

//index.jsp <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html locale="true"> <head> <title>A Welcome Page</title> <html:base/> </head> <body bgcolor="white"> <logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application">

 
   ERROR:  Application resources not loaded -- check servlet container
   logs for error messages.
 

</logic:notPresent>

Reading User Input

   <html:form action="Data"> 
         Please type your name: <html:text property="text" />
         <html:submit />
   </html:form> 

</body> </html:html> //ch03_01.jsp <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <%@ taglib uri="/ch03" prefix="ch03" %> <HTML>

   <HEAD>
       <TITLE>The Struts Cafe</TITLE>
   </HEAD>
   
   <BODY>

The Struts Cafe

       <html:errors/>
       <ch03:items/>
       <ch03:toppings/>
       <html:form action="ch03_04.do">
                       <bean:message key="toppings"/>
                       
<logic:iterate id="toppings1" name="toppings"> <html:multibox property="toppings"> <%= toppings1 %> </html:multibox> <%= toppings1 %>
</logic:iterate>
                       <bean:message key="items"/>
                       
<html:select property="items"> <html:options name="items"/> </html:select>
                                   
<bean:message key="email"/> <html:text property="email"/>
                 
<html:submit value="Place Your Order!"/> </html:form> </BODY>

</html> package ch03; import ch03.DataForm; import java.io.IOException; import javax.servlet.*; import javax.servlet.http.*; import org.apache.struts.action.*; public class DataAction extends Action {

 public ActionForward execute(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
   String text = null;
   String target = new String("success");
   if ( form != null ) {
     DataForm dataForm = (DataForm)form;
     text = dataForm.getText();
   }
   return (mapping.findForward(target));
 }

} package ch03; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; public class DataForm extends ActionForm {

 private String text = null;
 public String getText() {
   return (text);
 }
 public void setText(String text) {
   this.text = text;
 }
 public void reset(ActionMapping mapping,
   HttpServletRequest request) {
   this.text = null;
 }

// public ActionErrors validate(ActionMapping mapping, // HttpServletRequest request) { // ActionErrors errors = new ActionErrors(); // if ( (symbol == null ) || (symbol.length() == 0) ) { // errors.add("symbol", // new ActionError("errors.data.symbol.required")); // } // return errors; // } } package ch03; import java.util.*; import javax.servlet.jsp.tagext.TagSupport; public class ch03_02 extends TagSupport {

   public int doStartTag() 
     {
       
       String[] itemsArray = {"", "Pizza", "Calzone", "Sandwich"};
       
       pageContext.setAttribute("items", itemsArray);
       
       return SKIP_BODY;
   }

} package ch03; import java.util.*; import javax.servlet.jsp.tagext.TagSupport; public class ch03_03 extends TagSupport {

   public int doStartTag() 
     {
       String[] toppingsArray = {"Pepperoni", "Hamburger", "Sausage", "Ham", "Cheese"};
       
       pageContext.setAttribute("toppings", toppingsArray);
       
       return SKIP_BODY;
   }

} package ch03; import java.io.*; import java.util.*; import ch03.ch03_06; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.struts.action.*; public class ch03_04 extends Action {

 public ActionForward execute(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       ActionErrors actionerrors = new ActionErrors();
               
       ch03_06 orderForm = (ch03_06)form;
       
       String email = orderForm.getEmail();        
       if(email.trim().equals("")) {
           actionerrors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.noemail"));
       }
       
       String items = orderForm.getItems();        
       if(items.trim().equals("")) {
           actionerrors.add("ActionErrors.GLOBAL_ERROR", new ActionError("error.noitems"));
       }
       
       String[] toppings = orderForm.getToppings();        
       if(toppings == null) {
           actionerrors.add("ActionErrors.GLOBAL_ERROR", new ActionError("error.notoppings"));
       }
           
       if(actionerrors.size() != 0) {            
           saveErrors(request, actionerrors);
           return new ActionForward(mapping.getInput());            
       }
       return mapping.findForward("OK");
   }

}

      </source>
   
  
 
  



Blank Struts template

   <source lang="java">

/* This product includes software developed by The Apache Software Foundation (http://www.apache.org/).

  • /


      </source>
   
  
 
  



Create a pluggable validator for cross-form validation 2

   <source lang="java">

/* Struts Recipes By George Franciscus and Danilo Gurovich Publisher: Manning Publications Co. ISBN 1932394249

  • /


      </source>
   
  
 
  



Creating Custom Tags

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /

//ch07_01.jsp <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html>

   <head>
       <title>Using <logic> Tags</title>
   </head>
   
   <body>

Using <logic> Tags

       <html:form action="ch07_02.do">

Enter your data:

           <html:text property="text"/>
           

<html:submit value="Submit"/> <html:cancel/> </html:form> </body>

</html:html> //ch07_04.jsp <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML>

   <HEAD>
       <TITLE>Here"s Your Data...</TITLE>
   </HEAD>
   
   <BODY>

Here"s Your Data...

The text field text:

       <bean:write name="ch07_03" property="text"/>
       

Using <logic:empty name="ch07_03" property="empty">

       <logic:empty name="ch07_03" property="empty">
       Results: Empty
       </logic:empty>
       

Using <logic:notEmpty name="ch07_03" property="text">

       <logic:notEmpty name="ch07_03" property="text">
       Results: Not empty
       </logic:notEmpty>
       

Using <logic:equal name="ch07_03" property="number" value="6">

       <logic:equal name="ch07_03" property="number" value="6">
       Results: Equal
       </logic:equal>
       

Using <logic:notEqual> name="ch07_03" property="number" value="7"

       <logic:notEqual name="ch07_03" property="number" value="7">
       Results: Not equal
       </logic:notEqual>
       

Using <logic:greaterEqual name="ch07_03" property="number" value="3">

       <logic:greaterEqual name="ch07_03" property="number" value="3">
       Results: Greater than or equal
       </logic:greaterEqual>
       

Using <logic:greaterThan name="ch07_03" property="number" value="4">

       <logic:greaterThan name="ch07_03" property="number" value="4">
       Results: Greater than
       </logic:greaterThan>
       

Using <logic:lessEqual name="ch07_03" property="number" value="8">

       <logic:lessEqual name="ch07_03" property="number" value="8">
       Results: Less than or equal
       </logic:lessEqual>
       

Using <logic:lessThan name="ch07_03" property="number" value="8">

       <logic:lessThan name="ch07_03" property="number" value="8">
       Results: Less than
       </logic:lessThan>
       

Using <logic:match name="ch07_03" property="text" value="6">

       <logic:match name="ch07_03" property="text" value="6">
       Results: Matched
       </logic:match>
       

Using <logic:notMatch name="ch07_03" property="number" value="9">

       <logic:notMatch name="ch07_03" property="number" value="9">
       Results: No match
       </logic:notMatch>
       

Using <logic:present name="ch07_03" property="number">

       <logic:present name="ch07_03" property="number">
       Results: Present
       </logic:present>
       

Using <logic:notPresent name="ch07_03" property="fish">

       <logic:notPresent name="ch07_03" property="fish">
       Results: Not present
       </logic:notPresent>
       
</BODY>

</HTML> //ch07_05.jsp <%@ taglib uri="/tags/struts-html" prefix="html" %> <html:html>

   <head>
       <title>Using <bean> Tags</title>
   </head>
   <body> 

Using <bean> Tags

       <%
       Cookie cookie1 = new Cookie("message", "Hello!");
       cookie1.setMaxAge(24 * 60 * 60);
       response.addCookie(cookie1); 
       %> 
   
       <html:form action="ch07_06.do">

Enter your data:

           <html:text property="text"/>
           

<html:submit value="Submit"/> <html:cancel/> </html:form> </body>

</html:html> //ch07_08.jsp <%@ page import="ch07.ch07_07" %> <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <HTML>

   <HEAD>
       <TITLE>Here"s Your Data...</TITLE>
   </HEAD>
   
   <BODY>

Here"s Your Data...

The text field text:

       <bean:write name="ch07_07" property="text"/>
       

The cookie data:

       <bean:cookie id="messageCookie" name="message"/>
       <%= messageCookie.getValue() %>
       

The new variable:

       <bean:define id="variable" name="ch07_07" property="text"/>
       <%= variable %>
       

The user-agent header data:

       <bean:header id="headerObject" name="user-agent"/>
       <%= headerObject %>
       

The parameter data:

       <bean:parameter id="text" name="text"/>
       <%= text %>
       

The mapping data:

       <bean:struts id="mapping" mapping="/ch07_06"/>
       <% String[] a = mapping.findForwards(); 
       out.println(a[0]); %>
       
</BODY>

</html> package ch07; import org.apache.struts.action.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ch07_03 extends ActionForm {

   private String empty = "";
   private String text = "";
   private int number;
   
   public String getEmpty() 
   {
       return empty;
   }
   
   public void setEmpty(String text) 
   {
   }
   
   public String getText() 
   {
       return text;
   }
   
   public void setText(String text) 
   {
       this.text = text;
       this.number = Integer.parseInt(text);
   }
   
   public int getNumber() 
   {
       return number;
   }
   
   public void setNumber(int number) 
   {
       this.number = number;
   }
   

} package ch07; import java.io.*; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.struts.action.*; public class ch07_06 extends Action {

 public ActionForward execute(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       return mapping.findForward("success");
   }

} package ch07; import org.apache.struts.action.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ch07_07 extends ActionForm {

   private String text = "";
   
   public String getText() 
   {
       return text;
   }
   
   public void setText(String text) 
   {
       this.text = text;
   }
   

} package ch07; import java.io.*; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.struts.action.*; public class ch07_02 extends Action {

 public ActionForward execute(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       return mapping.findForward("success");
   }

}

      </source>
   
  
 
  



Essential Struts Action

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /

//index.jsp <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html locale="true"> <head> <title>A Welcome Page</title> <html:base/> </head> <body bgcolor="white">

A Sample Welcome Page

<logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application">

 
   ERROR:  Application resources not loaded -- check servlet container
   logs for error messages.
 

</logic:notPresent>

   <html:form action="Data"> 
         Please click the button:
         <html:submit />
   </html:form> 

</body> </html:html> //result.jsp <html>

 <head>
   <title>A Results page</title>
 </head>
 <body>

A Sample Results Page

   <%= request.getAttribute("DATA") %>
 </body>

</html> package ch02; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.*; public class DataForm extends ActionForm {

 public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
   return new ActionErrors();
 }

} package ch02; //import ch02.DataForm; import java.io.IOException; import javax.servlet.*; import javax.servlet.http.*; import org.apache.struts.action.*; public class DataAction extends Action {

 public ActionForward execute(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
   String text = "No worries.";
   String target = new String("success");
   request.setAttribute("DATA", text);
   return (mapping.findForward(target));
 }

}

      </source>
   
  
 
  



Exercise 10: Using Struts and Tiles

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Technical Objectives for this exercise: The technical objectives of this exercise is to learn ?how to?: 1) Use Struts and Tiles a) Add TilesRequestProcessor to struts-config.xml <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor" /> b) Define the 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> c) Create an empty Tiles definition file tiles-defs.xml under /WEB-INF directory <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/tiles-config_1_1.dtd"> <tiles-definitions> </tiles-definitions> d) Add the base definition to the tile definition xml <definition name="base.definition" path="/Layout.jsp"> <put name="title" value=""/> <put name="header" value="/common/header.jsp" /> <put name="footer" value="/common/footer.jsp" /> <put name="body" value="" /> </definition> e) Create the definition for each of the three pages by extending the above definition and overriding the empty values f) Change the references to physical jsps in struts-config.xml and replace them with one of the above names. For instance, change all references to NOTE: There is no replacement for index.jsp. Let us keep it as is. Hence don?t change references to index.jsp ....

  • /


      </source>
   
  
 
  



Exercise 1: Building your first Struts Application

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Technical Objectives for this exercise: 1. Create Struts ActionForm and Action 2. Understand the interaction between RequestProcessor, Action and ActionForm 3. Start development with CustomerForm.jsp & add tags and TLDs [Using basic Struts tags - html 4. Understand the basic elements of struts-config.xml 5. Create ActionForm fields for the JSP form fields 6. Implement the validate method in ActionForm 7. Create ActionMapping & associate the correct ActionForm and Action 8. Create the Action class & implement the execute method 9. Add ActionForward to the ActionMapping 10. Understand how to use Message Resource Bundle 11. Understand how to handle Form display, Form submission and validation 12. Look for constants in JSP (bean:message, srcKey, altKey etc.) to add them in Resource Bundle 13. Understand ForwardAction 14. Look for ActionError keys & add them to Resource Bundle 15. Build and deploy to WebLogic using the Build script provided and bean tags (totally 11 tags)]

  • /
      </source>
   
  
 
  



Exercise 2: Improving your first Struts Application

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Business Objectives: 1. Do not expose JSP URLs directly 2. Allow change of images without changing JSPs 3. Allow global change of error messages for a given type of error. 4. Add fields to capture customer address in the form using relevant form elements 5. Use Images instead of grey buttons for submitting data Technical Objectives for this exercise: The technical objectives of this exercise is to learn ?how to?: 1. Use MVC compliant html:link Tag 2. Use Img Tags (html:img) instead of <img src=..>. Externalize its src and alt to Resource Bundle. 3. Reuse error messages by value replacement 4. Modify the ActionForm and JSP Struts Tags to handle nested objects 5. Modify the ActionForm, Struts Tags in JSP & Action for image button form submission (using ImageButtonBean) 6. Use Checkbox & Radio tags for individual items 7. Initialize the ActionForm to pre-populate the html form 8. Use Select & Option Tag 9. Use Options to display collections in the Select Tag 10. Use Multiple Message Resource Bundles

  • /
      </source>
   
  
 
  



Exercise 3: Using JSTL, Struts-EL etc

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* . Business Objectives: The following business objectives will be met at the end of this exercise: 1. Add support for JavaScript 2. Controlling field navigation without mouse 3. Greater Control over the look and feel using CSS Stylesheets 4. Additional Message Display in Success page if user has accepted to receive promotional email. 5. Simplifying JSP maintenance by eliminating buggy scriptlets. Technical Objectives for this exercise: The technical objectives of this exercise is to learn ?how to?: 11. Implement Focus on the first field 12. Implement javascript handlers such as onmouseover etc. 13. Use tabindex 14. Use CSS StyleClass, Style etc. 15. Use JSTL Tag <c:out> 16. Use JSTL Tag <c:if> 17. Use Struts-EL 18. Use <c:forEach> tag & implement an effective way to display Collection of Radio Boxes using <c:forEach>

  • /
      </source>
   
  
 
  



Exercise 4: Applying Gof and J2EE Patterns:Deploy to WebLogic and Test

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Technical Objectives for this exercise: The technical objectives of this exercise is to learn ?how to?: 1. A whole lot of patterns based code is added in this exercise. Hence no Struts related functionality is added. Just the Search Functionality with Database is Implemented 2. Gof Patterns - Factory Method, Abstract Factory are implemented 3. Core J2EE Patterns - Business Delegate, Session Facade, Transfer Object, Data Access Object are implemented Observe how patterns are applied and the Search functionality is implemented. This steps are not listed since they are not core to Struts usage that we want to illustrate. Time permitting, I will add this section later. Let us move on to important coverage of Struts features in subsequent exercises.

  • /
      </source>
   
  
 
  



Exercise 5: Search, List, Action Chaining, Editable List Form

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Business Objectives: The following business objectives will be met at the end of this exercise: 1. From the search results, click thru for customer details 2. Provide features to add, edit and delete customers 3. Add hours of operation for each day of week for Customer Technical Objectives for this exercise: The technical objectives of this exercise is to learn ?how to?: 1. Reuse Actions by passing the context via Request Parameters 2. Pre populate Form from database. 3. Regular Action Chaining (Clearly understand when to use and when not to) 4. Action Chaining by parameter passing 5. Use Multibox for a collection of checkbox 6. Use Editable List Form

  • /

// when I try to deploy the exercise06.jar, some exceptions are printed /* SEVERE: Exception sending context initialized event to listener instance of clas s struts.example.util.ApplicationScopeInit java.lang.NullPointerException

       at java.util.Properties$LineReader.readLine(Properties.java:365)
       at java.util.Properties.load(Properties.java:293)
       at struts.example.util.ApplicationScopeInit.contextInitialized(Unknown S

ource)

       at org.apache.catalina.core.StandardContext.listenerStart(StandardContex

t.java:3637)

       at org.apache.catalina.core.StandardContext.start(StandardContext.java:4

073)

  • /
      </source>
   
  
 
  



Exercise 6: Paging

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Business Objectives: The following business objectives will be met at the end of this exercise: 1. Implement Paging Technical Objectives for this exercise: The technical objectives of this exercise is to learn how to implement Paging using Pager taglib a. Start by adding pager taglib to web.xml and CustomerSearchList.jsp <taglib> <taglib-uri>/WEB-INF/pager-taglib.tld</taglib-uri> <taglib-location>/WEB-INF/pager-taglib.tld</taglib-location> </taglib> <%@ taglib uri="/WEB-INF/pager-taglib.tld" prefix="pg" %> b. Use <pg:pager> body tag to cover the entire list display <pg:pager url="customerlist.do" maxIndexPages="10" maxPageItems="5"> c. Use <pg:item> for each item iterated over <pg:item> </pg:item> <c:forEach var="customer" items="${CUSTOMER_SUMMARY_OBJECTS}"> </c:forEach> d. Add a new table containing <pg:index> block with the tags: <pg:prev>, <pg:pages>, <pg:next>



Exercise 7: Better Form and Action Handling

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Business Objectives: The following business objectives will be met at the end of this exercise: 1. Split customer form into multiple pages 2. Prevent the customer from going back and resubmitting and getting a database error. 3. Better Exception handling in the system Technical Objectives for this exercise: The technical objectives of this exercise is to learn how to: 19. To fix the bug: when Enter key is pressed in the Customer Search Form, a blank page is shown 20. Use DispatchAction 21. See how things work without exception handling mechanism 22. Provide exception handling mechanism (DuplicateCustomerException) 23. Create custom exception handlers 24. Provide Global exception handling mechanism with JSP 25. Create base ActionForm and Action Classes and use them 26. Create multipage forms. (Expln Only) 27. Handle Duplicate Form Submissions for CustomerForm (Expln Only) 28. Use DynaActionForm for CustomerSearchForm (Expln Only) Default enter does not do search in Customer Search Form 2. Using DispatchAction a. Create two methods Create and Edit (notice the case) in ShowCustomerAction so that each method taking exactly the same input parameters as the execute method. b. Add appropriate code into each of these methods c. Comment (or delete) the execute method 1. When Enter key is pressed in the Customer Search Form, a blank page is shown a. This happens because the CustomerSearchAction performs the search only if serch.x or search.y are not null. Remove the if condition and it will work for enter key ........

  • /

// when I try to deploy the exercise07.jar, some exceptions are printed /* SEVERE: Exception sending context initialized event to listener instance of clas s struts.example.util.ApplicationScopeInit java.lang.NullPointerException

       at java.util.Properties$LineReader.readLine(Properties.java:365)
       at java.util.Properties.load(Properties.java:293)
       at struts.example.util.ApplicationScopeInit.contextInitialized(Unknown S

ource)

       at org.apache.catalina.core.StandardContext.listenerStart(StandardContex

t.java:3637)

       at org.apache.catalina.core.StandardContext.start(StandardContext.java:4

073)

  • /


      </source>
   
  
 
  



Exercise 8: Creating Struts Modules

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Technical Objectives for this exercise: The technical objectives of this exercise is to learn ?how to?: Create Struts application modules and break monolithic struts module into pieces NOTE: 1. For the sake of maintaining simplicity and clarity in rest of the exercise, we will not attempt to 2. The index page belongs to the default module. From the index page, we will provide a link to go break the existing application into modules. Rather we will add a new module. to module2. Module 2 will consist of a two dummy pages that can call each other and also have a link to return to default module. a) Change the web.xml to define a new module named xyz as follows: <init-param> <param-name>config/xyz</param-name> <param-value>/WEB-INF/struts-config-xyz.xml</param-value> </init-param> b) Copy over the struts-config.xml to create a new struts-config-xyz.xml c) Create a empty XYZ Message Resources d) Clean up the struts-config-xyz.xml to retain only empty blocks for form-beans, action mappings etc. Add the message resource bundle definition to struts-config-xyz.xml. e) Add SwitchAction to struts-config.xml & struts-config-xyz.xml as follows: <action path="/switch" type="org.apache.struts.actions.SwitchAction"/> f) Create a folder called xyz under the src/web directory. Create two jsps: xyz-page1.jsp & xyzpage2. jsp (Copy over index.jsp & change contents) .....

  • /
      </source>
   
  
 
  



Exercise 9: Using Commons Validator with Struts

   <source lang="java">

/* First edition copyright 2004 ObjectSource LLC. All rights reserved. This training material and the accompanying lab exercises were prepared by Srikanth Shenoy for ObjectSource LLC. GRANT OF LICENSE: ObjecSource LLC grants you a non-exclusive license to use the material. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of ObjectSource LLC. At its discretion, ObjectSource LLC may provide limited support through email or discussion forums at ObjectSource web site. ObjectSource incurs no obligation to provide any support under this Agreement.

  • /

/* Technical Objectives for this exercise: The technical objectives of this exercise is to learn ?how to?: 1) Use Commons Validator to validate ActionForm a) We will add validations to CustomerSearchForm b) The first thing while using Commons Validator is to extend the ActionForm from a predefined ValidatorForm.

  • /
      </source>
   
  
 
  



Hibernate and Struts

   <source lang="java">

/* Struts Recipes By George Franciscus and Danilo Gurovich Publisher: Manning Publications Co. ISBN 1932394249

  • /


      </source>
   
  
 
  



In-container testing with StrutsTestCase and Cactus

   <source lang="java">

/* Struts Recipes By George Franciscus and Danilo Gurovich Publisher: Manning Publications Co. ISBN 1932394249

  • /


      </source>
   
  
 
  



Securing Struts Applications

   <source lang="java">

/*

  1. Title: Struts: The Complete Reference
  2. Author(s): James Holmes
  3. Publisher: McGraw-Hill/Osborne, 2004
  4. ISBN: 0-07-223131-9
  • /


      </source>
   
  
 
  



Struts application

   <source lang="java">

/* Programming Jakarta Struts By Chuck Cavaness ISBN: 0-596-00328-5

  • /
      </source>
   
  
 
  



Struts application 2

Struts: bank application

Struts: Creating the Controller

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /

//ch06_01.jsp <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html>

   <head>
       <title>Using <html> Tags</title>
       <script language="JavaScript">
           function clicker()
           {
               confirm("You clicked the button.");
           }
       </script>
   </head>
   
   <body>

Using <html> Tags

       <html:errors/>
       <html:form action="ch06_02.do" method="POST" enctype="multipart/form-data">

Text Fields:

           <html:text property="text"/>
           

Text Areas:

           <html:textarea property="textarea" rows="10"/>
           

Checkboxes:

           <html:checkbox property="checkbox"/>Check Me
           

Radio Buttons:

           <html:radio property="radio" value="red"/>red
           <html:radio property="radio" value="green"/>green
           <html:radio property="radio" value="blue"/>blue
           

Buttons:

           <html:button onclick="clicker()" value="Click Me" property="text"/>
           

Links:

           <html:link action="ch06_02">Click Me</html:link>
           

Images:

           <html:img page="/image.jpg"/>
           

Image Controls:

           <html:image page="/imagecontrol.jpg" property=""/>
           

Select Controls:

           <html:select property="multipleSelect" size="9" multiple="true">
               <html:option value="Multi 0">Multi 0</html:option>
               <html:option value="Multi 1">Multi 1</html:option>
               <html:option value="Multi 2">Multi 2</html:option>
               <html:option value="Multi 3">Multi 3</html:option>
               <html:option value="Multi 4">Multi 4</html:option>
               <html:option value="Multi 5">Multi 5</html:option>
               <html:option value="Multi 6">Multi 6</html:option>
               <html:option value="Multi 7">Multi 7</html:option>
               <html:option value="Multi 8">Multi 8</html:option>
           </html:select>

Multibox Controls:

               <html:multibox property="multiBox" value="a" />a
               <html:multibox property="multiBox" value="b" />b
               <html:multibox property="multiBox" value="c" />c
               <html:multibox property="multiBox" value="d" />d
               <html:multibox property="multiBox" value="e" />e
           

File Controls:

           <html:file property="file" />
           

<html:submit value="Submit"/> <html:cancel/> </html:form> </body>

</html:html> package ch06; import org.apache.struts.action.*; import org.apache.struts.upload.FormFile; import org.apache.struts.upload.MultipartRequestHandler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class ch06_03 extends ActionForm {

   private String text = "";
   private String X;
   private String Y;
   private String textarea = "";
   private String[] selectItems = new String[3];
   private String[] multiBox = new String[5];
   private boolean checkbox = false;
   private String radio = "";
   private FormFile file;
   private String fileText;
   
   public String getText() 
   {
       return text;
   }
   
   public void setText(String text) 
   {
       this.text = text;
   }
   
   public String getTextarea() 
   {
       return textarea;
   }
   
   public void setTextarea(String textarea) 
   {
       this.textarea = textarea;
   }
   public boolean getCheckbox() 
   {
       return checkbox;
   }
   
   public void setCheckbox(boolean checkbox) 
   {
       this.checkbox = checkbox;
   }
   
   public String getRadio() 
   {
       return radio;
   }
   
   public void setRadio(String radio) 
   {
       this.radio = radio;
   }
   
   public String getX() 
   {
       return X;
   }
   
   public void setX(String X) 
   {
       this.X = X;
   }
   
   public String getY() 
   {
       return Y;
   }
   
   public void setY(String Y) 
   {
       this.Y = Y;
   }
   public String[] getSelectItems() 
     {
       return selectItems;
   }
   
   public void setSelectItems(String[] selectItems) 
   {
       this.selectItems = selectItems;
   }
   
   public String[] getMultiBox() 
     {
       return multiBox;
   }
   
   public void setMultiBox(String[] multiBox) 
   {
       this.multiBox = multiBox;
   }
   
   private String[] multipleSelect = {"Multi 3", "Multi 5", "Multi 7"};
   public String[] getMultipleSelect() {
       return (this.multipleSelect);
   }
   public void setMultipleSelect(String multipleSelect[]) {
       this.multipleSelect = multipleSelect;
   }
   public FormFile getFile() {
       return file;
   }
   public void setFile(FormFile file) {
       this.file = file;
   }
   public String getFileText() {
       try {
           ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
           InputStream input = file.getInputStream();
           byte[] dataBuffer = new byte[4096];
           int numberBytes = 0;
           while ((numberBytes = input.read(dataBuffer, 0, 4096)) != -1) {
               byteStream.write(dataBuffer, 0, numberBytes);
           }
           fileText = new String(byteStream.toByteArray());
           input.close();
       }
       catch (IOException e) {
           return null;
       }
       return fileText;
   }
   public void reset(ActionMapping mapping, HttpServletRequest request) 
   {
   }

} package ch06; import java.io.*; import java.util.*; import ch06.ch06_03; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.struts.action.*; public class ch06_02 extends Action {

 public ActionForward execute(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       ActionErrors actionerrors = new ActionErrors();
               
       ch06_03 dataForm = (ch06_03)form;
       
       String text = dataForm.getText();        
       if(text.trim().equals("")) {
           actionerrors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.notext"));
       }
       
       if(actionerrors.size() != 0) {            
           saveErrors(request, actionerrors);
           return new ActionForward(mapping.getInput());            
       }
       return mapping.findForward("success");
   }

}

      </source>
   
  
 
  



Struts: Creating the Model

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /

//ch05_03.jsp <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <HTML>

   <HEAD>
       <TITLE>Using Include Actions</TITLE>
   </HEAD>
   
   <BODY>

Using Include Actions

       <html:form action="ch05_04.do">
           Enter some text
           <html:text property="text"/>
           <html:submit value="Submit"/>
       </html:form>
   </BODY>

</HTML>

//ch05_07.jsp <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <HTML>

   <HEAD>
       <TITLE>Select an action to dispatch</TITLE>
   </HEAD>
   
   <BODY>

Select an action to dispatch

       <html:form action="ch05_05.do">
           <html:select property="method">
               <html:option value="red">Red</html:option>
               <html:option value="yellow">Yellow</html:option>
               <html:option value="green">Green</html:option>
           </html:select>
           


<html:submit /> </html:form> </BODY>

</html>

//ch05_11.jsp <%@ taglib uri="/tags/struts-bean" prefix="bean" %> <%@ taglib uri="/tags/struts-html" prefix="html" %> <HTML>

   <HEAD>
       <TITLE>Using LookupDispatchAction</TITLE>
   </HEAD>
   
   <BODY>

Using LookupDispatchAction

       <html:form action="ch05_09.do">
           Select an action to dispatch:
           <html:select property="method">
               <html:option value="red">Red</html:option>
               <html:option value="yellow">Yellow</html:option>
               <html:option value="green">Green</html:option>
           </html:select>
           


<html:submit /> </html:form> </BODY>

</html>

//ch05_08.jsp <HTML>

   <HEAD>
       <TITLE>Success</TITLE>
   </HEAD>
   
   <BODY>

Success

       The action has been dispatched.
   </BODY>

</html>

//ch05_12.jsp <HTML>

   <HEAD>
       <TITLE>Success</TITLE>
   </HEAD>
   
   <BODY>

Success

       The action has been dispatched.
   </BODY>

</HTML> package ch05; import java.io.*; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.struts.action.*; import org.apache.struts.actions.DispatchAction; public class ch05_05 extends DispatchAction {

 public ActionForward red(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       System.out.println("Stop.");
       return mapping.findForward("success");
   }
 public ActionForward yellow(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       System.out.println("Caution.");
       return mapping.findForward("success");
   }
 public ActionForward green(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       System.out.println("Go.");
       return mapping.findForward("success");
   }

} package ch05; import org.apache.struts.action.ActionForm; public class ch05_02 extends ActionForm {

   private String text = "Hello";
   
   public String getText() 
   {
       return text;
   }
   
   public void setText(String text) 
   {
       this.text = text;
   }

}

package ch05; import org.apache.struts.action.ActionForm; public class ch05_10 extends ActionForm {

   private String method = "";
   
   public String getmethod() 
   {
       return method;
   }
   
   public void setMethod(String method) 
   {
       this.method = method;
   }

}

package ch05; import java.io.*; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.struts.action.*; import org.apache.struts.actions.LookupDispatchAction; public class ch05_09 extends LookupDispatchAction {

 public ActionForward red(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       System.out.println("Stop.");
       return mapping.findForward("success");
   }
 public ActionForward yellow(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       System.out.println("Caution.");
       return mapping.findForward("success");
   }
 public ActionForward green(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       System.out.println("Go.");
       return mapping.findForward("success");
   }
  protected Map getKeyMethodMap()
  {
      Map map = new HashMap();
      map.put("ch05.red", "red");
      map.put("ch05.yellow", "yellow");
      map.put("ch05.green", "green");
      return map;
  }

} package ch05; import org.apache.struts.action.ActionForm; public class ch05_06 extends ActionForm {

   private String method = "";
   
   public String getmethod() 
   {
       return method;
   }
   
   public void setMethod(String method) 
   {
       this.method = method;
   }

}

      </source>
   
  
 
  



Struts Creating the View

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /


      </source>
   
  
 
  



Struts example

   <source lang="java">

/* This product includes software developed by The Apache Software Foundation (http://www.apache.org/).

  • /


      </source>
   
  
 
  



Struts Framework

   <source lang="java">

/* Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X

  • /


      </source>
   
  
 
  



Struts Framework: A Sample Struts Application

   <source lang="java">

/*

  1. Title: Struts: The Complete Reference
  2. Author(s): James Holmes
  3. Publisher: McGraw-Hill/Osborne, 2004
  4. ISBN: 0-07-223131-9
  • /

//index.jsp <%@ taglib uri="/WEB-INF/tlds/struts-html.tld" prefix="html" %> <html> <head> <title>ABC, Inc. Human Resources Portal</title> </head> <body> ABC, Inc. Human Resources Portal


&#149; Add an Employee
&#149; <html:link forward="search">Search for Employees</html:link>
</body> </html> //search.jsp <%@ taglib uri="/WEB-INF/tlds/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/tlds/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/tlds/struts-logic.tld" prefix="logic" %> <html> <head> <title>ABC, Inc. Human Resources Portal - Employee Search</title> </head> <body> ABC, Inc. Human Resources Portal - Employee Search


<html:errors/> <html:form action="/search">

<bean:message key="label.search.name"/>: <html:text property="name"/>
-- or --
<bean:message key="label.search.ssNum"/>: <html:text property="ssNum"/> (xxx-xx-xxxx)
<html:submit/>

</html:form> <logic:present name="searchForm" property="results">


<bean:size id="size" name="searchForm" property="results"/> <logic:equal name="size" value="0">

No Employees Found

</logic:equal> <logic:greaterThan name="size" value="0">

<logic:iterate id="result" name="searchForm" property="results"> </logic:iterate>
Name Social Security Number
<bean:write name="result" property="name"/> <bean:write name="result" property="ssNum"/>

</logic:greaterThan> </logic:present> </body> </html> package com.jamesholmes.minihr; public class Employee {

 private String name;
 private String ssNum;
 public Employee(String name, String ssNum) {
   this.name = name;
   this.ssNum = ssNum;
 }
 public void setName(String name) {
   this.name = name;
 }
 public String getName() {
   return name;
 }
 public void setSsNum(String ssNum) {
   this.ssNum = ssNum;
 }
 public String getSsNum() {
   return ssNum;
 }

} package com.jamesholmes.minihr; import java.util.ArrayList; public class EmployeeSearchService {

 /* Hard-coded sample data. Normally this would come from a real data
    source such as a database. */
 private static Employee[] employees = 
 {
   new Employee("Bob Davidson", "123-45-6789"),
   new Employee("Mary Williams", "987-65-4321"),
   new Employee("Jim Smith", "111-11-1111"),
   new Employee("Beverly Harris", "222-22-2222"),
   new Employee("Thomas Frank", "333-33-3333"),
   new Employee("Jim Davidson", "444-44-4444")
 };
 // Search for employees by name.
 public ArrayList searchByName(String name) {
   ArrayList resultList = new ArrayList();
   for (int i = 0; i < employees.length; i++) {
     if (employees[i].getName().toUpperCase().indexOf(name.toUpperCase()) != -1) {
       resultList.add(employees[i]);
     }
   }
   return resultList;
 }
 // Search for employee by social security number.
 public ArrayList searchBySsNum(String ssNum) {
   ArrayList resultList = new ArrayList();
   for (int i = 0; i < employees.length; i++) {
     if (employees[i].getSsNum().equals(ssNum)) {
       resultList.add(employees[i]);
     }
   }
   return resultList;
 }

} package com.jamesholmes.minihr; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public final class SearchAction extends Action {

 public ActionForward execute(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws Exception
 {
   EmployeeSearchService service = new EmployeeSearchService();
   ArrayList results;
   SearchForm searchForm = (SearchForm) form;
   // Perform employee search based on what criteria was entered.
   String name = searchForm.getName();
   if (name != null && name.trim().length() > 0) {
     results = service.searchByName(name);
   } else {
     results = service.searchBySsNum(searchForm.getSsNum().trim());
   }
   // Place search results in SearchForm for access by JSP.
   searchForm.setResults(results);
   // Forward control to this Action"s input page.
   return mapping.getInputForward();
 }

} package com.jamesholmes.minihr; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; public class SearchForm extends ActionForm {

 private String name = null;
 private String ssNum = null;
 private List results = null;
 public void setName(String name) {
   this.name = name;
 }
 public String getName() {
   return name;
 }
 public void setSsNum(String ssNum) {
   this.ssNum = ssNum;
 }
 public String getSsNum() {
   return ssNum;
 }
 public void setResults(List results) {
   this.results = results;
 }
 public List getResults() {
   return results;
 }
 // Reset form fields.
 public void reset(ActionMapping mapping, HttpServletRequest request)
 {
   name = null;
   ssNum = null;
   results = null;
 }
 // Validate form data.
 public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request)
 {
   ActionErrors errors = new ActionErrors();
   boolean nameEntered = false;
   boolean ssNumEntered = false;
   // Determine if name has been entered.
   if (name != null && name.length() > 0) {
     nameEntered = true;
   }
   // Determine if social security number has been entered.
   if (ssNum != null && ssNum.length() > 0) {
     ssNumEntered = true;
   }
   /* Validate that either name or social security number
      has been entered. */
   if (!nameEntered && !ssNumEntered) {
     errors.add(null,
       new ActionError("error.search.criteria.missing"));
   }
   /* Validate format of social security number if
      it has been entered. */
   if (ssNumEntered && !isValidSsNum(ssNum.trim())) {
     errors.add("ssNum",
       new ActionError("error.search.ssNum.invalid"));
   }
   return errors;
 }
 // Validate format of social security number.
 private static boolean isValidSsNum(String ssNum) {
   if (ssNum.length() < 11) {
     return false;
   }
   for (int i = 0; i < 11; i++) {
     if (i == 3 || i == 6) {
       if (ssNum.charAt(i) != "-") {
         return false;
       }
     } else if ("0123456789".indexOf(ssNum.charAt(i)) == -1) {
       return false;
     }
   }
   return true;
 }

}


      </source>
   
  
 
  



Struts Framework: Declarative Exception Handling

   <source lang="java">

/*

  1. Title: Struts: The Complete Reference
  2. Author(s): James Holmes
  3. Publisher: McGraw-Hill/Osborne, 2004
  4. ISBN: 0-07-223131-9
  • /


      </source>
   
  
 
  



Struts Framework: Tiles

   <source lang="java">

/*

  1. Title: Struts: The Complete Reference
  2. Author(s): James Holmes
  3. Publisher: McGraw-Hill/Osborne, 2004
  4. ISBN: 0-07-223131-9
  • /


      </source>
   
  
 
  



Struts Framework Validator

   <source lang="java">

/*

  1. Title: Struts: The Complete Reference
  2. Author(s): James Holmes
  3. Publisher: McGraw-Hill/Osborne, 2004
  4. ISBN: 0-07-223131-9
  • /


      </source>
   
  
 
  



Struts: Generate a response with XSL

   <source lang="java">

/* Struts Recipes By George Franciscus and Danilo Gurovich Publisher: Manning Publications Co. ISBN 1932394249

  • /


      </source>
   
  
 
  



Struts: Internationalizing Struts Applications

   <source lang="java">

/*

  1. Title: Struts: The Complete Reference
  2. Author(s): James Holmes
  3. Publisher: McGraw-Hill/Osborne, 2004
  4. ISBN: 0-07-223131-9
  • /


      </source>
   
  
 
  



Struts Recipes: Build Struts with Ant

   <source lang="java">

/* Struts Recipes By George Franciscus and Danilo Gurovich Publisher: Manning Publications Co. ISBN 1932394249

  • /


      </source>
   
  
 
  



Testing Struts Applications

   <source lang="java">

/*

  1. Title: Struts: The Complete Reference
  2. Author(s): James Holmes
  3. Publisher: McGraw-Hill/Osborne, 2004
  4. ISBN: 0-07-223131-9
  • /


      </source>
   
  
 
  



The Struts and Tags

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /

//ch09_01.jsp <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> <html:html>

   <head>
   <title>Using the Struts Validator</title>
   <html:base/>

</head> <body>

Using the Struts Validator

   <logic:messagesPresent>
       <bean:message key="errors.header"/>
    <html:messages id="error" property="byte">
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="short">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="integer">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="long">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="float">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="floatRange">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="double">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="date">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="creditCard">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="city">
    
  • <bean:write name="error"/>
  •            </html:messages>
               <html:messages id="error" property="zip">
    
  • <bean:write name="error"/>
  •            </html:messages>
    

   </logic:messagesPresent>
   <html:form action="ch09_02">
     <bean:message key="ch09_03.byte.text"/>
      
      
      
     <html:text property="byte" size="15" maxlength="15"/>
     

<bean:message key="ch09_03.short.text"/>       <html:text property="short" size="15" maxlength="15"/>

<bean:message key="ch09_03.integer.text"/>       <html:text property="integer" size="15" maxlength="15"/>

<bean:message key="ch09_03.long.text"/>       <html:text property="long" size="15" maxlength="15"/>

<bean:message key="ch09_03.float.text"/>       <html:text property="float" size="15" maxlength="15"/>

<bean:message key="ch09_03.floatRange.text"/>       <html:text property="floatRange" size="15" maxlength="15"/>

<bean:message key="ch09_03.double.text"/>       <html:text property="double" size="15" maxlength="15"/>

<bean:message key="ch09_03.date.text"/>       <html:text property="date" size="15" maxlength="15"/>

<bean:message key="ch09_03.creditCard.text"/>       <html:text property="creditCard" size="16" maxlength="16"/>

<bean:message key="ch09_03.city.text"/>       <html:text property="city" size="16" maxlength="16"/>

<bean:message key="ch09_03.zip.text"/>       <html:text property="zip" size="5" maxlength="5"/>

<html:submit property="submit"> Submit </html:submit>   <html:reset> Reset </html:reset>

</html:form> </body> </html:html> //ch09_04.jsp <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <HTML>

   <HEAD>
       <TITLE>Here"s Your Data...</TITLE>
   </HEAD>
   
   <BODY>

Here"s Your Data...

       <bean:message key="ch09_03.byte.text"/>: 
       <bean:write name="ch09_03" property="byte"/>
       

<bean:message key="ch09_03.short.text"/>: <bean:write name="ch09_03" property="short"/>

<bean:message key="ch09_03.integer.text"/>: <bean:write name="ch09_03" property="integer"/>

<bean:message key="ch09_03.long.text"/>: <bean:write name="ch09_03" property="long"/>

<bean:message key="ch09_03.float.text"/>: <bean:write name="ch09_03" property="float"/>

<bean:message key="ch09_03.floatRange.text"/>: <bean:write name="ch09_03" property="floatRange"/>

<bean:message key="ch09_03.double.text"/>: <bean:write name="ch09_03" property="double"/>

<bean:message key="ch09_03.date.text"/>: <bean:write name="ch09_03" property="date"/>

<bean:message key="ch09_03.creditCard.text"/>: <bean:write name="ch09_03" property="creditCard"/>

<bean:message key="ch09_03.city.text"/>: <bean:write name="ch09_03" property="city"/>

<bean:message key="ch09_03.zip.text"/>: <bean:write name="ch09_03" property="zip"/>
</BODY>

</HTML> package ch09; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.*; public final class ch09_02 extends Action {

   public ActionForward execute(ActionMapping mapping,
       ActionForm form,
       HttpServletRequest request,
       HttpServletResponse response)
       throws Exception 
   {
       return mapping.findForward("success");
   }

} package ch09; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; import org.apache.struts.validator.ValidatorForm;

public final class ch09_03 extends ValidatorForm {

   private String byteData = null;
   private String shortData = null;
   private String integerData = null;
   private String longData = null;
   private String floatData = null;
   private String floatDataRange = null;
   private String doubleData = null;
   private String dateData = null;
   private String creditData = null;
   private String cityData = null;
   private String zipData = null;
   public String getByte() 
   {
      return byteData;
   }
   public void setByte(String byteData) 
   {
        this.byteData = byteData;
   }
   public String getShort() 
   {
      return shortData;
   }
   public void setShort(String shortData) 
   {
        this.shortData = shortData;
   }
   public String getInteger() 
   {
      return integerData;
   }
   public void setInteger(String integerData) 
   {
        this.integerData = integerData;
   }
   public String getLong() 
   {
      return longData;
   }
   public void setLong(String longData) 
   {
        this.longData = longData;
   }
   public String getFloat() 
   {
      return floatData;
   }
   public void setFloat(String floatData) 
   {
        this.floatData = floatData;
   }
   public String getFloatRange() 
   {
      return floatDataRange;
   }
   public void setFloatRange(String floatDataRange) 
   {
         this.floatDataRange = floatDataRange;
   }
   public String getDouble() 
   {
      return doubleData;
   }
   public void setDouble(String doubleData) 
   {
        this.doubleData = doubleData;
   }
   public String getDate() 
   {
      return dateData;
   }
   public void setDate(String dateData) 
   {
        this.dateData = dateData;
   }
   public String getCreditCard() 
   {
      return creditData;
   }
   public void setCreditCard(String creditData) 
   {
        this.creditData = creditData;
   }
   public String getCity() 
   {
      return cityData;
   }
   public void setCity(String cityData) 
   {
        this.cityData = cityData;
   }
   public String getZip() 
   {
      return zipData;
   }
   public void setZip(String zipData)   
   {
        this.zipData = zipData;
   }
   public void reset(ActionMapping mapping, HttpServletRequest request) 
   {
      byteData = null;
      shortData = null;
      integerData = null;
      longData = null;
      floatData = null;
      floatDataRange = null;
      doubleData = null;
      dateData = null;
      creditData = null;
      cityData = null;
      zipData = null;
   }

}

      </source>
   
  
 
  



The Struts Tags

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /

//ch08_01.jsp <%@ taglib prefix="ch08" uri="WEB-INF/ch08_02.tld" %> <HTML>

   <HEAD>
       <TITLE>Inserting Text With Custom Tags</TITLE>
   </HEAD>
   <BODY>

Inserting Text With Custom Tags

       <ch08:message />
   </BODY>

</HTML> //ch08_04.jsp <%@ taglib prefix="ch08" uri="WEB-INF/ch08_05.tld" %> <HTML>

 <HEAD>
       <TITLE>Handling Custom Tag Attributes</TITLE>
   </HEAD>
   <BODY>

Handling Custom Tag Attributes

       <ch08:message text="This text was set using an attribute."/>
   </BODY>

</HTML> //ch08_07.jsp <%@ taglib prefix="ch08" uri="WEB-INF/ch08_08.tld" %> <HTML>

   <HEAD>
       <TITLE>Creating Iterating Tags</TITLE>
   </HEAD>
   <BODY>

Creating Iterating Tags

       <%
           String[] toppings = new String[]{ "Pepperoni", "Sausage", "Ham", "Olives" };
           pageContext.setAttribute("toppings", toppings);
       %>
       <ch08:iterator>
           Topping: 
       </ch08:iterator>
   </BODY>

</HTML> //ch08_10.jsp <%@ taglib prefix="ch08" uri="WEB-INF/ch08_11.tld" %> <HTML>

   <HEAD>
       <TITLE>Creating Cooperating Tags</TITLE>
   </HEAD>
   <BODY>

Creating Cooperating Tags

       <ch08:createToppings/>
       <ch08:iterator>
           Topping: 
       </ch08:iterator>
   </BODY>

</HTML> //ch08_13.jsp <%@ taglib prefix="ch08" uri="WEB-INF/ch08_15.tld" %> <HTML>

   <HEAD>
       <TITLE>Custom Tags and Variables</TITLE>
   </HEAD>
   <BODY>

Custom Tags and Variables

       <ch08:createToppings/>
       <%
           for(int loopIndex = 0; loopIndex < toppings.length; loopIndex++) {
               out.println("Topping: " + toppings[loopIndex] + "
"); }  %> </BODY>

</HTML> package ch08; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; public class ch08_03 extends TagSupport {

 public int doEndTag() throws JspException 

{

   try {
     pageContext.getOut().print("This text is from the custom tag.");
   } catch (Exception e) {
     throw new JspException(e.toString());
   } 
   return EVAL_PAGE;
 } 

}

package ch08; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; public class ch08_06 extends TagSupport {

 String text;
 public void setText(String s) {
   text = s;
 } 
 public int doEndTag() throws JspException 

{

   try {
     pageContext.getOut().print(text);
   } catch (Exception e) {
     throw new JspException(e.toString());
   } 
   return EVAL_PAGE;
 } 

} package ch08; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class ch08_09 extends TagSupport{

 private int iterationCounter = 0;
 private String[] toppings = null;
 public int doStartTag()
 {
   toppings = (String[]) pageContext.getAttribute("toppings");
   return EVAL_BODY_INCLUDE;
 }
 public int doAfterBody() throws JspException
 {
   try{
     pageContext.getOut().print(" " + toppings[iterationCounter] + "
"); } catch(Exception e){ throw new JspException(e.toString()); } iterationCounter++; if(iterationCounter >= toppings.length) { return SKIP_BODY; } return EVAL_BODY_AGAIN; }

}

package ch08; import javax.servlet.jsp.tagext.*; public class ch08_12 extends TagSupport {

 public int doStartTag() {
   String[] toppings = new String[] {"Pepperoni", "Sausage", "Ham", "Olives"};
   pageContext.setAttribute("toppings", toppings);
   return SKIP_BODY;
 } 

}

      </source>
   
  
 
  



Using bean:resource to expose the struts.config.xml to your view

   <source lang="java">

/* Struts Recipes By George Franciscus and Danilo Gurovich Publisher: Manning Publications Co. ISBN 1932394249

  • /
      </source>
   
  
 
  



Web Services and the Validator and Tile Packages

   <source lang="java">

/* Title: Struts : Essential Skills (Essential Skills) Authors: Steven Holzner Publisher: McGraw-Hill Osborne Media ISBN: 0072256591

  • /

//ch10_01.jsp <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> <tiles:insert page="Layout.jsp" flush="true">

 <tiles:put name="title"  value="Using Tiles" />
 <tiles:put name="header" value="header.jsp" />
 <tiles:put name="footer" value="footer.jsp" />
 <tiles:put name="menu"   value="menu.jsp" />
 <tiles:put name="body"   value="body.jsp" />

</tiles:insert> //ch10_02.jsp <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> <tiles:insert page="Layout.jsp" flush="true">

 <tiles:put name="title"  value="Using putList" />
 <tiles:put name="header" value="header.jsp" />
 <tiles:put name="footer" value="footer.jsp" />
 <tiles:put name="menu"   value="menu.jsp" />
 <tiles:put name="body"   value="list.jsp" />

</tiles:insert> //ch10_03.jsp <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> <tiles:definition id="theDefinition" template="/Layout.jsp" >

 <tiles:put name="title"  value="My first page" />
 <tiles:put name="header" value="/header.jsp" />
 <tiles:put name="footer" value="/footer.jsp" />
 <tiles:put name="menu"   value="/menu.jsp" />
 <tiles:put name="body"   value="/body.jsp" />

</tiles:definition> <tiles:insert beanName="theDefinition" flush="true" /> //ch10_04.jsp <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> <tiles:insert definition="tilesDefinition" flush="true" /> //ch10_05.jsp <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> <tiles:insert definition="tilesDefinition" flush="true" >

 <tiles:put name="title" value="Overloading Definitions" />
 <tiles:put name="header" value="/overloadedHeader.jsp" />

</tiles:insert> //ch10_06.jsp <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> <tiles:insert definition="tilesExtendedDefinition" flush="true" /> //ch10_07.jsp <%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %> <tiles:insert definition="attributeDefinition" flush="true" /> //ch10_08.jsp <%@ taglib uri="/tags/struts-html" prefix="html" %> <%@ taglib uri="/tags/struts-logic" prefix="logic" %> <html:html>

   <head>
       <title>Using <logic> Tags</title>
   </head>
   
   <body>

Using <logic> Tags

       <html:form action="ch10_09.do">

Enter your data:

           <html:text property="text"/>
           

<html:submit value="Submit"/> <html:cancel/> </html:form> </body>

</html:html> package ch10; import java.io.*; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.struts.action.*; public class ch10_09 extends Action {

 public ActionForward execute(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response)
   throws IOException, ServletException {
       return mapping.findForward("success");
   }

} package ch10; import org.apache.struts.action.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ch10_10 extends ActionForm {

   private String empty = "";
   private String text = "";
   private int number;
   
   public String getEmpty() 
   {
       return empty;
   }
   
   public void setEmpty(String text) 
   {
   }
   
   public String getText() 
   {
       return text;
   }
   
   public void setText(String text) 
   {
       this.text = text;
       this.number = Integer.parseInt(text);
   }
   
   public int getNumber() 
   {
       return number;
   }
   
   public void setNumber(int number) 
   {
       this.number = number;
   }

}

      </source>