How can I reuse code in JSP?
For example, the user will appear in 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 block of code?
Note. My code works in a tag, so I canβt use tags for this (or any JSP), otherwise I get a Scripting elements are disallowed here error Scripting elements are disallowed here .
Edit
I try to use a tag file, but get a PropertyNotFoundException.
This is my tag file named '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 use inside 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 With JSP 2.0, there is another kind of tag: tag files. Tag files are custom JSP tags written as the JSP template itself, which you seem to need.
http://fforw.de/post/creating-jsp-layouts-with-page-tags/ shows how to use a tag file such as a general layout solution. Using them as a component should be even easier.
You should be able to use tag files in tag files; this works for me in a JSP 2.2 container:
<%-- mytag.tag --%> <%@tag description="demo code" pageEncoding="UTF-8"%> <%@taglib prefix="cust" tagdir="/WEB-INF/tags" %> <%@attribute name="message"%> <cust:mytag2 message="${message}" /><%-- uses mytag2.tag --%> If this fails, you can use the include directive: <%@include file="/WEB-INF/jspf/fragment.jspf" %>
Note that the spec speaks about tags:
Directive Available? Interpretation/Restrictions ====================================================================== page no A tag file is not a page. The tag directive must be used instead. If this directive is used in a tag file, a translation error must result. So fragment.jspf should not have any elements that are not supported in tags, including the page directive.
In the example you specified, it sounds like it would take some kind of template system to display the user icon on each screen. At the simplest level, it could just be jsp: include, which always includes your "UserBadge.jsp".
If you work in a web environment, for example. JSF, you can use Facelet templates or write a custom component for this. Therefore, the answer depends on what kind of framework you have. Dividing it only into JSP and JSTL - the included JSP or javax.servlet.jsp.tagext.Tag will certainly reduce duplication.
Always be careful following the DRY principle ... Do not repeat yourself!
I feel that sometimes creating a .tag file is redundant (especially if it is for just one page), and I wanted you to describe for many years, so I wrote my own, simple solution. Take a look here: fooobar.com/questions/1300605 / ...