使用 JSTL 或 EL 创建数组 [英] Creating Array using JSTL or EL

查看:26
本文介绍了使用 JSTL 或 EL 创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Java 及其框架(Spring 3.1.1)开发一个 Web 应用程序.而且我试图尽可能避免使用 scriptlet,但是我找不到除此之外的其他方法来定义数组:

I'm working on a web application using Java and its frameworks(Spring 3.1.1). And I'm trying to avoid using scriptlets as much as possible, however I can't find a way other than this to define an array:

<%
    String[] alphabet = {"A", "B", "C", ... , "Z"};
    pageContext.setAttribute("alphabet", alphabet);      
%> 

设置 pageContext 属性后,我可以将它与 ${alphabet} 一起使用.但我想知道,是否可以使用普通的 JSTL/EL 来创建数组?

After setting pageContext attribute, I can use it with ${alphabet}. But I want to know, is it possible to use plain JSTL/EL to create an array?

更新:我正在使用这个数组来创建链接.例如,如果用户单击S",则会出现名字以S"开头的员工列表.所以,我不是一个一个地创建链接,而是迭代 ${alphabet}.

UPDATE: I'm using this array to create links. For example, if user clicks 'S', a list of employees whose first name starts with 'S' comes. So, instead of creating links one by one I'm iterating ${alphabet}.

推荐答案

如果您已经使用 EL 3.0(Tomcat 8+、WildFly 8+、GlassFish 4+、Payara 4+、TomEE 7+ 等),支持新的对集合对象的操作,可以使用${[...]} 语法构造一个列表,${{...}} 语法构造一个集合.

If you're already on EL 3.0 (Tomcat 8+, WildFly 8+, GlassFish 4+, Payara 4+, TomEE 7+, etc), which supports new operations on collection objects, you can use ${[...]} syntax to construct a list, and ${{...}} syntax to construct a set.

<c:set var="alphabet" value="${['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']}" scope="application" />

如果您尚未使用 EL 3.0,请在单个字符串上使用 ${fn:split()} 函数技巧,该字符串通过公共分隔符(例如逗号)分隔各个字符.

If you're not on EL 3.0 yet, use the ${fn:split()} function trick on a single string which separates the individual characters by a common separator, such as comma.

<c:set var="alphabet" value="${fn:split('A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z', ',')}" scope="application" />

不过,我同意您最好为此使用普通的 Java 代码.鉴于它显然是静态数据,只需创建此侦听器类:

I do however agree that you're better off using normal Java code for this. Given that it's apparently static data, just create this listener class:

@WebListener
public class ApplicationData implements ServletContextListener {

    private static final String[] ALPHABET = { "A", "B", "C", ..., "Z" };

    @Override
    public void contextInitialized(ServletContextEvent event) {
        event.getServletContext().setAttribute("alphabet", ALPHABET);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // NOOP.
    }

}

它会在 webapp 启动时透明地自动注册自己,并将所需的数据放入应用程序范围.

It'll transparently auto-register itself on webapp's startup and put the desired data in application scope.

这篇关于使用 JSTL 或 EL 创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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