jsp:useBean scope

两盒软妹~` 提交于 2019-11-27 06:26:18

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/14579121/jspusebean-scope

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