Friday 19 December 2008

Hints for a complete STRUTS Application (2)

Hints for a STRUTS Application
Source code is available from arsaral(at)yahoo.com

2nd Hint: A very simple Struts Iterator Tag example

This program uses the navigation trick of the 1st HINT to prepare the simple list that will be iterated to be printed on the screen.

Index.jsp
<HTML>

<BODY>
<logic:forward name="setList"></logic:forward>
</BODY>
</HTML>

Struts-config.xml
<global-forwards>
<forward name="setList" path="/setList.do" />
</global-forwards>

<action-mappings>
<action name="setList" path="/setList" type="com.actions.SetListAction">
<forward name="success" path="/iterateList.jsp"></forward>
</action>
</action-mappings>

As seen, first you will run index.jsp than index.jsp will run setList.do and that will run SetListAction.java.

package com.actions;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public final class SetListAction extends Action {

// The constructor method for this class
public SetListAction() {
}

// This sets the list as a session bean
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {

HttpSession session = request.getSession();

java.util.ArrayList list = new java.util.ArrayList();
list.add("item 1");
list.add("item 2");
list.add("item 3");

session.setAttribute("baseList",list);

ActionForward forward = mapping.findForward("success");
return forward;
}
}
As seen above, SetListAction.java prepares a list named baseList and then forwards the action with “success” to struts-config.xml. struts-config.xml than runs iterateList.jsp which is given below.

iterateList.jsp
<html:html>
<header>
<title>Iterator</title>
<html:base/>
</header>
<body>
<logic:present name="baseList">
<logic:iterate id="iteratorItem" name="baseList">
Item Val: <bean:write name="iteratorItem" /><br />
</logic:iterate>
</logic:present>
<html:submit value="Continue"/>
</body>
</html:html>

iterateList.jsp very simply writes the items of the list to the screen.