简体   繁体   English

从JSP访问Spring Bean?

[英]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): 我有一个简单的Spring Bean myUrl ,它是通过Preferences位置(Windows注册表)中的URL(例如http://yourdomain.is.here/something )初始化的:

<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): Bean工作正常,但我想直接在多个位置包含的JSP文件中使用它(因此,我不想尝试将其包含在特定控制器的模型中):

<%@ 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. 到目前为止,我还没有尝试过使myUrl bean的值显示在${myUrl}表达式中。 I've gone through this question and modified my ViewResolver to look like this: 我经历了这个问题,并将ViewResolver修改为如下形式:

<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? 谁能帮我?

You can create a controller init method that gets the myUrl bean and stores it on the http session. 您可以创建一个控制器初始化方法,该方法获取myUrl bean并将其存储在http会话中。

session.setAttribute("myUrl", myUrl);

Then in the JSP code you need to reference the bean. 然后,在JSP代码中,您需要引用bean。

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

For example to get the value: 例如,获取值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM