JSP and HTML
Hello,
I want to know that how can i fill the list box or combo box on HTML using JSP.
For example, I have a list of models of cars. When the HTML page gets loaded i want the user to see these cars.
What should i use List box or combo box?
In either case how can i fill the data to be derived from database, when form loads?
PLEASE HELP ME.
# 1
Hi there,
First you can write a back-end code to retrieve data from the database.
Learn to write SQL queries from an SQL tutorial: http://www.w3schools.com/sql/default.asp
Go through the JDBC tutorial on how to retrieve data from the database using SQL - it has sample code and examples:
http://java.sun.com/docs/books/tutorial/jdbc/
Then learn the basics of JavaBeans , call the JDBC code to retrieve the data from the database.
Then using jsp:useBean and other bean related tags interact with the JavaBean from your JSP.
# 2
Ok. Thanks for that information.But can you tell me whether it is possible to fill data in combo box using JSP?
# 3
Yes it is possible to fill an HTML combo box with JSP.In fact one can fill any type of HTML control, not just combo box with JSPs.
# 4
I am able to retrieve data from database using bean. I can call that bean in jsp
But i don't know how to display data in HTML form using that JSP
Can you show me some sample code example where we can fill data in HTML form using JSP?
I will be very thankful to you if you show me how do i fill a combo box.
Thanks.
# 5
[nobr]Hi, sorry for replying so late, I was innundated with work today. I don't know if you already figured out a solution.
I will show 2 methods of creating combo box in HTML along with JSP using JavaBeans, you can further improve the code as you like.
First method use JSP scriptlets, JSP expressions etc and is the *old* way of writing JSPs - if possible you should avoid writing scriptlets and move to JSTL (which is very easy to learn).
Second method uses JSTL.
Both these methods use 3 JavaBean classes.
So I'll create the 3 classes first:
Customer JavaBean , represents 1 record of Customer data
from the database
package test30;
import java.io.Serializable;
public class Customer implements Serializable {
String firstName;
double totalPrice;
public Customer() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
}
CustomerList - also a JavaBean allows you to
get or set a List of Customers. If you want
you can call the code that gets the list of customers from the
database in the get method of this JavaBean, but read and
try out the complete solution first before making any changes.
--
package test30;
import java.util.List;
import java.io.Serializable;
public class CustomerList implements Serializable {
List<Customer> customers;
public CustomerList() {
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
}
CreateCustomers creates some dummy Customers and
populates them into a List. You can avoid this bean if you
make use of the above bean instead to get customer list
(But wait, till you see the JSP code)
--
package test30;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
public class CreateCustomers implements Serializable {
CustomerList customerList;
public CreateCustomers() {
}
/* Assuming that getCustomerList , gets the list of Customers from the Database */
public CustomerList getCustomerList() {
Customer customer = new Customer();
customer.setFirstName("Jack");
customer.setTotalPrice(98);
List<Customer> customers = new ArrayList<Customer>();
customers.add(customer);
customer = new Customer();
customer.setFirstName("Jill");
customer.setTotalPrice(694);
customers.add(customer);
customer = new Customer();
customer.setFirstName("Michael");
customer.setTotalPrice(32);
customers.add(customer);
for(int i=0; i<20; i++){
customer = new Customer();
customer.setFirstName("Customer #" +i);
customer.setTotalPrice(i*i);
customers.add(customer);
}
this.customerList = new CustomerList();
customerList.setCustomers(customers);
return customerList;
}
public void setCustomerList(CustomerList customerList) {
this.customerList = customerList;
}
}
Method 1 - Using scriptlets, expressions inside JSP
Say index.jsp
<%@ page import="java.util.List" %>
<%@ page import="test30.Customer" %>
<%@ page import="test30.CreateCustomers" %>
<%@ page import="test30.CustomerList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head><title>Combo Box Example using JSP Scriptlets and Expressions</title></head>
<body>
<%
CreateCustomers createCustomers = new CreateCustomers();
CustomerList customerList = createCustomers.getCustomerList();
List<Customer> customers = customerList.getCustomers();
%>
Combo Box Example using JSP Scriptlets and Expressions
<br/><br/>
<%-- HTML Combo Box --%>
<select name="customerFirstName" multiple="multiple">
<%
String customerFirstName;
for (int i = 0; i < customers.size(); i++) {
customerFirstName = customers.get(i).getFirstName();
%>
<option value="<%=customerFirstName%>"><%=customerFirstName%></option>
<%
}//for (int i = 0; i < customers.size(); i++)
%>
</select>
</body>
</html>
Method 2 is definitely the right way to write JSPs in the recent years.
However it uses JSTL 1.1 , so you must properly install JSTL 1.1 and configure it .
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head><title>Combo Box Example using JSTL 1.1</title></head>
<body>
<jsp:useBean id="createCustomers" class="test30.CreateCustomers"/>
Combo Box Example using JSTL 1.1
<br/><br/>
<div>
<%-- HTML Combo Box --%>
<select name="customerFirstName" multiple="multiple" size="15" style="width:300px;background-color:green;color:white;">
<c:forEach var="customer" items="${createCustomers.customerList.customers}">
<option value="${customer.firstName}">${customer.firstName}</option>
</c:forEach>
</select>
</div>
</body>
</html>
In the above code the createCustomers JavaBean can be removed, if you want to directly use customerList bean to first get the list of customers directly from the database.[/nobr]
# 6
Hello,
Thats really nice. I have long working hours so i am able to work on this issue when i go home. Yesterday i found some unknown problem with the deploy tool.
This was surely not in my thoughts. I need to study this and try this.
Thanks once again, i will try this today and let you know the updates.
# 7
Hello,I have gone through your code many times. Now i am confused, in which bean we should use database connection string and get connected to database.Please tell.
# 8
You should read and follow what the code is doing, then you will be able to decide for yourself where to write the code that gets data from the database.
Also run the code and see how the application looks. You should be able to research on Google and find out what things you need to configure your environment and then run this application.
Here's a hint:
One place where you could write it would be here:
Customer customer = new Customer();
customer.setFirstName("Jack");
customer.setTotalPrice(98);
List<Customer> customers = new ArrayList<Customer>();
customers.add(customer);
customer = new Customer();
customer.setFirstName("Jill");
customer.setTotalPrice(694);
customers.add(customer);
customer = new Customer();
customer.setFirstName("Michael");
customer.setTotalPrice(32);
customers.add(customer);
for(int i=0; i<20; i++){
customer = new Customer();
customer.setFirstName("Customer #" +i);
customer.setTotalPrice(i*i);
customers.add(customer);
}
# 9
Thanks for this help.I really liked the way you are giving me help.I am working on it. Let you know if have some problem.
# 10
The best way to learn Java or any other programming language (after learning the basics with a book or online tutorial) is to test the code out and see what output it gives and then try to understand why it is giving a certain output.
Also use your favorite search engine - e.g Google, Yahoo etc, first if you get stuck with a particular concept - search on it and see what it means. If it is not clear then that's the right time to post a question to the forum (with relevant information in your question).
So you could run the above program as-is first and see if you are getting the output. Provided that your development environment is configured correctly everything should run fine.
After you get the program working and understand what it's doing it becomes clear on how to change it to do what you want it to do - that is adding the database code etc.
Message was edited by:
appy77
# 11
I am using j2sd1.4.2_06So when i am compiling your bean code i am getting error on line List<Customer> customers;I suppose its generic method used in 1.5Can you tell me what can i do instead of above line.Eagerly waiting for your reply.
# 12
Hi there,
Generics are supported in I think JDK 1.5 and later, so you will need J2SE5 or higher.
The term generics is associated with a variable and not with a function.
If you don't want to use Generics, you can still make the code work by
omitting this part <Customer> after List.
If you omit the <Customer> part after List, the list will hold Objects of type Customers , but when you do customers.get(i); you will have to cast it back to Customer object as in (Customer) customers.get(i);
# 13
Hello,Still I am unable to complie the CustomerList class.I am using j2sdk1.4I tried to follow your suggestions but still I can't complie.
# 14
In the above code if you notice carefully, Generics is being used in more than one files and in multiple places in the same file.
You need to make the change everywhere, not just in one place.
I found the following lines of code - accorss different files in the above code that use Generics - I think I've found all of them, but it doesn't hurt to check if I've left any out.
List<Customer> customers;
public List<Customer> getCustomers()
public void setCustomers(List<Customer> customers)
List<Customer> customers = new ArrayList<Customer>();
customers.add(customer);
List<Customer> customers = customerList.getCustomers();
So change the above lines of code accorss all files that contain them, to something like the following
List customers;
public List getCustomers()
public void setCustomers(List customers)
List customers = new ArrayList();
customers.add(customer);
List customers = customerList.getCustomers();
After you make the above code changes, every where the List or ArrayList item is referenced , it needs to be explicitly cast to the Customer object (since Generics is no longer being used).
So for example
Customer aCustomer = (Customer) customers.get(i);
If you are still getting compilation errors, carefully take a look at the error and see if it is mentioning a particular file, and then examine that file and see if something needs to be fixed/ changed.
If you're still stuck after trying the above then post all of your code accross different files, similar to they way I've posted. Also post relevant information about the stack trace/ error message you're getting.
Message was edited by:
appy77
# 15
package test30;
import java.util.List;
import java.io.Serializable;
public class CustomerList implements Serializable {
Customer customers;
List customers;
public CustomerList() {
}
public List customers getCustomers() {
return customers;
}
public void setCustomers(List customers) {
this.customers = customers;
}
}
There is something wrong i am doing in this code. Please tell me what is wrong?
# 16
Why have you declared the variable named "customers" twice?
Customer customers;
List customers;
In a Java class there cannot be more than one variable with the same name.
Another point, you don't need to declare Customer customers; at all, because that variable is not being used in the class at all.
So change the above code to the following:
package test30;
import java.util.List;
import java.io.Serializable;
public class CustomerList implements Serializable {
List customers;
public CustomerList() {
}
public List customers getCustomers() {
return customers;
}
public void setCustomers(List customers) {
this.customers = customers;
}
}
# 17
<html>
<body>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="java.io.*"%>
<% String s1=request.getParameter("uemail");
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://192.136.21.222/Bidding","mysql","xxxxxx");
PreparedStatement ps=con.prepareStatement("select * from User where user_email=? ; ");
ps.setString(1,s1);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
//out.println("<td>");
out.println("hello");
//out.println("<br><br>");
//out.println("<center><h2>These are the Details</h2></center>");
//out.println("<br><br>");
//out.println("<html><body><center>");
//out.println("<table border='25' cellpadding='12'>");
out.println("<tr><th>Name</th><td>"+rs.getString(1)+"</td></tr><tr><th>User Email</th><td>"+rs.getString(2)+"</td></tr><tr><th>Password</th><td>"+rs.getString(3)+"FFDGDG"+rs.getString(4));
out.println("</center></body></html>");
return;
}//if
}//try
catch(Exception e){out.println(e);}
finally{try{con.close();}catch(Exception e){}}%>
</body>
</html>
Blank page is displayed , instead of details
junita at 2007-7-21 17:16:15 >

# 18
<body>
<%try
{
//your database connection and query execution , executeQuery();
}
catch(SQLException s)
{
out.println("Exception : "+s);
}
%>
<select name="Select_inv_org">
<%
rs.first();
while(rs.next())
{
String invOrg=rs.getString("ticker"); //ticker is my column name
%>
<option values=<%=rs.getString("ticker")%>> <%=rs.getString("ticker") %>
<%
}
%>
</select>
# 19
Yes, I have noticed that Generics are used in more than one file.
First of all sorry. I was very sick and was unable to seat in front of comupter. Still don't have enough energy to seat but i want this problem to be solved. I will be working on this today and let you know the update.
Thanks.
# 20
Hello Yogesh_jadhav,If I am not wrong, JSP is to handle the presentation logic and not making connections to the database (business logic). The code you have listed is not wrong but according to me making database connections in JSP is not correct way of presentation.
# 21
Hello Yogesh_jadhav,If I am not wrong, JSP is to handle the presentation logic and not making connections to the database (business logic). The code you have listed is not wrong but according to me making database connections in JSP is not correct way of presentation.
# 22
But Where Do I Need To Typecast to CUSTOMERS When I am using the JSTL Code in my JSP given below :
Becuase when i run the JSP without Typecasting, the COMBO Box gives the following output :
${customer.firstName}
${customer.firstName}
${customer.firstName}
${customer.firstName}
${customer.firstName}
.........upto
15 TIMES
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head><title>Combo Box Example using JSTL 1.1</title></head>
<body>
<jsp:useBean id="createCustomers" class="test30.CreateCustomers"/>
Combo Box Example using JSTL 1.1
<div>
<%-- HTML Combo Box --%>
<select name="customerFirstName" multiple="multiple" size="15" style="width:300px;background-color:green;color:white;">
<c:forEach var="customer" items="${createCustomers.customerList.customers}">
<option value="${customer.firstName}">${customer.firstName}</option>
</c:forEach>
</select>
</div>
</body>
</html>
# 23
Hi there,
Have you configured JSTL 1.1 correctly?
How have you defined the web-app tag in web.xml ? It should be that of Servlet 2.4 version.
What web container version (e.g Tomcat) ?
What version of Servlet API does the web container support? It should be 2.4 , for JSTL 1.1.
First try printing a simple JSTL variable as follows:
<c:set var="someVariable" value="xyz"/>
${someVariable}
In the above sample do you see ${someVariable} or do you see xyz?
If you see ${someVariable} then JSTL EL is not evaluating and it needs to be configured correctly.
# 24
Yes You are correct, I dont see XYZ in my output.
All i get in my display is : ${someVariable}
Could you please suggest me some steps for configuring JSTL
I am deploying the application using JDeveloper 10.1.2.2 on Oracle Application Server 10g (Release 2)
Awaiting Ur Reply ?
# 25
Check if Oracle Application Server 10g (Release 2) , is built to Servlet 2.4 and JSP 2.0 specifications.
If it is not then you may need to upgrade to the version that supports Servlet 2.4 and JSP 2.0
For example, if you look at Tomcat servers chart:
http://tomcat.apache.org/whichversion.html , Tomcat 5.5.x supports Servlet 2.4 and JSP 2.0
--
Next check if your project's web.xml conforms to Servlet 2.4 spec:
It should be like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
</web-app>
Make sure your taglibs are using the correct URIs , whereever you use them in your JSP files:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
etc