Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain model attribute or spring's bean in sitemesh decorator?

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

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.

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

like image 217
glaz666 Avatar asked Oct 17 '10 09:10

glaz666


1 Answers

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);

    }

}

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.

like image 141
mfleshman Avatar answered Sep 30 '22 21:09

mfleshman