Parameters for HttpServletRequest

What we usually do in a servlet with the request object that we got in input, is getting from it the parameters the user sent us. We could have one or more parameters, and any parameter could contain a single value of an array of values.

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:
    <h1 align="center">Beer Selection Page</h1>
    <form method="POST" action="./">
        <p>Select beer characteristics ...</p>
        <select name="color">
            <option value="light">light</option>
            <option value="amber">amber</option>
            <option value="brown">brown</option>
            <option value="dark">dark</option>

        <select name="body">
            <option value="light">light</option>
            <option value="medium">medium</option>
            <option value="heavy">heavy</option>

        <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><input type="SUBMIT"></p>
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