简体   繁体   English

如何在scriptlet中使用JSP中可用的对象,可以做到这一点

[英]How to use an object that is available in JSP within a scriptlet, can this be done

I have a variable called statements which I am iterating over and naming row 我有一个称为statements的变量,正在迭代并命名row

<c:forEach items="${statements}" var="row">

Can I now use this variable row in a scriptlet if I do something like 我现在可以在脚本中使用此变量row吗?

<% ArrayList<String> myRows = **** something here *** %>

What do I have to replace ** something here * with to be able to do this. 为了能够执行此操作,我必须将**替换为*

Note: I know in theory this is bad, as far as I can see the problem I have (which is more complicated that this, can only be solved this way. 注意:就我所看到的问题而言,从理论上讲我知道这是不好的(更复杂的是,只能通过这种方式解决。

It's available as an attribute of the page, request, session or application scope. 它可用作页面,请求,会话或应用程序范围的属性。 If the scope is known, just call getAttribute() on the scope of interest. 如果范围是已知的,只需在感兴趣的范围上调用getAttribute()

<%
    Object pageAttribute = pageContext.getAttribute("name");
    Object requestAttribute = request.getAttribute("name");
    Object sessionAttribute = session.getAttribute("name");
    Object applicationAttribute = application.getAttribute("name");
%>

Or if the scope is unknown, use PageContext#findAttribute() . 或者,如果范围未知,则使用PageContext#findAttribute() It searches in subsequently the page, request, session and application scopes and returns the first match. 它随后在页面,请求,会话和应用程序范围内搜索,并返回第一个匹配项。

<%
    Object unknownScopedAttribute = pageContext.findAttribute("name");
%>

The above is also basically what EL is doing under the covers. 以上基本上也是EL在幕后所做的事情。


Unrelated to the concrete problem, this is definitely a workaround. 与具体问题无关,这绝对是一种解决方法。 If you elaborate in detail why need to do this, then we may be able to come up with real solutions instead of workarounds. 如果您详细说明了为什么需要这样做,那么我们也许可以提出真正的解决方案而不是解决方法。 In the meanwhile, read this thoroughly: How to avoid Java code in JSP files? 同时,请仔细阅读以下内容: 如何避免JSP文件中的Java代码?

simple answer: don't use scriptlets. 简单的答案:不要使用脚本。 complex answer: don't use scriptlets. 复杂的答案:不要使用脚本。

And that's all there is to it, really: don't use scriptlets. 这就是全部,真的:不要使用scriptlet。

If you knew how the JSTL code works, where it gets the ${statements} value from, you'd know how to use it in a scriptlet as well. 如果您知道JSTL代码的工作方式,以及从中获取$ {statements}值的地方,那么您也将知道如何在scriptlet中使用它。 But as you shouldn't use scriptlets, I'm not going to tell you any more, I'd only be leading you towards your doom and I don't intend to do that. 但是,由于您不应该使用scriptlet,所以我不会再告诉您了,我只会带您走向厄运,而我无意这样做。 Anyway, unless your ${statements} is a Collection<List<String>> your "row" local is never going to be a List<String> :) 无论如何,除非您的$ {statements}是Collection<List<String>> ,否则您的“行”本地绝不会是List<String> :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM