jonsinfinity
jonsinfinity

Reputation: 197

How do you Access Grails ServletContext in a gsp file?

I have a list of categories that need to live inside of the servletContext scope of the app since the list will be accessed by every view and will not need to be modified.

I tried setting a new servletContext property in the init method of BootStrap.groovy but I don't seem to be able to access the servletContext in the gsp files.

Here is what I'm trying. How do I access servletContext (application) scope properties from a gsp file?


import org.codehaus.groovy.grails.commons.ApplicationHolder as AH

import java.util.List
import java.util.ArrayList

class BootStrap {

    def init = { 

        servletContext ->

        def dataSource = AH.application.mainContext.dataSource

        List categories

        def sql = new Sql(dataSource);
        def rows = sql.rows("select distinct catgry from cmpitmms");

        categories = new ArrayList();

        for (arg in rows) {
            println arg.getAt(0)
            if (!arg.getAt(0).trim().equals("")) {
                categories.add(arg.getAt(0).trim());
            }
        }

        servletContext.categories = categories

    }
    def destroy = {
    }
}


Here is where I'm trying to access it in the gsp file.

<ul>
    <g:each var="category" in="${servletContext.categories}">
        <li><a href="category/${category}" title="${category}">${category}</a></li>
    </g:each>
</ul>

Upvotes: 2

Views: 3106

Answers (2)

Aditya
Aditya

Reputation: 21

You could still use

servletContext.categories = categories

and in the gsp use

<g:each var="category" in="${application.categories}">
   <li><a href="category/${category}" title="${category}">${category}</a></li>
</g:each>

Setting it as a attribute is not needed

Upvotes: 2

jonsinfinity
jonsinfinity

Reputation: 197

Found it!

Instead of

servletContext.categories = categories

Do

servletContext.setAttribute("categories", categories)

Then in the gsp use

<g:each var="category" in="${application.categories}">
   <li><a href="category/${category}" title="${category}">${category}</a></li>
</g:each>

Upvotes: 3

Related Questions