簡體   English   中英

如何在Session的幫助下通過Bean將參數從Servlet傳遞到JSP頁面?

[英]How to pass parameters from Servlet via Bean to JSP page with the help of Session?

如下所述,我對代碼進行了更改,如下例所示,但在JSP中未顯示名字和姓氏:

Servlet代碼:

//....
HttpSession session = request.getSession();
Person person = (Person) session.getAttribute("person");
if (person == null) {
    person = new Person();                      
}
person.setNewId(newId);
person.setFirstName(firstName);
person.setLastName(lastName);
session.setAttribute("person", person);

RequestDispatcher rd = request.getRequestDispatcher("jsp Address");
rd.forward(request, response);

人豆代碼:

private int newId;
private String firstName;
private String lastName;

// Default Constructor
public Person() {}

public Person(int newId, String firstName, String lastName) {
    setNewId(newId);
    setFirstName(firstName);
    setLastName(lastName);
}

//Getter and Setter Methods
public int getNewId() {return newId;}
public void setNewId(int newID) {this.newId = newID;}
public String getFirstName() {return firstName;}
public void setFirstName(String FirstName) {this.firstName = FirstName;}
public String getLastName() {return lastName;}
public void setLastName(String LastName) {this.lastName = LastName;}

並在JSP代碼中:

<jsp:useBean id="person" type="app.models.Person" scope="session">
    <jsp:getProperty name="person" property="firstName" />
    <jsp:getProperty name="person" property="lastName" />
</jsp:useBean>

此JSP頁面的輸出:無

預期輸出:firstName lastName

問題:

1. How can i pass parameters from Servlets to JSP via Bean with help of Session? 
2. Is there a better way to do this code? I am using MVC architecture.

擺脫<jsp:useBean> 當使用type屬性而不是class ,它不會檢查范圍中是否已有實例,它將使用新的空白默認構造實例簡單地覆蓋您在servlet中創建的Person實例。

當使用“ MVC體系結構”時, <jsp:useBean>標記是無用的。 刪除它,只需使用常規的EL即可訪問它:

${person.firstName} ${person.lastName}

或者更好的方法是使用JSTL <c:out>來防止XSS攻擊

<c:out value="${person.firstName} ${person.lastName}" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM