FAQ


Advertisement



How to retrieve values from HTML form input elements in JSP?

In theory, GET is for getting data from the server and POST is for sending data there. However, GET appends the form data (called a query string) to an URL, in the form of key/value pairs from the HTML form, for example, name=John. In the query string, key/value pairs are separated by & characters, spaces are converted to + characters, and special characters are converted to their hexadecimal equivalents. Because the query string is in the URL, the page can be bookmarked or sent as email with its query string. The query string is usually limited to a relatively small number of characters.

The POST method, however, passes data of unlimited length as an HTTP request body to the server. The user working in the client Web browser cannot see the data that is being sent, so POST requests are ideal for sending confidential data (such as a credit card number) or large amounts of data to the server.

The request is a pre-defined variable and available to all JSP pages. The request is a type of HttpServletRequest object. The data the user enters on the HTML form is stored in this request object. To retrieve any value from an HTML form input element on a JSP page, you need to use the request object's getParameter(String s) method. The String argument of the method getParameter(String s) is the elements name whose value you want to retrieve. The JSP pre-defined request variable is used to obtain information from the request as sent by the browser. The parameters, include from URL quert string and posted form data, are stored by the servlet container as a set of name-value pairs.

The result of getParameter(String s) method will differ according to what type of element you are querying. For instance a checkbox element might return "on" if it has been selected, or it might return null if it hasn't been selected. Where a text element will return the text/value that was part of the element at the time the form was submitted. A radio button will return the value of the selected radio button in the button group. If you try and query an element that never existed in the form, the request.getParameter(String s) will return null.

Example HTML Form:

<form name="myForm" action="/result.jsp" method="post" >
<input type="checkbox" name="inputCheckbox" >
<input type="radio" name="inputRadio" value="0" >
<input type="radio" name="inputRadio" value="1" >
<input type="text" name="inputText" >
<input type="submit" >
</form>

Example JSP page (This will only display the values recieved from the submitted form):

    <%= request.getParameter("inputCheckbox") %>
<%= request.getParameter("inputRadio") %>
<%= request.getParameter("inputText") %>


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |