0

I'm using MVC design pattern in jsp. I can pass an object to a single jsp page but not to other jsp pages(there could be many pages). I want to display userName and password of Teacher class using an Object (or through getters).

public class Teacher {
    String userName;
    String password;
    /*GETTERS AND SETTERS*/
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String userName;
    String password;

    userName = request.getParameter("tUserNameTxt");
    password = request.getParameter("tPasswordTxt");

    Teacher teacher = new Teacher();
    teacher.setUserName(userName);
    teacher.setPassword(password);

    request.setAttribute("teacher", teacher);

    RequestDispatcher dispatch;
    dispatch = request.getRequestDispatcher("login-success-teacher.jsp");
    dispatch.forward(request, response);
}

    Data to be displayed on pages:
    <body>
    <%
        Teacher teacher = (Teacher) request.getAttribute("teacher");
        session.setAttribute("teacher", teacher);
        out.println("Welcome "+ teacher.getUserName());
        out.println("Your ID is "+ teacher.getPassword());
    %>
    <h1>
        <a href="page2.jsp">Click Here</a>
    </h1>
    </body>

    Page 2:
    <body>
    <%
        Teacher teacher = (Teacher) request.getAttribute("teacher");
        session.setAttribute("teacher", teacher);
        out.println("Welcome "+ teacher.getUserName());
        out.println("Your ID is "+ teacher.getPassword());
    %>
    </body>
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
fhaider
  • 165
  • 2
  • 11

1 Answers1

2

Set the Teacher teacher in session scope in your Servlet rather than in your specific pages:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    //...
    Teacher teacher = new Teacher();
    //...
    request.getSession().setAttribute("teacher", teacher);
    //...
}

Then, retrieve it and use it in your JSP code with no problems:

Page1.jsp:

<body>
    Welcome ${teacher.username}. Your ID is ${teacher.password}
    <h1>
        <a href="page2.jsp">Click Here</a>
    </h1>
</body>

Page2.jsp:

<body>
    Welcome ${teacher.username}. Your ID is ${teacher.password}
</body>

Hints:

  • Do not use scriptlets anymore.
  • Don't use a password field as ID. Not even for test purposes. Assign a proper ID and do not store (real) password anywhere but in your database, and at least hashed.
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332