Without standard actions (using scripting)
Case1: Servlet Setting a String as Attribute and getting that string using JSP
Servlet code
String name = request.getParameter(“userName”);request.setAttribute(“name”, name);)
JSP
< %= request.getAttribute(“name”) % >Case2: Servlet Setting an Object as attribute and getting that Object using JSP
Servlet code
foo.Person p = new foo.Person();p.setName(“Evan”);
request.setAttribute(“person”, p);
JSP
< % foo.Person p = (foo.Person) request.getAttribute(“person”); % >Person is: < %= p.getName() % >
Or
Person is:< %= ((foo.Person) request.getAttribute(“person”)).getName() % >With standard actions (no scripting)
Case1: Servlet Setting an Object as attribute and getting that Object using beans in JSP
Servlet code
foo.Person p = new foo.Person();
p.setName(“Evan”);
request.setAttribute(“person”, p);
JSP
< jsp:getProperty >
< jsp:useBean id=”person” class=”foo.Person” scope=”request” / >
< jsp:getProperty name=”person” property=”name” / >
Case 2: JSP Setting an Object as attribute using beans
< jsp:setProperty >
< jsp:useBean id=”person” class=”foo.Person” scope=”request” / >
< jsp:setProperty name=”person” property=”name” value=”Fred” / >
If you put your setter code (< jsp:setProperty >) inside the body of < jsp:useBean >, the property values will be set only if a new bean is created. If an existing bean with that scope and id are found, the body of the tag will never run, so the property won’t be reset from your JSP code.
< jsp:useBean id=”person” class=”foo.Person” scope=”page” >
< jsp:setProperty name=”person” property=”name” value=”Fred” / >
< /jsp:useBean >
Adding a type attribute to < jsp:useBean >
< jsp:useBean id=”person” type=”foo.Person” class=”foo.Employee” scope=”page” >
Generated servlet based on above JSP code
foo.Person person = null;
// code to get the person attribute
if (person == null){
person = new foo.Employee();}
The scope attribute defaults to “page”
If you don’t specify a scope in either the < jsp:useBean > or < jsp:getProperty > tags,the Container uses the default of “page”.This
< jsp:useBean id=”person” class=”foo.Employee” scope=”page”/ >
Is the same as this
< jsp:useBean id=”person” class=”foo.Employee”/ >
Note: Be SURE that you remember:
In < jsp:useBean > attribute
In < jsp:useBean > attribute
type == reference type
class == object type
This post first appeared on Every Day Of Your Life Is A Page Of Your History, please read the originial post: here