Java/J2EE/Struts
Содержание
- 1 A Full Struts Application
- 2 Blank Struts template
- 3 Create a pluggable validator for cross-form validation 2
- 4 Creating Custom Tags
- 5 Essential Struts Action
- 6 Exercise 10: Using Struts and Tiles
- 7 Exercise 1: Building your first Struts Application
- 8 Exercise 2: Improving your first Struts Application
- 9 Exercise 3: Using JSTL, Struts-EL etc
- 10 Exercise 4: Applying Gof and J2EE Patterns:Deploy to WebLogic and Test
- 11 Exercise 5: Search, List, Action Chaining, Editable List Form
- 12 Exercise 6: Paging
- 13 Exercise 8: Creating Struts Modules
- 14 Exercise 9: Using Commons Validator with Struts
- 15 Hibernate and Struts
- 16 In-container testing with StrutsTestCase and Cactus
- 17 Securing Struts Applications
- 18 Struts application
- 19 Struts application 2
- 20 Struts: bank application
- 21 Struts: Creating the Controller
- 22 Struts: Creating the Model
- 23 Struts Creating the View
- 24 Struts example
- 25 Struts Framework
- 26 Struts Framework: A Sample Struts Application
- 27 Struts Framework: Declarative Exception Handling
- 28 Struts Framework: Tiles
- 29 Struts Framework Validator
- 30 Struts: Generate a response with XSL
- 31 Struts: Internationalizing Struts Applications
- 32 Struts Recipes: Build Struts with Ant
- 33 Testing Struts Applications
- 34 The Struts and Tags
- 35 The Struts Tags
- 36 Using bean:resource to expose the struts.config.xml to your view
- 37 Web Services and the Validator and Tile Packages
A Full Struts Application
/*
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">
<font color="red">
ERROR: Application resources not loaded -- check servlet container
logs for error messages.
</font>
</logic:notPresent>
<h1>Reading User Input</h1>
<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>
<H1>The Struts Cafe</H1>
<html:errors/>
<ch03:items/>
<ch03:toppings/>
<html:form action="ch03_04.do">
<TABLE>
<TR>
<TD ALIGN="LEFT" VALIGN="TOP">
<bean:message key="toppings"/>
<BR>
<logic:iterate id="toppings1" name="toppings">
<html:multibox property="toppings">
<%= toppings1 %>
</html:multibox>
<%= toppings1 %>
<BR>
</logic:iterate>
</TD>
<TD ALIGN="LEFT" VALIGN="TOP">
<bean:message key="items"/>
<BR>
<html:select property="items">
<html:options name="items"/>
</html:select>
</TD>
</TR>
<TR>
<TD ALIGN="LEFT">
<BR>
<bean:message key="email"/>
<html:text property="email"/>
</TD>
<TR>
</TABLE>
<BR>
<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");
}
}
Blank Struts template
/*
This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).
*/
Create a pluggable validator for cross-form validation 2
/*
Struts Recipes
By George Franciscus and Danilo Gurovich
Publisher: Manning Publications Co.
ISBN 1932394249
*/
Creating Custom Tags
/*
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>
<h1>Using <logic> Tags</h1>
<html:form action="ch07_02.do">
<h2>Enter your data:</h2>
<html:text property="text"/>
<br>
<br>
<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>
<H1>Here"s Your Data...</H1>
<h2>The text field text:</h2>
<bean:write name="ch07_03" property="text"/>
<BR>
<h2>Using <logic:empty name="ch07_03" property="empty"></h2>
<logic:empty name="ch07_03" property="empty">
Results: Empty
</logic:empty>
<BR>
<h2>Using <logic:notEmpty name="ch07_03" property="text"></h2>
<logic:notEmpty name="ch07_03" property="text">
Results: Not empty
</logic:notEmpty>
<BR>
<h2>Using <logic:equal name="ch07_03" property="number" value="6"></h2>
<logic:equal name="ch07_03" property="number" value="6">
Results: Equal
</logic:equal>
<BR>
<h2>Using <logic:notEqual> name="ch07_03" property="number" value="7"</h2>
<logic:notEqual name="ch07_03" property="number" value="7">
Results: Not equal
</logic:notEqual>
<BR>
<h2>Using <logic:greaterEqual name="ch07_03" property="number" value="3"></h2>
<logic:greaterEqual name="ch07_03" property="number" value="3">
Results: Greater than or equal
</logic:greaterEqual>
<BR>
<h2>Using <logic:greaterThan name="ch07_03" property="number" value="4"></h2>
<logic:greaterThan name="ch07_03" property="number" value="4">
Results: Greater than
</logic:greaterThan>
<BR>
<h2>Using <logic:lessEqual name="ch07_03" property="number" value="8"></h2>
<logic:lessEqual name="ch07_03" property="number" value="8">
Results: Less than or equal
</logic:lessEqual>
<BR>
<h2>Using <logic:lessThan name="ch07_03" property="number" value="8"></h2>
<logic:lessThan name="ch07_03" property="number" value="8">
Results: Less than
</logic:lessThan>
<BR>
<h2>Using <logic:match name="ch07_03" property="text" value="6"></h2>
<logic:match name="ch07_03" property="text" value="6">
Results: Matched
</logic:match>
<BR>
<h2>Using <logic:notMatch name="ch07_03" property="number" value="9"></h2>
<logic:notMatch name="ch07_03" property="number" value="9">
Results: No match
</logic:notMatch>
<BR>
<h2>Using <logic:present name="ch07_03" property="number"></h2>
<logic:present name="ch07_03" property="number">
Results: Present
</logic:present>
<BR>
<h2>Using <logic:notPresent name="ch07_03" property="fish"></h2>
<logic:notPresent name="ch07_03" property="fish">
Results: Not present
</logic:notPresent>
<BR>
</BODY>
</HTML>
//ch07_05.jsp
<%@ taglib uri="/tags/struts-html" prefix="html" %>
<html:html>
<head>
<title>Using <bean> Tags</title>
</head>
<body>
<h1>Using <bean> Tags</h1>
<%
Cookie cookie1 = new Cookie("message", "Hello!");
cookie1.setMaxAge(24 * 60 * 60);
response.addCookie(cookie1);
%>
<html:form action="ch07_06.do">
<h2>Enter your data:</h2>
<html:text property="text"/>
<br>
<br>
<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>
<H1>Here"s Your Data...</H1>
<h2>The text field text:</h2>
<bean:write name="ch07_07" property="text"/>
<BR>
<h2>The cookie data:</h2>
<bean:cookie id="messageCookie" name="message"/>
<%= messageCookie.getValue() %>
<BR>
<h2>The new variable:</h2>
<bean:define id="variable" name="ch07_07" property="text"/>
<%= variable %>
<BR>
<h2>The user-agent header data:</h2>
<bean:header id="headerObject" name="user-agent"/>
<%= headerObject %>
<BR>
<h2>The parameter data:</h2>
<bean:parameter id="text" name="text"/>
<%= text %>
<BR>
<h2>The mapping data:</h2>
<bean:struts id="mapping" mapping="/ch07_06"/>
<% String[] a = mapping.findForwards();
out.println(a[0]); %>
<BR>
</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");
}
}
Essential Struts Action
/*
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">
<h1>A Sample Welcome Page</h1>
<logic:notPresent name="org.apache.struts.action.MESSAGE" scope="application">
<font color="red">
ERROR: Application resources not loaded -- check servlet container
logs for error messages.
</font>
</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>
<h1>A Sample Results Page</h1>
<%= 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));
}
}
Exercise 10: Using Struts and Tiles
/*
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
....
*/
Exercise 1: Building your first Struts Application
/*
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)]
*/
Exercise 2: Improving your first Struts Application
/*
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
*/
Exercise 3: Using JSTL, Struts-EL etc
/*
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>
*/
Exercise 4: Applying Gof and J2EE Patterns:Deploy to WebLogic and Test
/*
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.
*/
Exercise 5: Search, List, Action Chaining, Editable List Form
/*
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)
*/
Exercise 6: Paging
/*
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 ==
<!-- start source code -->
<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)
*/
Exercise 8: Creating Struts Modules
/*
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)
.....
*/
Exercise 9: Using Commons Validator with Struts
/*
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.
*/
Hibernate and Struts
/*
Struts Recipes
By George Franciscus and Danilo Gurovich
Publisher: Manning Publications Co.
ISBN 1932394249
*/
In-container testing with StrutsTestCase and Cactus
/*
Struts Recipes
By George Franciscus and Danilo Gurovich
Publisher: Manning Publications Co.
ISBN 1932394249
*/
Securing Struts Applications
/*
# Title: Struts: The Complete Reference
# Author(s): James Holmes
# Publisher: McGraw-Hill/Osborne, 2004
# ISBN: 0-07-223131-9
*/
Struts application
/*
Programming Jakarta Struts
By Chuck Cavaness
ISBN: 0-596-00328-5
*/
Struts application 2
Struts: bank application
Struts: Creating the Controller
/*
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>
<h1>Using <html> Tags</h1>
<html:errors/>
<html:form action="ch06_02.do" method="POST" enctype="multipart/form-data">
<h2>Text Fields:</h2>
<html:text property="text"/>
<br>
<h2>Text Areas:</h2>
<html:textarea property="textarea" rows="10"/>
<br>
<h2>Checkboxes:</h2>
<html:checkbox property="checkbox"/>Check Me
<br>
<h2>Radio Buttons:</h2>
<html:radio property="radio" value="red"/>red
<html:radio property="radio" value="green"/>green
<html:radio property="radio" value="blue"/>blue
<br>
<h2>Buttons:</h2>
<html:button onclick="clicker()" value="Click Me" property="text"/>
<br>
<h2>Links:</h2>
<html:link action="ch06_02">Click Me</html:link>
<br>
<h2>Images:</h2>
<html:img page="/image.jpg"/>
<br>
<h2>Image Controls:</h2>
<html:image page="/imagecontrol.jpg" property=""/>
<br>
<h2>Select Controls:</h2>
<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>
<h2>Multibox Controls:</h2>
<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
<br>
<h2>File Controls:</h2>
<html:file property="file" />
<br>
<br>
<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");
}
}
Struts: Creating the Model
/*
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>
<H1>Using Include Actions</H1>
<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>
<H1>Select an action to dispatch</H1>
<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>
<BR>
<BR>
<BR>
<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>
<H1>Using LookupDispatchAction</H1>
<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>
<BR>
<BR>
<BR>
<html:submit />
</html:form>
</BODY>
</html>
//ch05_08.jsp
<HTML>
<HEAD>
<TITLE>Success</TITLE>
</HEAD>
<BODY>
<H1>Success</H1>
The action has been dispatched.
</BODY>
</html>
//ch05_12.jsp
<HTML>
<HEAD>
<TITLE>Success</TITLE>
</HEAD>
<BODY>
<H1>Success</H1>
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;
}
}
Struts Creating the View
/*
Title: Struts : Essential Skills (Essential Skills)
Authors: Steven Holzner
Publisher: McGraw-Hill Osborne Media
ISBN: 0072256591
*/
Struts example
/*
This product includes software developed by
The Apache Software Foundation (http://www.apache.org/).
*/
Struts Framework
/*
Beginning JavaServer Pages
Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell
ISBN: 0-7645-7485-X
*/
Struts Framework: A Sample Struts Application
/*
# Title: Struts: The Complete Reference
# Author(s): James Holmes
# Publisher: McGraw-Hill/Osborne, 2004
# 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>
<font size="+1">ABC, Inc. Human Resources Portal</font><br>
<hr width="100%" noshade="true">
• Add an Employee<br>
• <html:link forward="search">Search for Employees</html:link><br>
</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>
<font size="+1">
ABC, Inc. Human Resources Portal - Employee Search
</font><br>
<hr width="100%" noshade="true">
<html:errors/>
<html:form action="/search">
<table>
<tr>
<td align="right"><bean:message key="label.search.name"/>:</td>
<td><html:text property="name"/></td>
</tr>
<tr>
<td></td>
<td>-- or --</td>
</tr>
<tr>
<td align="right"><bean:message key="label.search.ssNum"/>:</td>
<td><html:text property="ssNum"/> (xxx-xx-xxxx)</td>
</tr>
<tr>
<td></td>
<td><html:submit/></td>
</tr>
</table>
</html:form>
<logic:present name="searchForm" property="results">
<hr width="100%" size="1" noshade="true">
<bean:size id="size" name="searchForm" property="results"/>
<logic:equal name="size" value="0">
<center><font color="red"><b>No Employees Found</b></font></center>
</logic:equal>
<logic:greaterThan name="size" value="0">
<table border="1">
<tr>
<th>Name</th>
<th>Social Security Number</th>
</tr>
<logic:iterate id="result" name="searchForm" property="results">
<tr>
<td><bean:write name="result" property="name"/></td>
<td><bean:write name="result" property="ssNum"/></td>
</tr>
</logic:iterate>
</table>
</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;
}
}
Struts Framework: Declarative Exception Handling
/*
# Title: Struts: The Complete Reference
# Author(s): James Holmes
# Publisher: McGraw-Hill/Osborne, 2004
# ISBN: 0-07-223131-9
*/
Struts Framework: Tiles
/*
# Title: Struts: The Complete Reference
# Author(s): James Holmes
# Publisher: McGraw-Hill/Osborne, 2004
# ISBN: 0-07-223131-9
*/
Struts Framework Validator
/*
# Title: Struts: The Complete Reference
# Author(s): James Holmes
# Publisher: McGraw-Hill/Osborne, 2004
# ISBN: 0-07-223131-9
*/
Struts: Generate a response with XSL
/*
Struts Recipes
By George Franciscus and Danilo Gurovich
Publisher: Manning Publications Co.
ISBN 1932394249
*/
Struts: Internationalizing Struts Applications
/*
# Title: Struts: The Complete Reference
# Author(s): James Holmes
# Publisher: McGraw-Hill/Osborne, 2004
# ISBN: 0-07-223131-9
*/
Struts Recipes: Build Struts with Ant
/*
Struts Recipes
By George Franciscus and Danilo Gurovich
Publisher: Manning Publications Co.
ISBN 1932394249
*/
Testing Struts Applications
/*
# Title: Struts: The Complete Reference
# Author(s): James Holmes
# Publisher: McGraw-Hill/Osborne, 2004
# ISBN: 0-07-223131-9
*/
The Struts and Tags
/*
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>
<h1>Using the Struts Validator</h1>
<logic:messagesPresent>
<bean:message key="errors.header"/>
<ul>
<html:messages id="error" property="byte">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="short">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="integer">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="long">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="float">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="floatRange">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="double">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="date">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="creditCard">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="city">
<li><bean:write name="error"/></li>
</html:messages>
<html:messages id="error" property="zip">
<li><bean:write name="error"/></li>
</html:messages>
</ul>
<hr>
</logic:messagesPresent>
<html:form action="ch09_02">
<bean:message key="ch09_03.byte.text"/>
<html:text property="byte" size="15" maxlength="15"/>
<br>
<br>
<bean:message key="ch09_03.short.text"/>
<html:text property="short" size="15" maxlength="15"/>
<br>
<br>
<bean:message key="ch09_03.integer.text"/>
<html:text property="integer" size="15" maxlength="15"/>
<br>
<br>
<bean:message key="ch09_03.long.text"/>
<html:text property="long" size="15" maxlength="15"/>
<br>
<br>
<bean:message key="ch09_03.float.text"/>
<html:text property="float" size="15" maxlength="15"/>
<br>
<br>
<bean:message key="ch09_03.floatRange.text"/>
<html:text property="floatRange" size="15" maxlength="15"/>
<br>
<br>
<bean:message key="ch09_03.double.text"/>
<html:text property="double" size="15" maxlength="15"/>
<br>
<br>
<bean:message key="ch09_03.date.text"/>
<html:text property="date" size="15" maxlength="15"/>
<br>
<br>
<bean:message key="ch09_03.creditCard.text"/>
<html:text property="creditCard" size="16" maxlength="16"/>
<br>
<br>
<bean:message key="ch09_03.city.text"/>
<html:text property="city" size="16" maxlength="16"/>
<br>
<br>
<bean:message key="ch09_03.zip.text"/>
<html:text property="zip" size="5" maxlength="5"/>
<br>
<br>
<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>
<H1>Here"s Your Data...</H1>
<bean:message key="ch09_03.byte.text"/>:
<bean:write name="ch09_03" property="byte"/>
<BR>
<BR>
<bean:message key="ch09_03.short.text"/>:
<bean:write name="ch09_03" property="short"/>
<BR>
<BR>
<bean:message key="ch09_03.integer.text"/>:
<bean:write name="ch09_03" property="integer"/>
<BR>
<BR>
<bean:message key="ch09_03.long.text"/>:
<bean:write name="ch09_03" property="long"/>
<BR>
<BR>
<bean:message key="ch09_03.float.text"/>:
<bean:write name="ch09_03" property="float"/>
<BR>
<BR>
<bean:message key="ch09_03.floatRange.text"/>:
<bean:write name="ch09_03" property="floatRange"/>
<BR>
<BR>
<bean:message key="ch09_03.double.text"/>:
<bean:write name="ch09_03" property="double"/>
<BR>
<BR>
<bean:message key="ch09_03.date.text"/>:
<bean:write name="ch09_03" property="date"/>
<BR>
<BR>
<bean:message key="ch09_03.creditCard.text"/>:
<bean:write name="ch09_03" property="creditCard"/>
<BR>
<BR>
<bean:message key="ch09_03.city.text"/>:
<bean:write name="ch09_03" property="city"/>
<BR>
<BR>
<bean:message key="ch09_03.zip.text"/>:
<bean:write name="ch09_03" property="zip"/>
<BR>
</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;
}
}
The Struts Tags
/*
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>
<H1>Inserting Text With Custom Tags</H1>
<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>
<H1>Handling Custom Tag Attributes</H1>
<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>
<H1>Creating Iterating Tags</H1>
<%
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>
<H1>Creating Cooperating Tags</H1>
<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>
<H1>Custom Tags and Variables</H1>
<ch08:createToppings/>
<%
for(int loopIndex = 0; loopIndex < toppings.length; loopIndex++) {
out.println("Topping: " + toppings[loopIndex] + "<BR>");
}
%>
</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] + "<BR>");
} 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;
}
}
Using bean:resource to expose the struts.config.xml to your view
/*
Struts Recipes
By George Franciscus and Danilo Gurovich
Publisher: Manning Publications Co.
ISBN 1932394249
*/
Web Services and the Validator and Tile Packages
/*
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>
<h1>Using <logic> Tags</h1>
<html:form action="ch10_09.do">
<h2>Enter your data:</h2>
<html:text property="text"/>
<br>
<br>
<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;
}
}