繁体   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