user1071914
user1071914

Reputation: 3393

Access a Spring Bean from JSP?

Note: See related question also.

I have a simple Spring Bean myUrl which is initialized with a URL (say http://yourdomain.is.here/something) from a Preferences location (Windows Registry):

<beans:bean id="myUrl" class="java.lang.String" >
    <beans:constructor-arg type="java.lang.String">
        <beans:value>${my.registry.location:some.url}</beans:value>
    </beans:constructor-arg>
</beans:bean>

The bean works fine, but I want to use it directly in a JSP file which is included in multiple locations (hence, I don't want to try including it in a specific controller's model):

<%@ taglib prefix="myTags" tagdir="/WEB-INF/tags" %>
<myTags:cssPath hostURL="${myUrl}"  relativePath="jquery-ui/css/smoothness/jquery-ui-1.10.3.custom.css" />
<myTags:cssPath hostURL="${myUrl}"  relativePath="style.css" />
<myTags:cssPath hostURL="${myUrl}"  relativePath="tableSorter.css" />

So far, nothing I have tried makes the value of the myUrl bean show up in the ${myUrl} expression. I've gone through this question and modified my ViewResolver to look like this:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/body/" />
    <property name="suffix" value=".jsp" />
    <property name="order" value="1" />
    <property name="exposedContextBeanNames">
        <list>
            <value>myUrl</value>
        </list>
    </property>
    <property name="exposeContextBeansAsAttributes" value="true"/>
</bean>

But still, the value doesn't show up. I suspect I've forgotten something horribly basic, but I don't know what. Can anyone help me?

Upvotes: 2

Views: 2824

Answers (1)

Glenn Grabbe
Glenn Grabbe

Reputation: 84

You can create a controller init method that gets the myUrl bean and stores it on the http session.

session.setAttribute("myUrl", myUrl);

Then in the JSP code you need to reference the bean.

<jsp:useBean id="myUrl" class="java.lang.String" scope="session"/>

For example to get the value:

<myTags:cssPath hostURL="<%= myUrl %>" ...

Upvotes: 4

Related Questions