简体   繁体   中英

Best practice: custom jsp tag or include tag?

What is the best practice for reusable jsp components in your code? Writing a custom tag or using the <jsp:include> tag?

Which circumstances would dictate the use of one or the other?

Use case: I'm trying to refactor part of an application and would like to make an informed decision on how to break down the html into reusable pieces. I'm currently using a custom tag to build a layout including page header and footer and the html head and dependencies. But I'm unsure of the best way to include a chunk of static html that's reused across the app.

There are really a number of reasons to go with one or the other from a codebase organization standpoint.

A primary reason to create a Tag Library instead of using the jsp:include tag is to provide parameters and values that might influence the markup generated. Say you want to pass a username to appear in your page header that you've spent precious cycles retrieving already. Also if you have especially complicated logic (ie anything more than conditionals or loops), a Tag Library is the way to go. Nobody wants a mess of spaghetti code sitting in a JSP.

I would say that a tag library that accepts no parameters that always produces static output is functionally equivalent to using jsp:include .

Your specific use case involves somewhat related markup. You have a page header and a page footer. It might make sense to implement this as different tags within the same Tag Library class, to keep these related snippets in the same location.

On the other hand, encapsulating HTML inside a Tag Library reduces the maintainability for non-developers. Say you have a graphic designer on a project that doesn't know a lick of Java but wanted to edit the markup. Sure, they might be able to wade through a tag library class and figure out what they need to change; maybe not!

To sum up, if you think you might pass parameters, or you have business logic, it's Tag Library all the way. If it's just static content and/or you want non-developers to help edit, maybe stick with an included .jsp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM