Sorry to be dense, but what are the steps to access the ServletContext in a Velocity view?
Thanks,
Jon
Sorry to be dense, but what are the steps to access the ServletContext in a Velocity view?
Thanks,
Jon
Seems as though the powers-that-be with Spring don't want you to. If in the configuration of your VelocityViewResolver, you set requestContextAttribute equal to something, say "context" for example, then you would be able to access like this:
But RequestContext.getServletContext() is protected, so that doesn't work. A way to do it that actually works is do this in your Controller:Code:$!{context.servletContext.serverInfo}
And then set exposeRequestAttributes equal to true in your VelocityViewResolver, then you can access it in Velocity like this:Code:request.setAttribute("servletContext",getServletContext());
Code:$!{servletContext.serverInfo}
Another approach would perhaps be to specifically get the properties you need from ServletContext and put them in your ModelAndView, for Spring MVC seems to promote passing data to views through ModelAndView.
--Jing Xue
Thanks for the suggestion Paul.
I modified what you suggested and came up with the following:
In my viewResolver definition:
Which places the RequestContext attribute into the request under the name "context", just like you mentioned.Code:... <property name="requestContextAttribute"><value>context</value></property> ...
Then, to get around getServletContext() being a protected method of RequestContext, I do the following in my Velocity templates:
This works great! However, does anyone know of a less wordy way to do this? It seems like:Code:$context.webApplicationContext.servletContext.getAttribute( "serverInfo" )
just to get one variable is a heck of a lot of typingCode:$context.webApplicationContext.servletContext.getAttribute( "serverInfo" ).
Thanks to both of you for your suggestions.
Jon