ssion的帮助下通过Bean将参数从Servlet传递到JSP

ssion的帮助下通过Bean将参数从Servlet传递到JSP

本文介绍了如何在Session的帮助下通过Bean将参数从Servlet传递到JSP页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所述,我对代码进行了更改,如下例所示,但它没有在JSP中显示firstname和lastname:

As mentioned below I have made changes to the code which looks like following example, but it doesn't show firstname and lastname in JSP:

Servlet代码:

Servlet code:

//....
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);

Person Bean代码:

Person Bean code:

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页面的输出:无

Output of this JSP page: none

预期输出:firstName lastName

Expected output: 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的> 。当使用类型属性而不是 class 时,它不会检查范围中是否已有实例,它将使用新的空白默认构造实例覆盖您在servlet中创建的 Person 实例。

Get rid of the <jsp:useBean>. When using the type attribute instead of class, it won't check if there's already an instance in the scope, it will plain override the Person instance which you created in the servlet with a new, blank, default constructed instance.

使用MVC架构时,< jsp:useBean> 标签无用。删除它,只需使用常用的即可访问它:

When using "MVC architecture", the <jsp:useBean> tag is useless. Remove it and just use usual EL to access it:

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

或者更好的是,为了防止,请使用 < c:out>

Or better, to prevent XSS attacks, use JSTL <c:out>.

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

这篇关于如何在Session的帮助下通过Bean将参数从Servlet传递到JSP页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:37