I'm working on an application which update the values in a list of users stored in a mySql DB. The application starts with a users.jsp which lists the users in the DB. You then click the Update link next to one of the users in this list. This calls the DisplayUser action, which displays firstName and lastName using the emailAdddress of the selected user. This takes you to the user.jsp which gives you input boxes to modify the values for the selected user. SUBMIT calls the UpdateUser action. The UpdateUserServlet takes the user object using the session value and updates the DB. Up until the UpdateUserServlet I am clear on how to code this application. The only I'd like some help on is how to get the user object from the session attribute. I put my confusion in bold comments under the UpdateUservlet in the below code. Thanks in advance!
My code is:
users.jsp
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <%@ page import="org.apache.log4j.Logger" %> <% org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger("users_jsp.class"); %> <head> <title>DB Test appP</title> </head> <body> <h1>Users List</h1> <table cellpadding="5" border=1> <tr valign="bottom"> <th>First Name</th> <th>Last Name</th> <th>Email Address</th> </tr> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <c:forEach var="user" items="${users}"> <tr valign="top"> <td><p>${user.firstName} </td> <%LOGGER.info("JSP TEST"); %> <td><p>${user.lastName}</td> <td><p>${user.emailAddress}</td> <td><a href="displayUser?emailAddress=${user.emailAddress}">Update</a></td> <td><a href="deleteUser?emailAddress=${user.emailAddress}">Delete</a></td> </tr> </c:forEach> </table> </body> </html>
DisplayUserServlet.java
package user; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import business.User; import data.UserDB; import java.util.ArrayList; public class DisplayUserServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get params from request String emailAddress = request.getParameter("emailAddress"); User user = UserDB.selectUser(emailAddress); HttpSession session = request.getSession(); session.setAttribute("user", user); String url = "/user.jsp"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); } }
user.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Murach's Java Servlets and JSP</title> </head> <script language="JavaScript"> function validate(form) { if (form.firstName.value=="") { alert("Please fill in your first name"); form.firstName.focus(); } else if (form.lastName.value=="") { alert("Please fill in your last name"); form.lastName.focus(); } else { form.submit(); } } </script> <body> <h1>Update User</h1> <form action="updateUser" method="post"> <table cellspacing="5" border="0"> <tr> <td align="right">First name:</td> <td><input type="text" name="firstName" value="${user.firstName}"> </td> </tr> <tr> <td align="right">Last name:</td> <td><input type="text" name="lastName" value="${user.lastName}"> </td> </tr> <tr> <td align="right">Email address:</td> <td>${user.emailAddress}</td> </tr> <tr> <td></td> <td><input type="button" value="Submit" onClick="validate(this.form)"></td> </tr> </table> </form> </body> </html>
UpdateUservlet.java
package user; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import business.User; import data.UserDB; import org.apache.log4j.Logger; public class UpdateUserServlet extends HttpServlet { private static Logger logger = Logger.getLogger("ch14userAdmin"); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); String firstName = request.getParameter("firstName"); String lastName = request.getParameter("lastName"); logger.debug("Update get parameter " + request.getParameter(firstName)); logger.debug("Update get parameter " + request.getParameter(lastName)); [B] // TODO: add code that gets the User object from the session and updates the database // this sets a new user object but actually it should get the User object from the session[/B] User user = new User(); user.setFirstName(lastName); user.setLastName(lastName); logger.debug("Update set first Name " + (firstName)); UserDB.update(user); logger.debug("Update set last Name " + (lastName)); String url = "/displayUsers"; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); } }
UserDB.java (DAO class)
package data; import java.sql.*; import java.util.ArrayList; import org.apache.log4j.Logger; import user.LogInit; import business.User; public class UserDB { private static Logger logger = Logger.getLogger("ch14userAdmin"); public static int insert(User user) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "INSERT INTO User (FirstName, LastName, EmailAddress) " + "VALUES (?, ?, ?)"; try { ps = connection.prepareStatement(query); ps.setString(1, user.getFirstName()); ps.setString(2, user.getLastName()); ps.setString(3, user.getEmailAddress()); return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int update(User user) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "UPDATE User SET " + "FirstName = ?, " + "LastName = ? " + "WHERE EmailAddress = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, user.getFirstName()); ps.setString(2, user.getLastName()); ps.setString(3, user.getEmailAddress()); return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static int delete(User user) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; String query = "DELETE FROM User " + "WHERE EmailAddress = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, user.getEmailAddress()); return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); return 0; } finally { DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static boolean emailExists(String emailAddress) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String query = "SELECT EmailAddress FROM User " + "WHERE EmailAddress = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, emailAddress); rs = ps.executeQuery(); return rs.next(); } catch (SQLException e) { e.printStackTrace(); return false; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static User selectUser(String emailAddress) { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String query = "SELECT * FROM User " + "WHERE EmailAddress = ?"; try { ps = connection.prepareStatement(query); ps.setString(1, emailAddress); rs = ps.executeQuery(); User user = null; if (rs.next()) { user = new User(); user.setFirstName(rs.getString("FirstName")); user.setLastName(rs.getString("LastName")); user.setEmailAddress(rs.getString("EmailAddress")); } return user; } catch (SQLException e) { e.printStackTrace(); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } public static ArrayList<User> selectUsers() { ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String query = "SELECT * FROM User "; try { ps = connection.prepareStatement(query); rs = ps.executeQuery(); // User users = null; ArrayList<User> users = new ArrayList<User>(); // System.out.println("test"); while (rs.next()) { User user = new User(); user.setFirstName(rs.getString("FirstName")); user.setLastName(rs.getString("LastName")); user.setEmailAddress(rs.getString("EmailAddress")); logger.info("DAO query result: " + rs.getString("FirstName")); logger.info("DAO query result: " + rs.getString("LastName")); logger.info("DAO query result: " + rs.getString("EmailAddress")); users.add(user); logger.info("The arrray object added is: " + user); user.getFirstName(); logger.info("Get first name: " + user.getFirstName()); logger.info("DAO RETURNS: " + (users)); } return users; //logger.info("UserDB RETURNS: " + (users)); } // TODO: add code that returns an ArrayList of User objects // that corresponds with the rows in the User table catch (SQLException e) { logger.info("The Database problem is:" + e); e.printStackTrace(); return null; } finally { DBUtil.closeResultSet(rs); DBUtil.closePreparedStatement(ps); pool.freeConnection(connection); } } }