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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With