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

匿名 (未验证) 提交于 2019-12-03 08:56:10

问题:

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 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 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;} 

And in JSP code:

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

Output of this JSP page: none

Expected output: firstName lastName

Questions:

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. 

回答1:

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.

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

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

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

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!