jsp:useBean 作用域 [英] jsp:useBean scope

查看:23
本文介绍了jsp:useBean 作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSP 代码是:

<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"/>

虽然我在 request 范围内设置 java 对象,而不是在 Controller Servlet 的 session 范围内设置 java 对象,我将请求从那里转发到这个 Servlet .<jsp:useBean> 如何获得请求属性,尽管标签中提到的范围是会话?如果它使用 pageContext.findAttribute() 来获取属性,那么在 <jsp:useBean> 标签中拥有 scope 属性有什么用?

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 ?

推荐答案

PageContext#findAttribute() 分别扫描页面、请求、会话和应用范围,直到第一个非<为给定的属性键找到 code>null 属性值.另请参阅 javadoc:

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.

这解释了为什么它在转发 servlet 中找到一组请求范围,而不是在 JSP 中声明的会话范围.这也在我们的 EL wiki 页面中进行了解释.

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.

无论如何,如果您使用的是 servlet,则不应在应该由 servlet 管理的模型对象上使用 <jsp:useBean>. 遵循不同的 MVC 级别,这只会在实际使用 servlet 作为控制器时导致混淆和维护麻烦.这也在 我们的 Servlets wiki 页面的编码风格和建议"部分中明确提及.

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}

你只需要添加JSTL 来防止潜在的XSS攻击漏洞,同时重新显示用户控制的数据(注意不这样做!)

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}" />

要了解有关 JSTL 的更多信息,请查看我们的 JSTL 维基页面.

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

这篇关于jsp:useBean 作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆