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

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

问题描述

我正在使用Java和它的框架(春季3.1.1)的Web应用程序。而我试图避免使用小脚本尽可能,但我找不到比这个其他的方式来定义一个数组:

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属性之后,我可以用 $使用{字母} 。但我想知道,是否有可能使用纯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'来了。因此,而不是创建链接一个接一个,我迭代 $ {字母}

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,它支持新的上收集操作对象,您可以使用 $ {[...]} 语法来构建一个列表,而 $ {{...}} 语法来构建一套。

If you're already on EL 3.0, 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:斯普利特()} 由一个共同的单个字符分隔一个字符串函数绝招分隔符,如逗号。

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 code这一点。鉴于这是显然的静态数据,只是创建这个监听器类:

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.
    }

}

这将在透明的web应用程序的启动自动注册本身,并把所需数据的应用范围。

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

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

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