Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reuse code in JSP?

Tags:

java

jsp

For example, a user will be rendered throughout my application as

<div class="user">
  <p class="username">${user.name}</p>
  <p class="karma">${user.karma}</p>
  <img src="/users/${user.id}"/>
</div>

How can I reuse this code block?

Note - my code is running within a tag, so I can't use tags for this (or any JSP) otherwise I get a Scripting elements are disallowed here error.

Edit

I'm trying to use a tag file, but getting PropertyNotFoundException.

This is my tag file called 'user.tag':

<%@tag description="User" pageEncoding="UTF-8" %>

<a href="../user/showUser.do?userId=${user.id}">
    <p>${user.name}</p>
    <img class='avatar' src='${user.avatarUrl}' alt=""/>
</a>

And usage inside a jsp:

Where job.poster is a java bean with id, name, and avatarUrl properties. If I add

<%@attribute name="user" %>

to the tag file, then I get an exception

Property 'id' not found on type java.lang.String
like image 612
ripper234 Avatar asked Feb 25 '23 03:02

ripper234


1 Answers

Since JSP 2.0, there is yet another kind of tags: Tag files. Tag files are JSP custom tags written as a JSP template itself, which seems to be what you want.

http://fforw.de/post/creating-jsp-layouts-with-page-tags/ shows how to use such a tag file as general layout solution. Using them as component should be even easier.

like image 180
fforw Avatar answered Mar 07 '23 14:03

fforw