Help with displaying results from a resultset
Hello,
I'm pretty new to Java and was wondering if there were any way to take my resultset and display it in the form of a table.
I've created a servlet and was able to put the results into a html table, however, I would like to now program an applet (that I would embed into an html page) that displays a table containing the results from a SQL query.
I am using Java SDK 1.4.2 and MySQL 5. I think my applet connects to the database fine, but I cant find any documentation about creating a table style interface with an applet.
Any help would be appreciated... thank you.
Vinh
[634 byte] By [
vinh] at [2007-11-11 8:04:31]

# 1 Re: Help with displaying results from a resultset
Why would you use an applet if you can use a JSP instead ?
You already have the servlet, so the JSP seems to be the next step.
Here's a piece of code out of one of my JSP's :
<DIV id=scroll1 style="BORDER:2px; OVERFLOW: auto; position: absolute; width: 700px; height: 250px; visibility: visible; left: 157px; top: 317px;">
<table width="600" border="0" align="center" id="lijst">
<%
for (Iterator i = filmLijst.iterator(); i.hasNext(); )
{
Film film = (Film) i.next();
%>
<tr>
<td width="80"><input name="detail" type="submit" id="detail" value="<%=film.getFilmnummer()%>"></td>
<td width="274"><%=film.getTitel()%> </td>
<td width="113"><%=film.getJaaruitgave()%></td>
<td width="115"><%=film.getGenre()%></td>
</tr>
<% } %>
</table>
</DIV>
If you want more information about how this works, let me know. I'll get more into detail of working with a JSP seems to you as a good idea
# 2 Re: Help with displaying results from a resultset
Well, the reason I would want to use an applet is that I'm not entirely thrilled with the look of my html table. Unless JSP will help produce a more attractive looking table?
I am interested in how your JSP code works, and if you could explain it I would appreciate it. Would I just be able to wrap my current servlet with the JSP code?
Thanks,
Vinh
vinh at 2007-11-11 22:37:38 >

# 3 Re: Help with displaying results from a resultset
Hi i m Rashmi will u pls tell me how to display records searched from access database into JTable can u pls send me some coding
Thanks
Rashmi Pant
# 4 Re: Help with displaying results from a resultset
Vinh,
I'll be most happy to explain to you how it works. This will take some replies as I want to post one story at a time and I don't want to type in a lot before I post this.
Let's begin with the MVC or Model View Controller design pattern.
- Model : these are the javabeans with their properties and methods (the getters, setters and constructors). The javabeans correspond to the concepts the users of your web application will use. For example, if your web application sells products, you will certainly have the following java beans : product, customer, order, invoice.
You could say that this is the heart of the business layer.
- View : these are the java server pages (JSP's). The JSP's only take care of the presentation of the data.
Therefor you can call this the presentation layer.
- Controller : this is the very heart of the application. Since a web application works with request - response, there must be a program able to catch every request and to formulate a response on it. This is the controller or servlet.
I've been comparing the MVC model to the 3 layers : so far, I've compared the model to the business layer and the view to the presentation layer. For the controller, there seems to be no corresponding layer.
And then there is a layer, which isn't mentioned in the 3 letters of the MVC.
But there is a corresponding object, namely the DAO or Data Access Object.
This kind of object connects to the database and makes javabeans out of the information obtained from
the database.
In conclusion : we have the following division of objects :
- model - business layer : javabeans
- view - presentation layer : JSP's
- controller - ? layer : servlets
- ? - data layer : DAO's
I shall soon return to you with examples from every kind of object.
To be continued ...
Gert
# 5 Re: Help with displaying results from a resultset
The model is composed of all the javabeans you need. This model corresponds to the business layer in the 3 layer-model.
Every Javabeans is composed of properties and methods. The methods can be divided into 3 different types :
- the constructor : used to create an object of this type of class
- the getter : used to show the value of a certain property
- the setter : used to note the value in a certain property.
The advantage of using getters and setters is that an object of the class is always responsible for its values. With the setter, the class can controll the values it is supposed to write down in its property. And in certain cases, the class
can refuse to write down an illegal value. The same goes for the getters : the class can decide to show the value in a certain format.
One of my javabeans is called film.java. Here's the code.
Some words are written in dutch; this helps me to know whether a
method is included in the java SDK or is one of my own.
package org.gertcuppens.cluif;
/* import java.util */
import java.util.Calendar;
import java.util.ArrayList;
/*import java .sql */
import java.sql.Blob;
import java.sql.Time;
import java.sql.ResultSet;
import java.sql.SQLException;
//import org.w3c.dom.Text;
/**
* @author GC1494
*
* Film verwijst naar een film uitgebracht in de cinema of op TV.
*/
public class Film {
private int filmnummer;
private String titel;
private short jaaruitgave;
private String genre;
private Calendar duurtijd;
private String taal;
private Blob poster;
private String korteInhoud;
private String inhoud;
private ArrayList filmPloeg;
private ArrayList rollenLijst;
public Film ()
{
this.setFilmnummer(0);
this.setTitel("");
this.setGenre("");
}
public Film (ResultSet _rs, String soort)
throws SQLException
{
if (soort.equals("lijst"))
{
this.setFilmnummer(_rs.getInt("filmnummer"));
this.setTitel(_rs.getString("titel"));
this.setJaaruitgave(_rs.getShort("jaarUitgave"));
this.setGenre(_rs.getString("genre"));
} /* soort == lijst */
else {
this.setFilmnummer(_rs.getInt("filmnummer"));
this.setTitel(_rs.getString("titel"));
this.setJaaruitgave(_rs.getShort("jaarUitgave"));
this.setGenre(_rs.getString("genre"));
this.setKorteInhoud(_rs.getString("korteInhoud"));
this.setInhoud(_rs.getString("inhoud"));
this.setDuurtijd(_rs.getTime("duurtijd"));
}
}
public String getFilmnummer() {
Integer filmnummerInt = new Integer(this.filmnummer);
String filmnummerStr = filmnummerInt.toString();
StringBuffer filmnummerBuffer = new StringBuffer();
switch (filmnummerStr.length())
{
case 1 : filmnummerBuffer.append("000");
filmnummerBuffer.append(filmnummerStr);
break;
case 2 : filmnummerBuffer.append("00");
filmnummerBuffer.append(filmnummerStr);
break;
case 3 : filmnummerBuffer.append("0");
filmnummerBuffer.append(filmnummerStr);
break;
default : filmnummerBuffer.append(filmnummerStr);
break;
} /* switch */
return filmnummerBuffer.toString();
}
/**
*
* @uml.property name="titel"
*/
public String getTitel() {
return titel;
}
/**
*
* @uml.property name="jaaruitgave"
*/
public String getJaaruitgave() {
if (this.jaaruitgave == 0)
{
return ("onbekend");
}
else
{
return (String.valueOf(this.jaaruitgave));
}
}
/**
*
* @uml.property name="genre"
*/
public String getGenre() {
if (genre == null)
{
return("onbekend");
}
else
return genre;
}
/**
*
* @uml.property name="duurtijd"
*/
public String getDuurtijd() {
int uur;
int minuten;
String uurStr, minutenStr, deel1;
if (duurtijd != null)
{
uur = duurtijd.get(10); // 10 == HOUR
minuten = duurtijd.get(12); // 12 == MINUTE
uurStr = String.valueOf(uur);
minutenStr = String.valueOf(minuten);
deel1 = uurStr.concat(":");
System.out.println("uur is" + uurStr);
System.out.println("minuten is " + minutenStr);
return (deel1.concat(minutenStr));
}
else
return "00:00" ;
}
/**
*
* @uml.property name="taal"
*/
public String getTaal() {
return taal;
}
/**
*
* @uml.property name="poster"
*/
public Blob getPoster() {
return poster;
}
public String getKorteInhoud() {
if (this.korteInhoud != null)
return korteInhoud;
else
return "";
}
/**
*
* @uml.property name="Inhoud"
*/
public String getInhoud() {
if (this.inhoud != null)
return inhoud;
else
return "";
}
public ArrayList getFilmPloeg ()
{
return this.filmPloeg;
}
public ArrayList getRollenLijst ()
{
return this.rollenLijst;
}
/**
*
* @uml.property name="filmnummer"
*/
public void setFilmnummer(int _filmnummer) {
this.filmnummer = _filmnummer;
}
/**
*
* @uml.property name="titel"
*/
public void setTitel(String _titel) {
this.titel = _titel;
}
/**
*
* @uml.property name="jaaruitgave"
*/
public void setJaaruitgave(short _jaaruitgave) {
this.jaaruitgave = _jaaruitgave;
}
/**
*
* @uml.property name="genre"
*/
public void setGenre(String _genre) {
this.genre = _genre;
}
/**
*
* @uml.property name="duurtijd"
*/
public void setDuurtijd(Time _duurtijd) {
Calendar duurtijdCal = Calendar.getInstance();
if (_duurtijd != null)
duurtijdCal.setTimeInMillis(_duurtijd.getTime());
this.duurtijd = duurtijdCal;
// gevonden op java.sun.com
// Time t = rs.getTime("time");
// Calendar cal = Calendar.getInstance();
// cal.setTimeInMillis(t.getTime());
}
/**
*
* @uml.property name="taal"
*/
public void setTaal(String _taal) {
this.taal = _taal;
}
/**
*
* @uml.property name="poster"
*/
public void setPoster(Blob _poster) {
this.poster = _poster;
}
public void setKorteInhoud(String _korteInhoud) {
this.korteInhoud = _korteInhoud;
}
/**
*
* @uml.property name="korteInhoud"
*/
public void setInhoud(String _inhoud) {
this.inhoud = _inhoud;
}
public void setFilmPloeg (ArrayList _filmPloeg)
{
this.filmPloeg = _filmPloeg;
}
public void setRollenLijst (ArrayList _rollenLijst)
{
this.rollenLijst = _rollenLijst;
}
}
# 6 Re: Help with displaying results from a resultset
With the Javabeans, you've built the model. But to make the javabeans, you need to have a DAO or Data Access Object. A DAO is nothing but a java class who knows how to connect to a database and execute SQL-instructions.
First of all, here's a little trick. You need to create an abstract class GeneralDao which describes how to connect to the database. Every DAO you need will inherit from this GeneralDao. That way, if you change your database or the database driver, there's just one place where you need to write down this change, and that's the GeneralDao.
Compare this effort with the effort you need to change the database or driver if you connect to the database inside each JSP. For a small web application, it's OK. But for a big one, you would need much more time compared to the use of the GeneralDao.
Gert
Below you will find the code. And don't mention the code mentioning gcoLogger.
This is merely for writing down a log with Log4J. You won't need this to make the web app work.
package org.gertcuppens.cluifDao;
//import java.util.*;
import java.util.ResourceBundle;
import java.sql.*;
/* import org.apache.log4j */
import org.apache.log4j.Logger;
/* import org.gertcuppens.algemeen */
import org.gertcuppens.algemeen.Melding;
public abstract class GeneralDao {
protected Connection getDatabaseConnection()
throws Melding
{
Connection dbconn = null;
ResourceBundle resBundle;
Logger gcoLogger = Logger.getLogger("gco.log");
System.out.println("GeneralDao - start connectie databank " );
gcoLogger.debug("GeneralDao - start connectie databank " );
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
resBundle = ResourceBundle.getBundle("gcoConfig");
gcoLogger.debug("ophalen resourceBundle (gcoConfig) " );
String dbConnectie = resBundle.getString("databaseconnection");
gcoLogger.debug("lezen databaseconnection in resourceBundle " );
//dbconn = DriverManager.getConnection("jdbc:mysql://localhost/gco");
dbconn = DriverManager.getConnection(dbConnectie,"username", "password");
gcoLogger.debug("maken connectie databank " );
} catch (InstantiationException exc)
{
System.out.println("GeneralDao - Fout bij getConnection - instantiation " );
gcoLogger.fatal("GeneralDao - Fout bij getConnection - instantiation " );
// exc.printStackTrace();
Melding melding = new Melding(1,"instantiring is niet gelukt bij getConnection()");
throw melding ;
}
catch (ClassNotFoundException exc)
{
System.out.println("GeneralDao - Fout bij getConnection - class not found " );
gcoLogger.fatal("GeneralDao - Fout bij getConnection - class not found " );
Melding melding = new Melding(2,"class is niet gevonden bij getConnection()");
throw melding;
}
catch (IllegalAccessException exc)
{
System.out.println("GeneralDao - Fout bij getConnection - illegal acces " );
gcoLogger.fatal("GeneralDao - Fout bij getConnection - illegal acces " );
Melding melding = new Melding(3,"toegang is niet toegelaten bij getConnection()");
throw melding;
}
catch (SQLException exc)
{
System.out.println("GeneralDao - Fout bij getConnection - SQLException " );
gcoLogger.fatal("GeneralDao - Fout bij getConnection - SQLExeption " );
Melding melding = new Melding(exc);
throw melding;
}
return dbconn;
}
} /* public abstract class GeneralDao */
# 7 Re: Help with displaying results from a resultset
Now that you have the abstract class GeneralDao, you can write any DAO you need.
Each DAO will need to inherit from the GeneralDao like this :
public class FilmDao extends GeneralDao {
Below, you will find the code of my FilmDao class
Whenever you see the class Melding in the code, this class is used for catching exceptions.
Melding is dutch for message, but I've got the habit of giving my classes dutch names.
That way, I know right away whether I've written the class or whether it's a class from Java or another provider.
package org.gertcuppens.cluifDao;
/*import java.sql */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Blob;
import java.util.ArrayList;
// import java.util.Collection;
/* import org.apache.log4j */
import org.apache.log4j.Logger;
/* import org.gertcuppens.* */
import org.gertcuppens.cluif.Film;
import org.gertcuppens.cluif.FilmMedewerker;
import org.gertcuppens.algemeen.Melding;
/**
* @author GC1494
*
* De GeneralDao definieert nmaal de getConnection() methode om connectie met de databank te leggen.
* Alle DAO's erven van deze GeneralDao.
*/
public class FilmDao extends GeneralDao {
public ArrayList zoekFilmOpLetter(String _letter)
throws Melding
{
ArrayList filmLijst = new ArrayList();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
StringBuffer zoekString = new StringBuffer();
zoekString.append("select * from film ");
zoekString.append("where titel like '" + _letter + "%'");
System.out.println("zoekstring heeft de waarde " + zoekString);
con = getDatabaseConnection();
ps = con.prepareStatement(zoekString.toString());
rs = ps.executeQuery();
if (rs == null)
{
ps.close();
con.close();
System.out.println("geen film gevonden");
}
else
{
while (rs.next() )
{
Film film = new Film (rs, "lijst");
System.out.println("gevonden film is " + film.getTitel());
filmLijst.add(film);
} /* while rs.next() */
rs.close();
ps.close();
con.close();
} /* else : rs != null */
} catch (SQLException sqlEx)
{
Melding melding = new Melding(sqlEx);
throw melding;
}
catch (Melding melding)
{
throw melding;
}
return filmLijst;
}
public ArrayList zoekFilmOpSelectie(boolean[] _selectie, String _titel, String _jaar, String _genre, String _naam)
throws Melding
{
Logger gcoLogger = Logger.getLogger("gco.log");
ArrayList filmLijst = new ArrayList();
/* lokaal heb ik MySQL versie 4.1 die subqueries aankan
* op de server zit ik met versie 4.0 die nog geen subqueries aankan
* Dus moet ik een aantal SQL-statements herschrijven
*/
try {
Connection con = this.getDatabaseConnection();
StringBuffer zoekString = new StringBuffer();
if (_selectie[3] == false)
{
zoekString.append("select * from film where ");
} /* geen selectie op medewerker */
else {
zoekString.append("select * from film, filmrol, persoon "); zoekString.append(" where film.filmnummer = filmrol.filmnummer and ");
zoekString.append(" filmrol.persoonsnummer = persoon.persoonsnummer and ");
} /* wel selectie op medewerker */
if (_selectie[0] == true && _titel != null)
{
zoekString.append(" titel like '%" + _titel + "%'");
if (_selectie[1] == true || _selectie[2] == true
|| _selectie[3] == true)
{
zoekString.append(" and ");
}
} /* selectie op titel */
if (_selectie[1] == true && _jaar != null)
{
System.out.println("FilmDAO - zoeken op jaar" + _jaar);
zoekString.append(" jaarUitgave = " + _jaar + " ");
if (_selectie[2] == true || _selectie[3] == true)
{
zoekString.append(" and ");
}
} /* selectie op jaar */
if (_selectie[2] == true && _genre != null)
{
System.out.println("FilmDAO - zoeken op genre");
zoekString.append(" genre = '" + _genre + "' ");
if ( _selectie[3] == true)
{
zoekString.append(" and ");
}
} /* selectie op genre */
if (_selectie[3] == true && _naam != null)
{
System.out.println("FilmDAO - zoeken op naam");
zoekString.append(" (naam like '%" + _naam + "%' or ");
zoekString.append(" voornaam like '%" + _naam + "%' ) ");
} /* selectie op naam */
System.out.println("zoekstring is " + zoekString );
gcoLogger.debug("zoekstring is " + zoekString );
PreparedStatement ps = con.prepareStatement(zoekString.toString());
ResultSet rs = ps.executeQuery();
if (rs == null)
{
ps.close();
con.close();
} /* rs == null */
else {
while (rs.next())
{
Film film = new Film(rs, "lijst");
filmLijst.add(film);
} /* while rs.next() */
rs.close();
ps.close();
con.close();
} /* rs != null */
} catch (SQLException SQLEx)
{
Melding melding = new Melding(SQLEx);
throw melding;
} /* catch */
catch (Melding melding)
{
throw melding;
}
return filmLijst;
}
public Film zoekFilmOpNummer(String _nummer)
throws Melding
{
System.out.println(" FilmDao : zoeken van filmnummer " + _nummer);
Integer nummerInteger = new Integer(_nummer);
int nummer = nummerInteger.intValue();
StringBuffer zoekFilmString = new StringBuffer();
StringBuffer zoekPosterString = new StringBuffer();
StringBuffer zoekNulPosterString = new StringBuffer();
Film film ;
Connection con = null;
PreparedStatement ps = null;
ResultSet rsFilm = null;
ResultSet rsPoster = null;
/* syntax van de Left Join :
* select * from film left join filmposter on film.filmnummer = filmposter.filmnummer
*/
/* tweede poging van syntax :
* select * from film left join filmposter
* on film.filmnummer = filmposter.filmnummer
* where film.filmnummer = 5
* order by filmposter.volgnummer
*/
//zoekString.append("select * from film left join filmposter");
//zoekString.append(" on film.filmnummer = filmposter.filmnummer");
// zoekString.append(" and filmposter.volgnummer = 1 ");
// zoekString.append(" where film.filmnummer = ?");
zoekFilmString.append("select * from film");
zoekFilmString.append(" where filmnummer = ?");
zoekPosterString.append("select * from filmposter");
zoekPosterString.append(" where filmnummer = ?");
zoekNulPosterString.append("select * from filmposter");
zoekNulPosterString.append(" where filmnummer = 0");
try {
/* zoek filmdetail op basis van nummer */
con = getDatabaseConnection();
ps = con.prepareStatement(zoekFilmString.toString());
ps.setInt(1, nummer);
rsFilm = ps.executeQuery();
if (rsFilm.next())
{
film = new Film(rsFilm, "detail");
/* zoek filmposter */
ps = con.prepareStatement(zoekPosterString.toString());
ps.setInt(1, nummer);
rsPoster = ps.executeQuery();
if (rsPoster.next())
{
Blob poster = rsPoster.getBlob("poster");
film.setPoster(poster);
} /* if rs.next() == filmposter gevonden */
else {
ps = con.prepareStatement(zoekNulPosterString.toString());
rsPoster = ps.executeQuery();
if (rsPoster.next())
{
Blob poster = rsPoster.getBlob("poster");
film.setPoster(poster);
} /* zoek de NUL-poster */
} /* geen filmposter gevonden : zoek die
* van filmposter met nummer 0 */
/* zoek de technische fiche van de film */
film.setFilmPloeg(zoekMedewerkers(film, 1));
film.setRollenLijst(zoekMedewerkers(film, 2));
} /* if rs.next() == film gevonden */
else film = new Film();
} catch (SQLException sqlEx )
{
Melding melding = new Melding(sqlEx);
throw melding;
}
catch (Melding melding)
{
throw melding;
}
return film;
} /* zoekFilmOpNummer () */
private ArrayList zoekMedewerkers (Film _film, int _aard)
throws Melding, SQLException
{
Integer nummerInteger = new Integer(_film.getFilmnummer());
int nummer = nummerInteger.intValue();
Connection con = null;
PreparedStatement ps = null;
StringBuffer zoekString;
ResultSet rsMedewerker = null;
ArrayList mwLijst = new ArrayList();
try {
con = getDatabaseConnection();
zoekString = new StringBuffer();
zoekString.append("select * from filmrol, persoon ");
zoekString.append("where filmrol.persoonsnummer = persoon.persoonsnummer ");
if (_aard == 1)
{
zoekString.append("and filmrol.filmrol <> 'acteur' ");
}
else {
zoekString.append("and filmrol.filmrol = 'acteur' ");
} /* _aard != 1) */
zoekString.append("and filmnummer = ?");
ps = con.prepareStatement(zoekString.toString());
ps.setInt(1, nummer);
rsMedewerker = ps.executeQuery();
while (rsMedewerker.next())
{
FilmMedewerker filmMedewerker = new FilmMedewerker(rsMedewerker);
System.out.println("nieuwe medewerker " + filmMedewerker.getNaam());
mwLijst.add(filmMedewerker);
} /* while rsMedewerker */
if (_aard == 1)
{
}
else {
}
} catch (Melding melding)
{
throw melding;
}
catch (SQLException sqlEx)
{
Melding melding = new Melding(sqlEx);
throw melding;
}
finally {
if (rsMedewerker != null) rsMedewerker.close();
if (ps != null) ps.close();
if (con != null) con.close();
}
return mwLijst;
} /* zoekMedewerkersVanFilm() */
}
# 8 Re: Help with displaying results from a resultset
With the view, we've arrived in the presentation layer of the application.
And this is the collection of JSP's you've written.
All a JSP has to do is taking the information out of the javabean and displaying it.
I show you as an example the JSP which displays a list of movies.
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Expires", "0");
response.setHeader("Pragma", "No-cache");
response.addHeader("Cache-control", "no-store"); // tell proxy not to cache
response.addHeader("Cache-control", "max-age=0"); // stale right away
%>
<%@ page import = "java.util.Iterator" %>
<%@ page import = "org.gertcuppens.cluif.Film" %>
<jsp:useBean id="filmLijst" class="java.util.ArrayList" scope="session"/>
<jsp:useBean id="melding" class="org.gertcuppens.algemeen.Melding" scope="request"/>
<jsp:useBean id="servletPath" class="java.lang.String" scope="request"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>CLUIF - CLUb op het Internet voor Filmfanaten</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="cluif.css" rel="stylesheet" type="text/css">
</head>
<body>
<table width="700" border="0" align="center" id="hoofding">
<tr>
<td width="91"><img src="images/movieCamera.jpg" width="85" height="90"></td>
<td width="599"><p align="center" class="Hoofdtitel">CLUIF</p>
<p align="center">Club op het internet voor filmliefhebbers </p></td>
</tr>
</table>
<table width="700" height="50" border="0" align="center" id="hoofding2">
<tr>
<td background="images/filmrol6.gif"> </td>
</tr>
</table>
<p align="center">geselecteerde letter </p>
<form action="/gco/cluif" method="post" name="filmLijstForm" id="filmLijstForm">
<table width="700" border="0" align="center" id="hoofdmenu">
<tr>
<td width="100"><input name="alfabet" type="submit" class="menuknop" id="alfabet" value="alfabet"></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<table width="700" border="0" align="center" id="submenu">
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td>
<% if (melding != null)
{ if (melding.getCategorie() == 4)
{ %>
<%=melding.getSQLMelding()%>
<% }
else { %>
<%=melding.getBoodschap()%>
<% } %>
<%} /* melding != null */ %>
</td>
</tr>
</table>
<table width="700" border="0" align="center">
<tr>
<th width="80">kies</th>
<th width="369">titel</th>
<th width="111">uitgave</th>
<th width="108">genre</th>
<th width="11"> </th>
<th width="15"> </th>
<th width="20"> </th>
</tr>
</table>
<DIV id=scroll1 style="BORDER:2px; OVERFLOW: auto; position: absolute; width: 700px; height: 250px; visibility: visible; left: 157px; top: 317px;">
<table width="600" border="0" align="center" id="lijst">
<%
for (Iterator i = filmLijst.iterator(); i.hasNext(); )
{
Film film = (Film) i.next();
%>
<tr>
<td width="80"><input name="detail" type="submit" id="detail" value="<%=film.getFilmnummer()%>"></td>
<td width="274"><%=film.getTitel()%> </td>
<td width="113"><%=film.getJaaruitgave()%></td>
<td width="115"><%=film.getGenre()%></td>
</tr>
<% } %>
</table>
</DIV>
<p>
<Input type="hidden" name="viewNaam" value="/cluifFilmLijst.jsp">
</p>
</FORM>
</body>
</html>
# 9 Re: Help with displaying results from a resultset
So now, we have the model or javabeans, the DAO who create the javabeans, the view or JSP's who display the
information inside the javabeans.
But which class takes control of the whole of the application ? That's the controller, and in a java web application we write the controller as a servlet. For a small web app, one single servlet should do.
With a servlet, you have 2 possibilities to call them : with a GET or a POST.
The difference between the 2 of them is simple : with GET, you always show the variables in the URL.
You've certainly seen URLS containg a question mark like this one :
http://www.amazon.com/exec/obidos/tg/detail/-/0596007736/qid=1114176032/sr=1-1/ref=sr_1_1/103-0402606-0055040?v=glance&s=books
The problem with this kind or URL's is that the user can change the value of the parameter and thus he might see a page which he isn't allowed to see.
Therefor, always write the following code in your servlet :
public void doGet (HttpServletRequest _request, HttpServletResponse _response)
throws ServletException, IOException
{
doPost (_request, _response);
} /* doGet() */
So, with this code, you are always referring to the POST method, no matter what.
A POST method takes care of the parameters without showing the parameters
# 10 Re: Help with displaying results from a resultset
At the beginning of my servlet I've defined the different JSP's I know :
public class CluifController extends HttpServlet
{
protected final String ALFABET_PAGINA = "/cluifAlfabet.jsp";
protected final String LETTERLIJST_PAGINA = "/cluifFilmLijst.jsp";
protected final String FILMINHOUD_PAGINA = "/cluifFilmInhoud.jsp";
protected final String FILMROLLEN_PAGINA = "/cluifFilmRollen.jsp";
protected final String SELECTIE_PAGINA = "/cluifSelecties.jsp";
In the doPost, I check to see if I've got a viewname.
If I don't, then this means my web app has just been started and still needs to show its first JSP :
public void doPost (HttpServletRequest _request, HttpServletResponse _response)
throws ServletException, IOException
{
String requestedPage;
/* Haal de naam van de view op. Indien de gebruiker cluif opstart
* is er nog geen viewnaam.
*/
String viewNaam = _request.getParameter("viewNaam");
String radioLetter = _request.getParameter("radioLetter");
_____________ :
if there is no viewNaam, then show the first JSP
if (viewNaam == null)
{
/* viewNaam == null dus CLUIF is pas opgestart */
/* creer een sessie - via de boolean true geef je aan
* dat er een sessie gecreerd moet worden als er
* nog geen bestaat */
HttpSession session = _request.getSession(true);
System.out.println("geen view : alfabet gevraagd");
requestedPage = ALFABET_PAGINA;
}_______________ :
if there is a viewName, check out which one to know which JSP has been
shown and where the user is in the web app
else { /* viewnaam != null dus er is een viewnaam gekend */
HttpSession session = _request.getSession(false);
if (session == null) requestedPage = ALFABET_PAGINA;
if (viewNaam.equals(ALFABET_PAGINA))
{ /* Gebruiker komt van cluifAlfabet.jsp */
System.out.println("van alfabet naar Letter");
requestedPage = behandelAlfabet (_request);
}
else if (viewNaam.equals(LETTERLIJST_PAGINA))
{ /* Gebruiker komt van cluifLetterLijst.jsp */
System.out.println("van Letter naar Detail");
requestedPage = behandelLetterLijst (_request);
}
# 11 Re: Help with displaying results from a resultset
The viewName to which I referred in my previous email, is merely a hidden variable inside the <FORM> tag of the JSP.
<Input type="hidden" name="viewNaam" value="/cluifAlfabet.jsp">
</form>
Whenever the user clicks on the submit button, each part of the FORM is put inside the request and given to the servlet. Therefor, the hidden field inside the <FORM> tag can be read by the servlet.
The next question is : now that we know who controls the web app (== the servlet), who starts the servlet ? That's Tomcat. And how does he do that ?
Well, If I type in http://localhost:8080 , I call Tomcat and he shows me the index page of Tomcat. If I want him to start my web app, I type in http://localhost:8080/gco/cluif.
With /gco I refer to the folder C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\gco
Inside this folder , you have the web.xml inside the WEB-INF folder.
So, by typing http://localhost:8080/gco I ask Tomcat to look for the file WEB-INF\web.xml and read it
By adding cluif ( http://localhost:8080/gco/cluif) , I ask Tomcat to start the servlet which corresponds to the word cluif.
And with the following web.xml, Tomcat knows that by "cluif" I ask him to start the servlet called cluifcontroller.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>CLUIF</display-name>
<description>CLUb op het Internet voor Filmfanaten</description>
<servlet>
<servlet-name>LoggerServlet</servlet-name>
<servlet-class>org.gertcuppens.controller.LoggerServlet</servlet-class>
<init-param>
<param-name>properties</param-name>
<param-value>WEB-INF\classes\log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>org.gertcuppens.controller.CluifController</servlet-name>
<servlet-class>org.gertcuppens.controller.CluifController</servlet-class>
</servlet>
<servlet>
<servlet-name>org.gertcuppens.controller.ImageServlet</servlet-name>
<servlet-class>org.gertcuppens.controller.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>org.gertcuppens.controller.CluifController</servlet-name>
<url-pattern>/cluif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>org.gertcuppens.controller.ImageServlet</servlet-name>
<url-pattern>/cluifimg</url-pattern>
</servlet-mapping>
</web-app>
# 12 Re: Help with displaying results from a resultset
Let's imagine the following scenario : the servlet has started the web app and has shown a page in which the user can select with a radio button a letter. Then he/she pushes on the button "submit". This way, the servlet receives another requests and looks for the view that was shown. The servlet figures out this was the alphabetPage :
else { /* viewnaam != null dus er is een viewnaam gekend */
HttpSession session = _request.getSession(false);
if (session == null) requestedPage = ALFABET_PAGINA;
if (viewNaam.equals(ALFABET_PAGINA))
{ /* Gebruiker komt van cluifAlfabet.jsp */
requestedPage = behandelAlfabet (_request);
}
So, now we go to the private method behandelAlfabet; this method will look up some things and tell the servlet which page has to be shown next.
# 13 Re: Help with displaying results from a resultset
What happens in this private method ?
We take a look at what information the request contains, so we know what the user wants.
We look at the value of the radiobutton.
private String behandelAlfabet (HttpServletRequest _request)
{
Logger gcoLogger = Logger.getLogger("gco.log");
String radioLetter = _request.getParameter("radioLetter");
System.out.println("gcoController -- radioLetter is " + radioLetter);
gcoLogger.debug("gcoController -- radioLetter is " + radioLetter);
Then, we must know which button was pushed : was it the button "selecteren" (select) or zoeken (search) ?
If the user pushed the select button, the page he wants to see was
the selectionPage :
if (_request.getParameter("selecteren") != null)
{
System.out.println("button is selecteren");
gcoLogger.debug("button is selecteren");
return SELECTIE_PAGINA;
}
If it was the button zoeken or search, we must look for all the movies
beginning with the selected letter contained in the radiobutton.
And for this we need the FilmDao class.
else if (_request.getParameter("zoeken") != null)
{
System.out.println("button is zoeken");
gcoLogger.debug("button is zoeken");
HttpSession sessie = _request.getSession(true);
// if (sessie == null) sessie = _request.getSession(true);
FilmDao filmDao = new FilmDao();
ArrayList filmLijst = new ArrayList();
We give the radioLetter to the filmDao so it know which films
it has to look for
try {
filmLijst = filmDao.zoekFilmOpLetter(radioLetter);
Melding melding = new Melding("selectie op films beginnend met " + radioLetter);
_request.setAttribute("melding",melding);
} catch (Melding melding)
{
// Melding melding = new Melding(exc);
//HttpSession sessie = _request.getSession(false);
/* plaats de melding in request; als je melding
* in sessie plaatst, blijft de foutmelding terugkomen
* ook al is ze niet meer van toepassing
*/
_request.setAttribute("melding", melding);
System.out.println("gcoController -- melding klaargezet in behandelLetter() ");
System.out.println("melding boodschap is " + melding.getBoodschap());
System.out.println("melding SQL is" + melding.getSQLMelding());
}
sessie.setAttribute("filmLijst", filmLijst);
return FILMLIJST_PAGINA;
} /* selecteren geklikt */
This search will have given us the arrayList filmLijst as result.
We put this resultset in the request so the JSP can get it there
when it has to display the values of this arraylist on screen.
Always be prepared for the unexpected : if neither of the buttons
select or search has been pressed on, just go back to the alphabetPage.
else
{
System.out.println("behandelalfabet : onvoorzien geval");
gcoLogger.debug("behandelalfabet : onvoorzien geval ");
return ALFABET_PAGINA;
}
} /* behandelAlfabet () */
In short : you must always use the request to get your information from to know what to do. And put the found information in the request so that other objects may use this information to work on.
