Jsp Option Value

In this section, we are going to create a select box by retrieving the value from the database in jsp.

Jsp Option Value


In this section, we are going to create a select box by retrieving the value from the database in jsp. For further processing, first of all you need to create a table in the database. 

We create a table 'countries' that has the specified fieldnames and datatypes respectively.





Create Table 'countries':

CREATE TABLE countries 
(countries_id varchar(10) NOT NULL,
  countries_name varchar(100) default   NULL);

Then we have used the html tag <select>. Its syntax is:

<select name="">
<option value="">--select--</option>
<option value="">--select--</option>
- - - - - - --  - - - - - -- - - - -- - - -- 
- - - - - - - -- - - - -- - - --  -- - -- -- 

Do the database connectivity and use the query "select * from countries" in order to retrieve the values from the table 'countries'. Then we have create a variable 'name' of string type and using the ResultSet method getString(2), all the values are retrieved from the database and stored into this variable. Then put this variable inside the <option> tag like: <option value="<%= name %>">

Here is the code of optionValue.jsp:

<%@page import="java.sql.*"%>
<form name="form" method="post" >
<b>Select a country:</b>&nbsp;</td>
<select name="sel"><option value=""><---Select---></option>
String connectionURL = "jdbc:mysql://localhost:3306/test";
Connection connection= DriverManager.getConnection(connectionURL, "root", "root");
PreparedStatement psmnt = connection.prepareStatement("select * from countries ");
ResultSet results = psmnt.executeQuery();
String name = results.getString(2);
String id = results.getString(1);
%><option value="<%= name %>">
<% out.println(name); %>
<%} results.close(); psmnt.close(); %>
<input type="submit" value="Submit"/><br>

<%String option=request.getParameter("sel");
out.println("You have selected: <b>"+option+"</b>"+"<br>");

Output will be displayed as:

On clicking the dropdown button, it will show you a list of countries:

After selecting the country, click the button, a message is displayed:

Download Source Code:

Share on Google+Share on Google+

Jsp Option Value

Posted on: February 3, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Jsp Option Value   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Srinu B
June 4, 2012
Ignoring words after space in the option value.

When we try to read the values that are shown in the drop down list, it's omitting the words which are after space. If you have a solution please post here. Thanks in advance.