You can pass the ArrayList of objects (each object represents a record from the database) to the JSP , through a JavaBean.
Make use of jsp:useBean , to access the JavaBean inside the JSP
Then use JSTL 1.1 (you must install and configure JSTL 1.1 on a Serlvet 2.4 container like Tomcat 5.5 etc)
inside your JSP use <c:forEach tag to iterate over the list of items stored in the ArrayList, and then access each object's property.>
[nobr]Assuming that you have JSTL 1.1 installed and configured on a web server that supports Servlet 2.4 ( e.g Tomcat 5.5) and web.xml , you should be able to run the following code on your system to see how it works.
This is how it should be in the JSP:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title></title></head>
<body>
The Servlet UrlDispatcher forwarded control to this JSP page: /p/test45/index.jsp
<br/><br/>
<jsp:useBean id="dataRecords" class="java.util.ArrayList" scope="request"/>
<c:forEach var="currentRecord" items="${dataRecords}">
Age is : ${currentRecord.age} <br/>
First Name is : ${currentRecord.firstName} <br/>
<hr/>
</c:forEach>
</body>
</html>
I'll explain at a high level how it works
1) First you'll invoke your Servlet - I've named it UrlDispatcher - this Servlet is declared in web.xml (deployment descriptor) as:
<servlet>
<servlet-name>UrlDispatcher</servlet-name>
<servlet-class>test45.servlet.UrlDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UrlDispatcher</servlet-name>
<url-pattern>/UrlDispatcher</url-pattern>
</servlet-mapping>
2) Based on that URL Mapping in web.xml you'll be calling your servlet with this URL
http://localhost:8080/UrlDispatcher
Once the servlet is called , via the above URL the following doPost method executes
package test45.servlet;
import test45.dao.SomeDataAccessObject;
import test45.javabeans.DataRecord;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import java.util.ArrayList;
import java.io.IOException;
/**
This Servlet gets the ArrayList of Objects , which is obtained from the database
and then stores the ArrayList inside HTTP Request, and then forwards the HTTP Request
to a JSP page. The JSP page then accesses the ArrayList from the HTTP Request object.
Note that this servlet is to be declared in web.xml , and a URL mapping should be assigned to it.
*/
public class UrlDispatcher extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
doGet(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//Get the ArrayList of Objects from the database
SomeDataAccessObject someDataAccessObject = new SomeDataAccessObject();
ArrayList<DataRecord> dataRecords = someDataAccessObject.getDataRecords();
//Store the ArrayList of objects into HTTP Request
request.setAttribute("dataRecords",dataRecords);
//Forward the Http Request to a JSP page.
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/p/test45/index.jsp");
requestDispatcher.forward(request,response);
}
}
3) Inside the doPost we call a Data Access Object, which performs a connection to the database and gets all the records and stores them in the ArrayList - I assume that you already know how to get records from the database - otherwise please refer to the JDBC tutorial.
package test45.dao;
import test45.javabeans.DataRecord;
import java.util.ArrayList;
/**
* This is a Java class that queries the Database with a given SELECT query
* using JDBC, and then iterates over the ResultSet and stores each record from the
* database into the ArrayList.
*/
public class SomeDataAccessObject {
public ArrayList<DataRecord> getDataRecords() {
ArrayList<DataRecord> dataRecords = new ArrayList<DataRecord>();
DataRecord dataRecord;
//while(rs.next()){
// Get the values from the result set and store them in the arraylist here.
dataRecord = new DataRecord();
dataRecord.setAge(53);
dataRecord.setFirstName("Harry");
dataRecords.add(dataRecord);
dataRecord = new DataRecord();
dataRecord.setAge(43);
dataRecord.setFirstName("Jenny");
dataRecords.add(dataRecord);
//}
return dataRecords;
}
}
4) Each data record is stored in an instance of this JavaBean, by storing it in a JavaBean ( a JavaBean follows a certain notation - refer to JavaBeans tutorial for details)
package test45.javabeans;
import java.io.Serializable;
/**
* This is a JavaBean representing one record of data.
* Store instances of this JavaBean in an ArrayList.
*/
public class DataRecord implements Serializable {
private int age;
private String firstName;
public DataRecord() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
5) When the UrlDispatcher servlet is called it, reads the ArrayList of objects from the database and stores it in the HTTP Request and forwards the control to the JSP page which then uses a JavaBean to read the ArrayList from the request and then iterates over the ArrayList using JSTL c:forEach
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title></title></head>
<body>
The Servlet UrlDispatcher forwarded control to this JSP page: /p/test45/index.jsp
<br/><br/>
<jsp:useBean id="dataRecords" class="java.util.ArrayList" scope="request"/>
<c:forEach var="currentRecord" items="${dataRecords}">
Age is : ${currentRecord.age} <br/>
First Name is : ${currentRecord.firstName} <br/>
<hr/>
</c:forEach>
</body>
</html>
References:
1) JSP useBean , getProperty and setProperty
http://java.sun.com/products/jsp/syntax/2.0/syntaxref20.html
2) JavaBeans tutorial
http://java.sun.com/docs/books/tutorial/javabeans/
3) JSTL 1.1 API
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html
Message was edited by:
appy77[/nobr]
hi... my code is as follows
i have a jsp page as follows that requests information from a database
<body>
<form method="get" action="http://localhost/servlet/JobServlet">
View Job Details:
Enter job number <input name="jobno" type="text" id="jobno" />
<input name="view" type="submit" id="view" value="View Details" />
</form> </body>
my interface:
import java.rmi.*;
public interface JobInt extends Remote {
public String getDetails(int jobno) throws RemoteException; }
the server:
import java.rmi.*;
public class JobServer {
public static void main(String[] args) {
try {
JobImpl j = new JobImpl();
Naming.rebind("//"+"localhost"+"/JobImpl",j); System.out.println("Registered"); }
catch (Exception e) {
System.out.println("Exception occured in JobServer ... " +e); } } }
implementation:
import java.rmi.*;
import java.rmi.server.*;
import java.sql.*;
public class JobImpl extends UnicastRemoteObject implements JobInt {
Connection con; Statement st; ResultSet rs;
String url = "jdbc:mysql://localhost:3306/db?user=root;password=admin";
public JobImpl() throws RemoteException {
super();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, "", "");
st = con.createStatement(); }
catch (Exception e) {
System.out.println("problem while establishing connection"+e); } }
public String getDetails(int jobno) throws RemoteException {
try {
rs = st.executeQuery("Select * from job where jobno="+jobno);
rs.next();
return(rs.getString(2)); }
catch (Exception e) {
e.printStackTrace(); }
return null; } }
from the jsp page, when the jobno is entered all the details about the job should be displayed on the servlet
the servlet:
import java.rmi.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class JobServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();
res.setContentType("text/plain");
try {
int jobno = Integer.parseInt(req.getParameter("jobno"));
JobInt j = (JobInt)Naming.lookup("//"+"localhost"+"/JobInt");
System.out.println("Job Details: "+j.getDetails(jobno)); }
catch (Exception e1) {
System.out.println(""+e1); } } }
hmm... do i have to do all this just to display the forward the information to a JSP page?
at first look, seems quite complex!
i tried the code you sent and while compiling the servlet UrlDispatcher i get the error "package dao does not exist"
i installed jakarta -taglibs-standard-1.1.2 and copied the jstl.jar and standard.jar files in WEB-INF\lib folder
my servlet is in WEB-INF\classes
can you help plz?
You are getting the "package ....... does not exist" because you didn't create a package for it.
A package is a folder / directory. so simply create a folder called dao under the folder called test45, or whatever you are calling it and then make sure you place the Java file(s) that has package test45.dao under that folder.
This is the package I used in the above code test45.dao
Message was edited by:
appy77
i did everything following your example...
my folder test45 is in ROOT... i copied the class files for DataRecord, SomeDataAccessObject and UrlDispatcher to ROOT/WEB-INF/classes... am i doing it rite?
when i call the servlet through http://localhost/UrlDispatcher it gives me the following error:
The requested resource (Servlet UrlDispatcher is not available) is not available.
i am using a preconfigured version of tomcat...
plz help
Is there a web.xml under WEB-INF of your project?
Did you define the servlet and servlet mappings in web.xml?
If you configure everything correctly for this project, it should work fine.
Instead of manually placing the class files in classes folder , use Ant build scripts - but do that for later because it does take some time to learn Ant.
Even in your classes folder the package/ folder hierarchy should be correctly defined as it is mentioned in the Java files.
ROOT/test45 contains index.jsp and UrlDispatcher
ROOT/test45/javabeans contains DataRecord
ROOT/test45/dao contains SomeDataAccessObject
i compiled everything in their respective folders and just copied the class files to ROOT/WEB-INF/classes
i modified ROOT/WEB-INF/web.xml to include the servlet-mapping for UrlDispatcher
any idea whats wrong?