如何在速度工具中获取 HttpServletRequest?

How to get the HttpServletRequest within a velocity tool?

我想实现一个速度工具,它提供了一种方法来查明用户是否登录。我正在使用 VelocityLayoutServlet 以便在每个请求上呈现模板。

我的速度-tools.xml 看起来像这样:

<tools>
    <toolbox scope="request">
       <tool key="user" class="UserTool"/>
    </toolbox>
</tools>

我的工具class:

public class UserTool{

    // How do I get this object?
    private HttpServletRequest request;

    public boolean isLoggedIn(){
        return !request.getUserPrincipal().getName().isEmpty();
    }

}

如何在我的工具中获取 HttpServletRequest 对象?

仅供参考:我正在使用容器管理的身份验证。

这有两个缺陷:

  1. 如果请求是匿名的,您将收到 NullPointerException
  2. 您的工具是多余的,因为 Velocity-bundled Servlet 应该已经将请求添加到上下文中:$request.remoteUser.

作用域request不表示HTTP请求。它只是强调在每次渲染请求时都会重新创建此工具。