Andrea Desole wrote:
It's not really clear to me how your code works. The biggest question
probably is related to how your search works, and the relationship with
these session attributes. What I would suggest is to take your code,
remove what you don't need (like all the sql queries), make it as simple
as possible, and post it here. If I understand correctly it should be
one or two jsps and one or two servlets. It's not unlikely that, while
you are doing that, you will find the cause of your problem.
Unfortunately isolating the code did not solve the problem for me.
So you need a table in the mysql database called t_Agent that has the
FirstName and LastName columns, varchar(32) will do for these. My current
table has 7 users all with the surname of Smith.
If you start with PEPagents.jsp and fill in a search string such as Smith in
the surname and press the search button you will get passed to the search
results form with correct list of users.
If you then go back in the browser and execute the search again you will end
up with a list that is twice the size of the original list and the entries
will be duplicated such that the original list has been appended with the
same list again. This happens repeatedly.
If you then close the browser and start all over again, the same thing will
happen in that the list will keep grwoing in size by appending the search
results to the end of the previous list.
If you open another browser and therefore a new session you end up with the
extended list in the new browser!
I do not know what is causing this or what to do to prevent this. The only
way to clear the list os to restart the Tomcat container.
The main servlet
================
package core;
// Import the standard java classes
import java.io.*;
import java.util.*;
// Import the servlet classes
import javax.servlet.*;
import javax.servlet.http.*;
// Import the java sql classes
import java.sql.*;
// Import the packages own classes
import core.beans.Pep;
public class PEPagentEditor extends HttpServlet
{
private Pep agentObject;
private String errorString;
private ArrayList agentArray = new ArrayList();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
errorString = "";
// Get the session object
HttpSession session = request.getSession();
Pep agentEditor = new Pep();
boolean searchingForUsers = (request.getParameter("buttonSearch") !=
null);
boolean creatingNewUsers = (request.getParameter("buttonNew") != null);
String userFirstName = request.getParameter("userFirstName");
if (userFirstName != null)
// Set the agent editor first name
{
agentEditor.setFirstName(userFirstName);
}
String userLastName = request.getParameter("userLastName");
if (userLastName != null)
// Set the agent editor last name
{
agentEditor.setLastName(userLastName);
}
searchForUser(agentEditor);
if (errorString.equals("") && (agentArray.size() != 0))
// No errors so display the users
{
session.setAttribute("agentArray", agentArray);
getServletConfig().getServletContext().getRequestDispatcher("/PEPsearchResults.jsp").forward(request,
response);
}
if (!errorString.equals(""))
// Guess a error occurred
{
// Add the error string
session.setAttribute("errorString", errorString);
// Remove the agent array so that we don't recursively fill it up.
session.removeAttribute("agentArray");
// Branch to the login page, because we have to go somewhere
getServletConfig().getServletContext().getRequestDispatcher("/PEPagents.jsp").forward(request,
response);
}
}
private void searchForUser(Pep agentEditor)
{
try
{
// Create the database url which is <driver type:database
type://hostname/database name>
String databaseUrl = "jdbc:mysql://localhost/TestDB";
// Load the database driver
Class.forName("com.mysql.jdbc.Driver");
// Create the datbase connection
Connection sqlConnection = DriverManager.getConnection(databaseUrl,
"user", "password");
// Create the sql statement
Statement sqlStatment = sqlConnection.createStatement ();
// Execute the query, storing the results in a result
String sqlQuery = "select LastName, FirstName from t_Agent where LastName
like '"
+
agentEditor.getLastName()
+
"%'";
ResultSet sqlResultSet = sqlStatment.executeQuery(sqlQuery);
int numberOfColumns = sqlResultSet.getMetaData().getColumnCount();
if (numberOfColumns != 2)
// There is an error here as we should only get 2 columns
{
errorString += "<p>Login was unsuccessful because a incorrect number of
columns received!";
}
else
{
while (sqlResultSet.next())
// handle all the rows returned
{
Pep agentFound = new Pep();
agentFound.setLastName(sqlResultSet.getString(1));
agentFound.setFirstName(sqlResultSet.getString(2));
agentArray.add(agentFound);
}
}
sqlResultSet.close();
sqlStatment.close();
sqlConnection.close();
}
catch(ClassNotFoundException exception)
{
errorString += "java class not found error: " + exception.getMessage();
}
catch(SQLException sqlException)
{
while (sqlException != null)
{
errorString += "<p>SQL Exception: " + sqlException.getMessage();
sqlException = sqlException.getNextException ();
}
}
}
}
the main jsp
============
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- Handle the session attributes -->
<%
String errorString = (String)session.getAttribute("errorString");
session.removeAttribute("agentArray");
%>
<HTML>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<FORM method=POST ACTION=/servlet/core.PEPagentEditor>
Surname:
<INPUT TYPE="TEXT" NAME="userLastName" VALUE="">
<P>
Christian:
<INPUT TYPE="TEXT" NAME="userFirstName" VALUE="">
<p>
<input type=SUBMIT name=buttonSearch value="SEARCH">
<p>
<input type=SUBMIT name=buttonNew value="NEW">
</FORM>
</CENTER>
<p> <% if (errorString != null){ %>
<p> <%= errorString %>
<p> <% } %>
<p><b><u>Session attributes</u></b>
<%
java.util.Enumeration attributeNames = session.getAttributeNames();
while (attributeNames.hasMoreElements())
{
String attributeName = (String)attributeNames.nextElement();
%>
<p> <%= attributeName %>
<%
}
%>
</BODY>
</HTML>
<!-- Clear up the session attributes -->
<%
session.removeAttribute("errorString");
// It is possible that this already exists if the user has pressed a back
key in the browser so we need to remove it
session.removeAttribute("agentArray");
%>
The search results jsp
======================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<jsp:useBean id="agentArray" scope="session" class="java.util.ArrayList"/>
<!-- Handle the session attributes -->
<%
String errorString = (String)session.getAttribute("errorString");
%>
<HTML>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<FORM method=POST ACTION="/servlet/core.PEPagentSelectedResult">
<SELECT name=agentSelected size=1>
<% for (int arrayElement = 0; arrayElement < agentArray.size();
arrayElement++) {%>
<% core.beans.Pep agentFound =
(core.beans.Pep)agentArray.get(arrayElement); %>
<OPTION value= <%= arrayElement %> > <%= agentFound.getLastName() %>
<%= agentFound.getFirstName() %>
<% } %>
</SELECT>
<P>
<INPUT TYPE="SUBMIT" VALUE="OPEN" NAME=openButton>
</FORM>
</CENTER>
<p> <% if (errorString != null){ %>
<p> <%= errorString %>
<p> <% } %>
<p><b><u>Session attributes</u></b>
<%
java.util.Enumeration attributeNames = session.getAttributeNames();
while (attributeNames.hasMoreElements())
{
String attributeName = (String)attributeNames.nextElement();
%>
<p> <%= attributeName %>
<%
}
%>
</BODY>
</HTML>
<!-- Clear up the session attributes -->
<%
session.removeAttribute("errorString");
%>
The bean
========
package core.beans;
public class Pep
{
private String lastName;
private String firstName;
public Pep()
{
setLastName("");
setFirstName("");
}
public Pep(
String lastName,
String firstName
)
{
setLastName(lastName);
setFirstName(firstName);
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return(lastName);
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return(firstName);
}
}