How can I reuse HTML / JSP on a page?

I am new to JSP and I am trying to reduce the sheer amount of cut and paste code.
Each project page has about 25 lines of mixed JSPs, Struts tags, JSTL tags, and HTML tags that have been cut and pasted at different points on the page. These ~ 25 lines of reusable code are not even removed similarly from page to page (and there are ~ 250 pages) , but exactly the same on every page . Ultimately, this code (business logic) should be removed from the view, but it will be a larger project than my schedule allows at the moment, so I wonder if there is an easy way to reuse Mixed Tags + JSP inside the page, as a temporary correction, so that the code can be reorganized in stages, taking into account the time.

For clarity, I'm looking for a way to encapsulate the code without creating a new file (/ local for the page area) - that is, it must be defined on the same page from which it is called.

Some have suggested that this can be done with Tiles - if so, please show me how to do it.

+7
jsp code-reuse
source share
3 answers

Take a look at Apache tiles . Since you are working with Struts, I am surprised that you have not found it yet. It is basically a template engine, and I think it meets your requirements.

The already proposed <jsp:include> can be used with <jsp:param> to pass variables. how

 <jsp:include file="includedFile.jsp"> <jsp:param name="username" value="jsmith" /> </jsp:include> 

Actually, if you want to include only 1 file with common code, I would recommend the simplicity of <jsp:include> in terms of the power of Tiles.

+7
source share

you can create one include and jsp file: include it where necessary. variable parts can be executed using jsp conditions, jstl EL attributes, or EL locations.

i will not necessarily transcode existing pages, as they already work.

+2
source share

Struts Tiles are best used in Struts to template a specific page, so the part that is common to all pages does not have to be encoded every time. See http://struts.apache.org/1.x/struts-tiles/ .

A simpler approach, very specific to JSP, is jsp: include, as discussed above.

Just for information, there is a third approach, which is an include include approach.

The difference between the jsp: include and include directive is as follows

You should use the include directive (<@include file relativeURL>) only if 1) if the file contains static text 2) if the file rarely changes (the JSP engine cannot recompile JSP if this type of included file is changed) 3) if you have A common piece of code that can be reused across multiple pages (for example, headers and footers)

You should use jsp: include only if 1) The content of the included JSP is dynamic and can change at runtime 2) choose which content to display at runtime (since page and src attributes can take expressions at runtime)

Hope this helps you decide.

+1
source share

All Articles