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:

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:


<%! String[] movies; %>

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

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