Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

java - jsp:useBean scope

The JSP code is :

<jsp:useBean id="person" class="org.example.model.PersonModel" scope="session">
</jsp:useBean>
<br> Name : <jsp:getProperty property="name" name="person"/>
<br> Surname : <jsp:getProperty property="surname" name="person"/>

Although I set java object in the request scope and not in the session scope in the Controller Servlet from where I am forwarding the request to this Servlet . How does the <jsp:useBean> gets hold of the request attribute although scope mentioned in the tag is session? If it uses pageContext.findAttribute() to get the attribute, then what is the use of having the scope attribute in that <jsp:useBean> tag ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The PageContext#findAttribute() scans in respectively the page, request, session and application scopes until the first non-null attribute value is found for a given attribute key. See also the javadoc:

Searches for the named attribute in page, request, session (if valid), and application scope(s) in order and returns the value associated or null.

That explains why it finds the request scoped one set in the forwarding servlet instead of the session scoped one declared in the JSP. This is also explained in our EL wiki page.

In any case, if you're using a servlet, you should not be using <jsp:useBean> on model objects which are supposed to be managed by a servlet. The <jsp:useBean> follows namely a different MVC level which would only lead to confusion and maintenance trouble when actually using a servlet as controller. This is also explicitly mentioned in "Coding style and recommendations" section of our Servlets wiki page.

So, instead of all those <jsp:xxx> things, you can just do:

<br>Name: ${person.name}
<br>Surname: ${person.surname}

You only need to add JSTL <c:out> to prevent potential XSS attack holes while redisplaying user-controlled data (note that <jsp:getProperty> doesn't do that!)

<br>Name: <c:out value="${person.name}" />
<br>Surname: <c:out value="${person.surname}" />

To learn more about JSTL, check our JSTL wiki page.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...