Search code examples
javajspjsp-tags

How can I call a class inside <tag:loggedin> tags


My code in my JSP is something like this:

<tag:loggedin>
    <a href="./logout">logout</a>
</tag:loggedin>

How can I call a class or put scripting code inside tags when I can't use <% scripting elements?


Solution

  • There probably is a reason why you can't use scriptlets (<%).

    Maybe the architect on your team has forbidden to use this via a declaration in web.xml, or you are using jspx (jsp documents, aka the XML version of jsp)? The latter technically allows you to insert scriptlets, but it's too awkward in practice to really work.

    The answer to your last question is thus a simple: don't.

    Do not try to find a way to put scripting code in a JSP, it's a bad practice.

    Instead, use a Servlet to put something in the request scope. Then whatever has been put there can be referenced via an EL expression on your JSP page. The Servlet can call any Java class it wants or execute any kind of java code directly.

    In most cases it's probably easier to use a web framework like JSF, Struts or Tapestry then to cobble something together yourself using Servlets and JSP pages. For the smallest of web projects the 'old way' might still be interesting to learn a little how the lower level stuff works.