如何在SiteMesh装饰器中获取模型属性或Spring Bean? [英] How to obtain model attribute or spring's bean in sitemesh decorator?

查看:64
本文介绍了如何在SiteMesh装饰器中获取模型属性或Spring Bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Spring 3与sitemesh一起使用.我想在sitemesh中定义的装饰器页面中引用spring context bean.

I am using Spring 3 with sitemesh. I would like to refer to spring context bean in decorator page defined in sitemesh.

问题在于SiteMesh过滤器在Spring上下文之外运行,因此sitemesh装饰器jsp页面上的请求对象是本机HttpServletRequest,而不是具有用于访问上下文等的有用函数的包装器.

The problem is that SiteMesh filter is working outside the Spring context, so request object on sitemesh decorator jsp page is native HttpServletRequest and not wrapper with useful functions to access context and etc.

是否可以通过某种方式配置spring和sitemesh来访问装饰器页面中的Spring上下文?

Is there a way to somehow configure both spring and sitemesh to have access to Spring context in decorator page?

推荐答案

我遇到了同样的问题,并通过使用过滤器解决了我的问题.我创建了一个环境过滤器,可用于为所有请求设置环境数据.在过滤器中自动装配您也需要访问的bean.

I had the same issue and solved my problem by using a filter. I created an environment filter that I could use for setting environment data for all requests. Autowire the bean you need to have access too in the filter.

@Component
public class EnvironmentFilter extends OncePerRequestFilter {

    @Autowired
    Object bean;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        request.setAttribute("bean", bean); // add bean or just specific properties of bean.

        filterChain.doFilter(request, response);

    }

}

在web.xml中配置过滤器,请确保对过滤器映射使用与Sitemesh过滤器相同的模式.

Configure the filter in web.xml, be sure to use the same pattern for the filter mapping as you have for Sitemesh filter.

<filter>
    <filter-name>environmentFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>environmentFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

通过过滤器设置的属性现在可以在装饰页面上使用.

The attributes set from your filter are now available from your decorator page.

这篇关于如何在SiteMesh装饰器中获取模型属性或Spring Bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆