We have already seen that we can use an HTML select - option to set a single parameter in a form. We are now extending the beer selector form to generate two singled value parameter, and an array of values:
<body> <h1 align="center">Beer Selection Page</h1> <form method="POST" action="./SelectBeer.do"> <p>Select beer characteristics ...</p> <p>Color: <select name="color"> <option value="light">light</option> <option value="amber">amber</option> <option value="brown">brown</option> <option value="dark">dark</option> </select></p> <p>Body: <select name="body"> <option value="light">light</option> <option value="medium">medium</option> <option value="heavy">heavy</option> </select></p> <p>Can Sizes:<br /> <input type="checkbox" name="sizes" value="33cc">33 cc<br /> <input type="checkbox" name="sizes" value="50cc">50 cc<br /> <input type="checkbox" name="sizes" value="66cc">66 cc<br /> </p> <p><input type="SUBMIT"></p> </form> </body>Besides the color parameter, having one value among the available options, we now have a body parameter (light, medium, or heavy value). More interesting is the sizes parameter.
The idea is that in the sizes parameter we want have an array of values. In this case we want give the user a way to specify the format of the beer he is interested in. He could select no checkbox, one, two, or all of them.
To implement this requirement we add three checkbox input control, all of them with the same name, sizes, meaning that the value, when the chechbox is selected, is added to the same parameter, that contains an array of values, and not a single one.
Getting the body parameter in the servlet is no news, while to get the sizes parameter, an array of Strings, we should use a different methods on the HttpServletRequest:
String body = request.getParameter("body"); String[] sizes = request.getParameterValues("sizes");Pay attention to the fact that sizes could be null, if no checkbox is checked, so you have to test it before using it.
I originally wrote this post while I was reading the fourth chapter of Head First Servlet and JSP, a fun ad interesting book on Java EE.
No comments:
Post a Comment