Creating Array using JSTL or EL

后端 未结 6 1177
迷失自我
迷失自我 2020-12-05 10:06

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 oth

6条回答
  •  情歌与酒
    2020-12-05 10:51

    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.

    
    

    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.

    
    

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

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

提交回复
热议问题