有时候您可能需要自己动手写一些工具类在view层进行使用,类似jstl函数在jsp页面中使用,(关于jstl函数,相信做java的开发人员基本都用过),下面介绍一种在spring mvc中将工具类导出在view层使用的另一种方式,功能很容易,实现也简单,在此记录下。
类org.springframework.web.servlet.view.UrlBasedViewResolver提供了2个方法:
我们可以利用这个扩展点结合util:map标签进行下面设置:
这样就可以在页面中直接使用${selfKey}或者${utilKey.方法名(方法参数)}
注意:这种方法的对于jsp要生效,请选用支持el 2.2 specification的服务器,比如tomcat7
类org.springframework.web.servlet.view.UrlBasedViewResolver提供了2个方法:
public void setAttributes(Properties props) {
CollectionUtils.mergePropertiesIntoMap(props, this.staticAttributes);
}
public void setAttributesMap(Map<String, ?> attributes) {
if (attributes != null) {
this.staticAttributes.putAll(attributes);
}
}
我们可以利用这个扩展点结合util:map标签进行下面设置:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<!--attributesMap这个name也可以使用attributes-->
<property name="attributesMap" ref="constants" />
</bean>
<util:map id="constants">
<entry key="selfKey" value="value" />
<entry key="utilKey" ref="工具类beanid" />
</util:map>
这样就可以在页面中直接使用${selfKey}或者${utilKey.方法名(方法参数)}
注意:这种方法的对于jsp要生效,请选用支持el 2.2 specification的服务器,比如tomcat7