Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: How to retrieve an object from a session attribute

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    19
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default How to retrieve an object from a session attribute

    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);
     
     
            }
     
        }
    }
    Last edited by jps; September 3rd, 2013 at 06:53 AM. Reason: code tags


  2. #2
    Junior Member
    Join Date
    Aug 2013
    Posts
    19
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: How to retrieve an object from a session attribute

    Once again I'm solving this myself and I'll post the fix:

    In the UpdateUserServlet the creation of a new user object (User user = new User()) should be replaced with a user object that calls the user session from the prior servlet (DisplayUserSelrvlet). In this case the User object becomes:

    User user = session.getAttribute("user);
     
     String firstName = request.getParameter("firstName");
           String lastName = request.getParameter("lastName");
     
     
            logger.debug("Update get parameter " + session.getAttribute("user"));
            // logger.debug("Update get parameter " + request.getParameter(lastName));
     
     
            user.setFirstName(firstName);
            user.setLastName(lastName);
     
     
            UserDB.update(user);

  3. The Following User Says Thank You to jaltaie For This Useful Post:

    jps (September 2nd, 2013)

  4. #3
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 262 Times in 231 Posts

    Default Re: How to retrieve an object from a session attribute

    Quote Originally Posted by jaltaie View Post
    Once again I'm solving this myself and I'll post the fix:
    Keep up the good work, and thanks for posting the solution for future readers

  5. #4
    Junior Member
    Join Date
    Aug 2013
    Posts
    19
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: How to retrieve an object from a session attribute

    Thanks, but can you please tell me if I'm posting in the right forum since I don't seem to be getting responses to my posts. For example, I now have another question concerning writing DELETE pages in the same type of MVC app. Is the JSP section the right place to post? Should I be asking my questions on the theory part or should I make my question more related to the coding / practical part in order to actually get a response? Many thanks, J

  6. #5
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 262 Times in 231 Posts

    Default Re: How to retrieve an object from a session attribute

    I think the reason you get no reply is the extensive amount of code posted.
    Personally, I feel I can reply to 3 or 4 other posts by the time I digest the code posted here. I did start to read it, searching for the section you marked in bold...
    Bold does not work within code tags, I suggest using the code=java tag to get highlighting instead of the code tag, and use regular comments in the code to draw attention

  7. #6
    Junior Member
    Join Date
    Aug 2013
    Posts
    19
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: How to retrieve an object from a session attribute

    Noted. Thanks so much for the response. Does bold work in the code=java tag?

  8. #7
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 262 Times in 231 Posts

    Default Re: How to retrieve an object from a session attribute

    Quote Originally Posted by jaltaie View Post
    Does bold work in the code=java tag?
    No, but with code=java tag the syntax is colored, so comments stand out as they would in an IDE
    ....see your code above

  9. #8
    Junior Member
    Join Date
    Aug 2013
    Posts
    19
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: How to retrieve an object from a session attribute

    Great. I tried this in a similar post which I posted today. Cut down on the code content too. Please let me know if this is more consistent with your site rules (would also be great to get a response to the problem):

    Using session atttributes and DAO class to delete mySql user records

    Thanks a lot

Similar Threads

  1. Replies: 149
    Last Post: February 19th, 2013, 09:04 PM
  2. Replies: 1
    Last Post: February 14th, 2013, 06:30 PM
  3. Saving session info in a context object
    By bhask1 in forum Web Frameworks
    Replies: 0
    Last Post: September 19th, 2011, 02:14 PM
  4. not able to get the context attribute set in ServletContextListener
    By jkoder70014 in forum JavaServer Pages: JSP & JSTL
    Replies: 1
    Last Post: August 17th, 2011, 11:47 AM
  5. [HELP] How can I retrieve attribute/method?
    By k4it0xtr3me in forum Object Oriented Programming
    Replies: 0
    Last Post: January 21st, 2011, 01:18 AM

Tags for this Thread