Announcement Announcement Module
Collapse
No announcement yet.
How to access ServletContext in Velocity Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to access ServletContext in Velocity

    Sorry to be dense, but what are the steps to access the ServletContext in a Velocity view?

    Thanks,
    Jon

  • #2
    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:

    Code:
    $!{context.servletContext.serverInfo}
    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:
    request.setAttribute("servletContext",getServletContext());
    And then set exposeRequestAttributes equal to true in your VelocityViewResolver, then you can access it in Velocity like this:

    Code:
    $!{servletContext.serverInfo}

    Comment


    • #3
      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.

      Comment


      • #4
        Thanks for the suggestion Paul.

        I modified what you suggested and came up with the following:

        In my viewResolver definition:

        Code:
        ...
        <property name="requestContextAttribute"><value>context</value></property>
        ...
        Which places the RequestContext attribute into the request under the name "context", just like you mentioned.

        Then, to get around getServletContext() being a protected method of RequestContext, I do the following in my Velocity templates:

        Code:
        $context.webApplicationContext.servletContext.getAttribute&#40; "serverInfo" &#41;
        This works great! However, does anyone know of a less wordy way to do this? It seems like:

        Code:
        $context.webApplicationContext.servletContext.getAttribute&#40; "serverInfo" &#41;
        just to get one variable is a heck of a lot of typing.

        Thanks to both of you for your suggestions.

        Jon

        Comment

        Working...
        X