Skip to Main Content
Jakarta Struts Cookbook
book

Jakarta Struts Cookbook

by Bill Siggelkow
February 2005
Intermediate to advanced content levelIntermediate to advanced
528 pages
12h 53m
English
O'Reilly Media, Inc.
Content preview from Jakarta Struts Cookbook

5.3. Using a List-Backed Form Property

Problem

You want to create and use a form property backed by a java.util.List. You want to be able to access the entire list of data through one method as well as specific values in the list using indexed properties.

Solution

Create the form property as an indexed property, backed by a java.util.List, as shown in Example 5-4.

Example 5-4. List-backed form property

package com.oreilly.strutsckbk.ch05;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class ListForm extends ActionForm {
    
    private int size = 3;
    private List friends = new ArrayList(size);
    
    public List getFriends( ) { 
        return friends;
    }

    public String getFriend(int index) {
        return (String) friends.get(index);
    }

    public void setFriend(int index, String name) {
        friends.set(index, name);
    }
  
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        // prepopulate the list with empty strings
        friends = new ArrayList( );
        for (int i=0; i<size;i++) friends.add("");
    }
}

Example 5-5 (list_form_test.jsp) shows how the property values can be accessed on a JSP page. The form is created by accessing individual elements as indexed properties. The results are output by iterating over the list.

Example 5-5. Accessing list-backed form properties

<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming Jakarta Struts

Programming Jakarta Struts

Chuck Cavaness
Beginning Spring Framework 2

Beginning Spring Framework 2

Bruce Snyder, Sing Li, Anne Horton, Thomas Van de Velde, Naveen Balani, Christian Dupuis
Java Cookbook

Java Cookbook

Ian F. Darwin
Struts 2 in Action

Struts 2 in Action

J. Scott Stanlick, Chad Michael Davis, Donald J. Brown

Publisher Resources

ISBN: 059600771XSupplemental ContentErrata Page