How do I pass values from a list box (with multiple selects) to a Java Bean?

Govind Seshadri

Consider the following HTML, which basically allows the user to select multiple values by means of a checkbox:


<html>
<body>
What's your favorite movie?

<form method=post action=Movies.jsp> <input type=checkbox name=faveMovies value="2001: A Space Odyssey"> 2001: A Space Odyssey
<input type=checkbox name=faveMovies value="The Waterboy"> The Waterboy
<input type=checkbox name=faveMovies value="The Tin Drum"> The Tin Drum
<input type=checkbox name=faveMovies value="Being John Malkovich"> Being John Malkovich
<input type=submit> </form> </body> </html>

To handle HTML elements like checkboxes and lists which can be used to select multiple values, you need to use a bean with indexed properties (arrays). The following bean can be used to store the data selected from the above check box, since it contains an indexed property movies:


package foo;
public class MovieBean {
    private String[] movies;
    public MovieBean() {
     String movies[] = new String[0];
    }
    public String[] getMovies() {
       return movies;
    }
    public void setMovies(String[] m) {
     this.movies = m;
    }   
}

Although a good design pattern would be to have the names of the bean properties match those of the HTML input form elements, it need not always be the case, as indicated within this example. The JSP code to process the posted form data is as follows:


<html> 
<body>

<%! String[] movies; %>

<jsp:useBean id="movieBean" class="foo.MovieBean">
  <jsp:setProperty name="movieBean"
    property="movies" 
    param="faveMovies" />
</jsp:useBean>

<%   movies = movieBean.getMovies();
   if (movies != null) {
      out.println("You selected: <br>");
      out.println("<ul>");
      for (int i = 0; i < movies.length; i++) {
        out.println ("<li>"+movies[i]+"</li>");
      }
      out.println("</ul>");
    } else 
      out.println ("Don't you watch any movies?!");
%>

</body>
</html>

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact