0

I want to implement a velocity tool that provides a method in order to find out weather a user is logged in or not. I'm using the VelocityLayoutServlet in order to render the templates on each request.

My velocity-tools.xml looks like this:

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

My tool class:

public class UserTool{

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

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

}

How do I get the HttpServletRequest object within my tool?

FYI: I'm using container managed authentication.

Mr ASquare
  • 391
  • 1
  • 8
  • 22
eztam
  • 3,443
  • 7
  • 36
  • 54

1 Answers1

1

This has two flaws:

  1. If the request is anonymous, you will receive a NullPointerException
  2. Your tool is superfluous because the Velocity-bundled Servlet is supposed to add request already into the context: $request.remoteUser.

The scope request does not denote the HTTP request. It simply reams that this tools is recreated on every rendering request.

Michael-O
  • 18,123
  • 6
  • 55
  • 121
  • Thanks for the answer, now I'm one step further. Now I can access the user from within the template file. But I need to render some parts of the template only, when the user is logged in. How can I do this? `$request.remoteUser.isEmpty()` works only when the user is logged in. – eztam Mar 18 '16 at 12:10
  • 1
    @eztam Don't use `isEmpty` you may run into a NPE. Idealy, you work with roles: `$request.isUserInRole`. If you care for authentication only use this idiom `#if ($request.remoteUser) ... #end`. See [here](http://stackoverflow.com/a/3478701/696632). – Michael-O Mar 18 '16 at 13:26