2014-12-02 194 views
0

我在jsp中使用MVC設計模式。我可以將一個對象傳遞給一個jsp頁面,但不能傳遞給其他jsp頁面(可能有很多頁面)。我想使用對象(或通過getters)顯示教師類的用戶名和密碼。JSP&MVC:將對象從控制器傳遞給jsp頁面

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> 

回答

2

坐落在你的servlet會話範圍的Teacher teacher而不是在特定的網頁:

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

然後,檢索它和你的JSP代碼,沒有任何問題使用它:

第1頁.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> 

提示:

  • Do not use scriptlets anymore
  • 請勿使用密碼字段作爲ID。甚至不用於測試目的。分配一個適當的ID並且不要將(真實)密碼存儲在數據庫中的任何地方,至少要散列。