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

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>
- - - - - - --  - - - - - -- - - - -- - - -- 
- - - - - - - -- - - - -- - - --  -- - -- -- 
</select>

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.*"%>
<html>
<form name="form" method="post" >
<b>Select a country:</b>&nbsp;</td>
<select name="sel"><option value=""><---Select---></option>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
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();
while(results.next()){
String name = results.getString(2);
String id = results.getString(1);
%><option value="<%= name %>">
<% out.println(name); %>
</option>
<%} results.close(); psmnt.close(); %>
</select><br>
<input type="submit" value="Submit"/><br>

</form>
<%String option=request.getParameter("sel");
if(option==null){
}
else{
out.println("You have selected: <b>"+option+"</b>"+"<br>");
}
%>
</html>

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: