In a special case, I need to make the same as <jsp:useBean in Java class.
It sounds like using org.apache.commons.beanutils.BeanUtils.cloneBean(Object bean) will do the work.
But what is driving me crazy is that I can't find the TLD associated to <jsp: tags, nor the class used by <jsp:useBean.
Even <short-name>jsp</short-name> on Google gives me nothing.
The JSP specs I found makes me believe that it's not a tag like the others and that the code behind <jsp:useBean is in Java's core.
Am I right? Have I missed something?
There's no TLD for <jsp: elements in the JSP page. These elements are part of the JSP language. With this language you can create JSP pages but if you need to use custom TLDs like JSTL then you should use taglib directive.
What is interesting in JSP: it's called now Jakarta Server Pages. You can read more about this in the article What is JSP? Introduction to Jakarta Server Pages.
One of the original Java web technologies, JSP is still widely used with servlets and JSTL. Here's how to use Jakarta Server Pages to build dynamic web pages that connect to the Java back end.
<jsp:useBean> is an action tag and not part of a tag library, cf. https://en.wikipedia.org/wiki/Jakarta_Server_Pages#Syntax, scroll down to "Additional Tags".
The code probably was part of J2EE back in the day or is in the servlet containers. Today it apparently is an eclipse project: https://projects.eclipse.org/projects/ee4j.jsp.
<jsp:useBean> is actually "a JSP server markup tag" "the server knows in a JSP specification server", the "tags" you are thinking of are standard tag library c: f: are resources that use a TLD Tag Library Descriptor (stored in a jar package to be loaded as a resource) and are from the original "custom tag" API system.
Custom tags do not need to be in a .jar, unjared they must be put in /webapplication/WEB-INF/tags/ often associated with non programmatic tags that operate like an include markup file. jar packaged tags are in a folder structure /webapplication*/META-INF/tags/* any tags wherever they reside require to be named to their full path in an XML markup like .tld file in the top directory of the package.
If your needs are simple for the bean, then you can just add code directly to your JSP. To see what I mean, look at the Servlet that was generated from your JSP. Every JSP is translated to a Servlet. For example, consider the following JSP.
<jsp:useBean id="myList" class="java.util.ArrayList"/>
${myList.add("My first element")}
<%myList.add("My second element");%>
${myList}
The translation(in Tomcat's work folder) is
java.util.ArrayList myList = null;
myList = (java.util.ArrayList) _jspx_page_context.getAttribute("myList", jakarta.servlet.jsp.PageContext.PAGE_SCOPE);
if (myList == null){
myList = new java.util.ArrayList();
_jspx_page_context.setAttribute("myList", myList, jakarta.servlet.jsp.PageContext.PAGE_SCOPE);
}
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${myList.add(\"My first element\")}", java.lang.String.class, (jakarta.servlet.jsp.PageContext)_jspx_page_context, null));
myList.add("My second element");
out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${myList}", java.lang.String.class, (jakarta.servlet.jsp.PageContext)_jspx_page_context, null));
The useBean action tag just creates a scripting variable and sets a scoped variable. You can do that without any special tag. The following JSP does the same thing.
<%# page import="java.util.ArrayList"%>
<%
ArrayList myList2 = new ArrayList();
myList2.add("one");
pageContext.setAttribute("myList2", myList2);
%>
${myList2}
<%=myList2%>
Related
It seems that there are two methods for templating with JSP. Including files with one of these statements
<%# include file="foo.html" %>
<jsp:include page="foo.html" />
or using JSP tag files
// Save this as mytag.tag
<%# tag description="Description" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<jsp:doBody/>
</body>
</html>
And in another JSP page call it with
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:mytag>
<h1>Hello World</h1>
</t:mytag>
So which method should I use? Is one now considered deprecated or are they both valid and cover different use cases?
Edit
Isn't using this tag file the same as using an include?
// Save this as product.tag
<%# tag description="Product templage" pageEncoding="UTF-8"%>
<%# tag import="com.myapp.Product" %>
<%# attribute name="product" required="true" type="com.myapp.Product"%>
Product name: ${product.name} <br/>
Quantity: ${product.quantity} <br/>
And call it on another JSP with
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:product>
<c:forEach items="${cart.products}" var="product">
<t:product product="${product}"/>
</c:forEach>
</t:product>
That seems to me to be the very same as using an include and passing parameters to it. So are Tag Files the same as includes?
Overview of JSP Syntax Elements
First, to make things more clear, here is a short overview of JSP syntax elements:
Directives: These convey information regarding the JSP page as a
whole.
Scripting elements: These are Java coding elements such as
declarations, expressions, scriptlets, and comments.
Objects and scopes: JSP objects can be created either explicitly or
implicitly and are accessible within a given scope, such as from
anywhere in the JSP page or the session.
Actions: These create objects or affect the output stream in the JSP
response (or both).
How content is included in JSP
There are several mechanisms for reusing content in a JSP file.
The following 4 mechanisms to include content in JSP can be categorized as direct reuse:
(for the first 3 mechanisms quoting from "Head First Servlets and JSP")
1) The include directive:
<%# include file="header.html" %>
Static: adds the content from the value of the file attribute to the current page at translation time. The directive was
originally intended for static layout templates, like HTML headers.
2) The <jsp:include> standard action:
<jsp:include page="header.jsp" />
Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic
content coming from JSPs.
3) The <c:import> JSTL tag:
<c:import url=”http://www.example.com/foo/bar.html” />
Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like
<jsp:include>, but it’s more powerful and flexible: unlike the
other two includes, the <c:import> URL can be from outside the
web Container!
4) Preludes and codas:
Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas
(also called footers) for a group of JSP pages by adding
<include-prelude> and <include-coda> elements respectively within
a <jsp-property-group> element in the Web application web.xml deployment descriptor.
Read more here:
• Configuring Implicit Includes at the Beginning and End of JSPs
• Defining implicit includes
Tag File is an indirect method of content reuse, the way of encapsulating reusable content.
A Tag File is a source file that contains a fragment of JSP code that is reusable as a custom tag.
The PURPOSE of includes and Tag Files is different.
Tag file (a concept introduced with JSP 2.0) is one of the options for creating custom tags. It's a faster and easier way to build custom tags.
Custom tags, also known as tag extensions, are JSP elements that allow custom logic and output provided by other Java components to be inserted into JSP pages. The logic provided through a custom tag is implemented by a Java object known as a tag handler.
Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control.
Regarding your Edit
Maybe in your example (in your "Edit" paragraph), there is no difference between using direct include and a Tag File. But custom tags have a rich set of features. They can
Be customized by means of attributes passed from the calling page.
Pass variables back to the calling page.
Access all the objects available to JSP pages.
Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag.
Be nested within one another and communicate by means of private variables.
Also read this from "Pro JSP 2": Understanding JSP Custom Tags.
Useful reading.
Difference between include directive and include action in
JSP
JSP tricks to make templating
easier
Very informative and easy to understand tutorial from coreservlet.com with beautiful
explanations that include <jsp:include> VS. <%# include %>
comparison table:
Including Files and Applets in JSP
Pages
Another nice tutorial from coreservlets.com related to tag libraries and
tag files:
Creating Custom JSP Tag Libraries: The
Basics
The official Java EE 5 Tutorial with examples:
Encapsulating Reusable Content
Using Tag
Files.
This page from the official Java EE 5 tutorial should give you even
more understanding:
Reusing Content in JSP
Pages.
This excerpt from the book "Pro JSP 2" also discuses why do you need
a Tag File instead of using static include:
Reusing Content with Tag
Files
Very useful guide right from the Oracle documentation:
Static Includes Versus Dynamic Includes
Conclusion
Use the right tools for each task.
Use Tag Files as a quick and easy way of creating custom tags that can help you encapsulate reusable content.
As for the including content in JSP (quote from here):
Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.
Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.
Possible Duplicate Question
<#include> - The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.
Only one servlet is executed at run time.
Scriptlet variables declared in the parent page can be accessed in the included page (remember, they are the same page).
The included page does not need to able to be compiled as a standalone JSP. It can be a code fragment or plain text. The included page will never be compiled as a standalone. The included page can also have any extension, though .jspf has become a conventionally used extension.
One drawback on older containers is that changes to the include pages may not take effect until the parent page is updated. Recent versions of Tomcat will check the include pages for updates and force a recompile of the parent if they're updated.
A further drawback is that since the code is inlined directly into the service method of the generated servlet, the method can grow very large. If it exceeds 64 KB, your JSP compilation will likely fail.
<jsp:include> - The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.
Each included page is executed as a separate servlet at run time.
Pages can conditionally be included at run time. This is often useful for templating frameworks that build pages out of includes. The parent page can determine which page, if any, to include according to some run-time condition.
The values of scriptlet variables need to be explicitly passed to the include page.
The included page must be able to be run on its own.
You are less likely to run into compilation errors due to the maximum method size being exceeded in the generated servlet class.
Depending on your needs, you may either use <#include> or
<jsp:include>
Main advantage of <jsp:include /> over <%# include > is:
<jsp:include /> allows to pass parameters
<jsp:include page="inclusion.jsp">
<jsp:param name="menu" value="objectValue"/>
</jsp:include>
which is not possible in <%#include file="somefile.jsp" %>
All three template options - <%#include>, <jsp:include> and <%#tag> are valid, and all three cover different use cases.
With <#include>, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.
<jsp:include> (and JSTL's <c:import>, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import> also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".
Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%#tag attribute> and these arguments can be either mandatory or optional - somewhat like method parameters.
Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.
According to:
Java Revisited
Resources included by include directive are loaded during jsp translation time, while resources included by include action are loaded during request time.
Any change on included resources will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in the next request.
Include directive is static import, while include action is dynamic import.
Include directive uses file attribute to specify resources to be included while include action uses page attribute for the same purpose.
It seems that there are two methods for templating with JSP. Including files with one of these statements
<%# include file="foo.html" %>
<jsp:include page="foo.html" />
or using JSP tag files
// Save this as mytag.tag
<%# tag description="Description" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<jsp:doBody/>
</body>
</html>
And in another JSP page call it with
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:mytag>
<h1>Hello World</h1>
</t:mytag>
So which method should I use? Is one now considered deprecated or are they both valid and cover different use cases?
Edit
Isn't using this tag file the same as using an include?
// Save this as product.tag
<%# tag description="Product templage" pageEncoding="UTF-8"%>
<%# tag import="com.myapp.Product" %>
<%# attribute name="product" required="true" type="com.myapp.Product"%>
Product name: ${product.name} <br/>
Quantity: ${product.quantity} <br/>
And call it on another JSP with
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:product>
<c:forEach items="${cart.products}" var="product">
<t:product product="${product}"/>
</c:forEach>
</t:product>
That seems to me to be the very same as using an include and passing parameters to it. So are Tag Files the same as includes?
Overview of JSP Syntax Elements
First, to make things more clear, here is a short overview of JSP syntax elements:
Directives: These convey information regarding the JSP page as a
whole.
Scripting elements: These are Java coding elements such as
declarations, expressions, scriptlets, and comments.
Objects and scopes: JSP objects can be created either explicitly or
implicitly and are accessible within a given scope, such as from
anywhere in the JSP page or the session.
Actions: These create objects or affect the output stream in the JSP
response (or both).
How content is included in JSP
There are several mechanisms for reusing content in a JSP file.
The following 4 mechanisms to include content in JSP can be categorized as direct reuse:
(for the first 3 mechanisms quoting from "Head First Servlets and JSP")
1) The include directive:
<%# include file="header.html" %>
Static: adds the content from the value of the file attribute to the current page at translation time. The directive was
originally intended for static layout templates, like HTML headers.
2) The <jsp:include> standard action:
<jsp:include page="header.jsp" />
Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic
content coming from JSPs.
3) The <c:import> JSTL tag:
<c:import url=”http://www.example.com/foo/bar.html” />
Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like
<jsp:include>, but it’s more powerful and flexible: unlike the
other two includes, the <c:import> URL can be from outside the
web Container!
4) Preludes and codas:
Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas
(also called footers) for a group of JSP pages by adding
<include-prelude> and <include-coda> elements respectively within
a <jsp-property-group> element in the Web application web.xml deployment descriptor.
Read more here:
• Configuring Implicit Includes at the Beginning and End of JSPs
• Defining implicit includes
Tag File is an indirect method of content reuse, the way of encapsulating reusable content.
A Tag File is a source file that contains a fragment of JSP code that is reusable as a custom tag.
The PURPOSE of includes and Tag Files is different.
Tag file (a concept introduced with JSP 2.0) is one of the options for creating custom tags. It's a faster and easier way to build custom tags.
Custom tags, also known as tag extensions, are JSP elements that allow custom logic and output provided by other Java components to be inserted into JSP pages. The logic provided through a custom tag is implemented by a Java object known as a tag handler.
Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control.
Regarding your Edit
Maybe in your example (in your "Edit" paragraph), there is no difference between using direct include and a Tag File. But custom tags have a rich set of features. They can
Be customized by means of attributes passed from the calling page.
Pass variables back to the calling page.
Access all the objects available to JSP pages.
Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag.
Be nested within one another and communicate by means of private variables.
Also read this from "Pro JSP 2": Understanding JSP Custom Tags.
Useful reading.
Difference between include directive and include action in
JSP
JSP tricks to make templating
easier
Very informative and easy to understand tutorial from coreservlet.com with beautiful
explanations that include <jsp:include> VS. <%# include %>
comparison table:
Including Files and Applets in JSP
Pages
Another nice tutorial from coreservlets.com related to tag libraries and
tag files:
Creating Custom JSP Tag Libraries: The
Basics
The official Java EE 5 Tutorial with examples:
Encapsulating Reusable Content
Using Tag
Files.
This page from the official Java EE 5 tutorial should give you even
more understanding:
Reusing Content in JSP
Pages.
This excerpt from the book "Pro JSP 2" also discuses why do you need
a Tag File instead of using static include:
Reusing Content with Tag
Files
Very useful guide right from the Oracle documentation:
Static Includes Versus Dynamic Includes
Conclusion
Use the right tools for each task.
Use Tag Files as a quick and easy way of creating custom tags that can help you encapsulate reusable content.
As for the including content in JSP (quote from here):
Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.
Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.
Possible Duplicate Question
<#include> - The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.
Only one servlet is executed at run time.
Scriptlet variables declared in the parent page can be accessed in the included page (remember, they are the same page).
The included page does not need to able to be compiled as a standalone JSP. It can be a code fragment or plain text. The included page will never be compiled as a standalone. The included page can also have any extension, though .jspf has become a conventionally used extension.
One drawback on older containers is that changes to the include pages may not take effect until the parent page is updated. Recent versions of Tomcat will check the include pages for updates and force a recompile of the parent if they're updated.
A further drawback is that since the code is inlined directly into the service method of the generated servlet, the method can grow very large. If it exceeds 64 KB, your JSP compilation will likely fail.
<jsp:include> - The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.
Each included page is executed as a separate servlet at run time.
Pages can conditionally be included at run time. This is often useful for templating frameworks that build pages out of includes. The parent page can determine which page, if any, to include according to some run-time condition.
The values of scriptlet variables need to be explicitly passed to the include page.
The included page must be able to be run on its own.
You are less likely to run into compilation errors due to the maximum method size being exceeded in the generated servlet class.
Depending on your needs, you may either use <#include> or
<jsp:include>
Main advantage of <jsp:include /> over <%# include > is:
<jsp:include /> allows to pass parameters
<jsp:include page="inclusion.jsp">
<jsp:param name="menu" value="objectValue"/>
</jsp:include>
which is not possible in <%#include file="somefile.jsp" %>
All three template options - <%#include>, <jsp:include> and <%#tag> are valid, and all three cover different use cases.
With <#include>, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.
<jsp:include> (and JSTL's <c:import>, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import> also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".
Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%#tag attribute> and these arguments can be either mandatory or optional - somewhat like method parameters.
Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.
According to:
Java Revisited
Resources included by include directive are loaded during jsp translation time, while resources included by include action are loaded during request time.
Any change on included resources will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in the next request.
Include directive is static import, while include action is dynamic import.
Include directive uses file attribute to specify resources to be included while include action uses page attribute for the same purpose.
In the JSP Spec 2.1, I found an example about the JSP include directive and JSP include tag:
For an example of a more complex set of inclusions, consider the following
four situations built using four JSP files: A.jsp, C.jsp, dir/B.jsp and dir/C.jsp :
I don't quite understand this, especially the first and last situation, why the C.jsp are not resolved to C.jsp in the first situation? and why the c.jsp are not resolved to dir/c.jsp in the last situation?
include directive
Use this directive to specify a resource that contains text or code to be inserted into the JSP page when it is translated.
For example:
<%# include file="/jsp/userinfopage.jsp" %>
Specify either a page-relative or context-relative path to the resource.
See Requesting a JSP Page for discussion of page-relative and context-relative paths.
Notes:
The include directive, referred to as a static include, is comparable in nature to the jsp:include action discussed later in this chapter, but jsp:include takes effect at request-time instead of translation-time. See Static Includes Versus Dynamic Includes.
The include directive can be used only between files in the same servlet context (application).
In a JSP include directive the path can be relative to the including page or absolute (then it has to start with a / and belongs to the web application root directory).
For more info have a look at another post here
Please have a look at Including Content in a JSP Page
The directive <%# include> fills in the text of an evaluation of the included JSP with the <%#> directives evaluated. As such the nested include is evaluated with respect to directory of the included JSP.
The tag <jsp:include> calls a compiled version of the included jsp.
So a single JSP is evaluated for text on its own, triggering the evaluation on includes first. Now it should be clear.
First case:
evaluate directives - A.jsp, include dir/B.jsp
evaluate directives - dir/B.jsp, ... include C.jsp = dir/C.jsp
generate java for A.jsp, with text of dir/B.jsp with text from dir/C.jsp.
<%# include file= ... > is executed while the page is translated into a servlet class. Thus, it knows the context of the file system. This is also called static inclusion, and the tag is a direction.
<jsp:include page= ...> is executed while the page is executed for a request. This is also called dynamic include, and the tag is an action. Here, the context of the file system is unknown.
Static inclusion means that a chunk of code lines is copied into the resulting final file. Dynamic inclusion means that the included page is executed, and the result is copied into the resulting final file.
Here are good sources:
http://docs.oracle.com/javaee/1.3/tutorial/doc/JSPIntro8.html
http://www.albeesonline.com/blog/2008/05/22/difference-between-static-include-and-dynamic-include-in-jsp/
http://www.coderanch.com/how-to/java/IncludesActionDirective
It seems that there are two methods for templating with JSP. Including files with one of these statements
<%# include file="foo.html" %>
<jsp:include page="foo.html" />
or using JSP tag files
// Save this as mytag.tag
<%# tag description="Description" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<jsp:doBody/>
</body>
</html>
And in another JSP page call it with
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:mytag>
<h1>Hello World</h1>
</t:mytag>
So which method should I use? Is one now considered deprecated or are they both valid and cover different use cases?
Edit
Isn't using this tag file the same as using an include?
// Save this as product.tag
<%# tag description="Product templage" pageEncoding="UTF-8"%>
<%# tag import="com.myapp.Product" %>
<%# attribute name="product" required="true" type="com.myapp.Product"%>
Product name: ${product.name} <br/>
Quantity: ${product.quantity} <br/>
And call it on another JSP with
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:product>
<c:forEach items="${cart.products}" var="product">
<t:product product="${product}"/>
</c:forEach>
</t:product>
That seems to me to be the very same as using an include and passing parameters to it. So are Tag Files the same as includes?
Overview of JSP Syntax Elements
First, to make things more clear, here is a short overview of JSP syntax elements:
Directives: These convey information regarding the JSP page as a
whole.
Scripting elements: These are Java coding elements such as
declarations, expressions, scriptlets, and comments.
Objects and scopes: JSP objects can be created either explicitly or
implicitly and are accessible within a given scope, such as from
anywhere in the JSP page or the session.
Actions: These create objects or affect the output stream in the JSP
response (or both).
How content is included in JSP
There are several mechanisms for reusing content in a JSP file.
The following 4 mechanisms to include content in JSP can be categorized as direct reuse:
(for the first 3 mechanisms quoting from "Head First Servlets and JSP")
1) The include directive:
<%# include file="header.html" %>
Static: adds the content from the value of the file attribute to the current page at translation time. The directive was
originally intended for static layout templates, like HTML headers.
2) The <jsp:include> standard action:
<jsp:include page="header.jsp" />
Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic
content coming from JSPs.
3) The <c:import> JSTL tag:
<c:import url=”http://www.example.com/foo/bar.html” />
Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like
<jsp:include>, but it’s more powerful and flexible: unlike the
other two includes, the <c:import> URL can be from outside the
web Container!
4) Preludes and codas:
Static: preludes and codas can be applied only to the beginnings and ends of pages.
You can implicitly include preludes (also called headers) and codas
(also called footers) for a group of JSP pages by adding
<include-prelude> and <include-coda> elements respectively within
a <jsp-property-group> element in the Web application web.xml deployment descriptor.
Read more here:
• Configuring Implicit Includes at the Beginning and End of JSPs
• Defining implicit includes
Tag File is an indirect method of content reuse, the way of encapsulating reusable content.
A Tag File is a source file that contains a fragment of JSP code that is reusable as a custom tag.
The PURPOSE of includes and Tag Files is different.
Tag file (a concept introduced with JSP 2.0) is one of the options for creating custom tags. It's a faster and easier way to build custom tags.
Custom tags, also known as tag extensions, are JSP elements that allow custom logic and output provided by other Java components to be inserted into JSP pages. The logic provided through a custom tag is implemented by a Java object known as a tag handler.
Some examples of tasks that can be performed by custom tags include operating on implicit objects, processing forms, accessing databases and other enterprise services such as email and directories, and implementing flow control.
Regarding your Edit
Maybe in your example (in your "Edit" paragraph), there is no difference between using direct include and a Tag File. But custom tags have a rich set of features. They can
Be customized by means of attributes passed from the calling page.
Pass variables back to the calling page.
Access all the objects available to JSP pages.
Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag.
Be nested within one another and communicate by means of private variables.
Also read this from "Pro JSP 2": Understanding JSP Custom Tags.
Useful reading.
Difference between include directive and include action in
JSP
JSP tricks to make templating
easier
Very informative and easy to understand tutorial from coreservlet.com with beautiful
explanations that include <jsp:include> VS. <%# include %>
comparison table:
Including Files and Applets in JSP
Pages
Another nice tutorial from coreservlets.com related to tag libraries and
tag files:
Creating Custom JSP Tag Libraries: The
Basics
The official Java EE 5 Tutorial with examples:
Encapsulating Reusable Content
Using Tag
Files.
This page from the official Java EE 5 tutorial should give you even
more understanding:
Reusing Content in JSP
Pages.
This excerpt from the book "Pro JSP 2" also discuses why do you need
a Tag File instead of using static include:
Reusing Content with Tag
Files
Very useful guide right from the Oracle documentation:
Static Includes Versus Dynamic Includes
Conclusion
Use the right tools for each task.
Use Tag Files as a quick and easy way of creating custom tags that can help you encapsulate reusable content.
As for the including content in JSP (quote from here):
Use the include directive if the file changes rarely. It’s the fastest mechanism. If your container doesn’t automatically detect changes, you can force the changes to take effect by deleting the main page class file.
Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.
Possible Duplicate Question
<#include> - The directive tag instructs the JSP compiler to merge contents of the included file into the JSP before creating the generated servlet code. It is the equivalent to cutting and pasting the text from your include page right into your JSP.
Only one servlet is executed at run time.
Scriptlet variables declared in the parent page can be accessed in the included page (remember, they are the same page).
The included page does not need to able to be compiled as a standalone JSP. It can be a code fragment or plain text. The included page will never be compiled as a standalone. The included page can also have any extension, though .jspf has become a conventionally used extension.
One drawback on older containers is that changes to the include pages may not take effect until the parent page is updated. Recent versions of Tomcat will check the include pages for updates and force a recompile of the parent if they're updated.
A further drawback is that since the code is inlined directly into the service method of the generated servlet, the method can grow very large. If it exceeds 64 KB, your JSP compilation will likely fail.
<jsp:include> - The JSP Action tag on the other hand instructs the container to pause the execution of this page, go run the included page, and merge the output from that page into the output from this page.
Each included page is executed as a separate servlet at run time.
Pages can conditionally be included at run time. This is often useful for templating frameworks that build pages out of includes. The parent page can determine which page, if any, to include according to some run-time condition.
The values of scriptlet variables need to be explicitly passed to the include page.
The included page must be able to be run on its own.
You are less likely to run into compilation errors due to the maximum method size being exceeded in the generated servlet class.
Depending on your needs, you may either use <#include> or
<jsp:include>
Main advantage of <jsp:include /> over <%# include > is:
<jsp:include /> allows to pass parameters
<jsp:include page="inclusion.jsp">
<jsp:param name="menu" value="objectValue"/>
</jsp:include>
which is not possible in <%#include file="somefile.jsp" %>
All three template options - <%#include>, <jsp:include> and <%#tag> are valid, and all three cover different use cases.
With <#include>, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.
<jsp:include> (and JSTL's <c:import>, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import> also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".
Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%#tag attribute> and these arguments can be either mandatory or optional - somewhat like method parameters.
Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.
According to:
Java Revisited
Resources included by include directive are loaded during jsp translation time, while resources included by include action are loaded during request time.
Any change on included resources will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in the next request.
Include directive is static import, while include action is dynamic import.
Include directive uses file attribute to specify resources to be included while include action uses page attribute for the same purpose.
I have a web app, where I have different navigation anchor tags such as Home, Profile and etc.
What I want:
When I press anchor tags like home or profile. I just want to ensure that current user gets its information in that Tags/JSP Page.
Sample Example that I am trying:
Profile
The pageContext is an implicit object available in JSPs. The EL documentation says
The context for the JSP page. Provides access to various objects including:
servletContext: ...
session: ...
request: ...
response: ...
Thus this expression will get the current HttpServletRequest object and get the context path for the current request and append /JSPAddress.jsp to it to create a link (that will work even if the context-path this resource is accessed at changes).
The primary purpose of this expression would be to keep your links 'relative' to the application context and insulate them from changes to the application path.
For example, if your JSP (named thisJSP.jsp) is accessed at http://myhost.com/myWebApp/thisJSP.jsp, thecontext path will be myWebApp. Thus, the link href generated will be /myWebApp/JSPAddress.jsp.
If someday, you decide to deploy the JSP on another server with the context-path of corpWebApp, the href generated for the link will automatically change to /corpWebApp/JSPAddress.jsp without any work on your part.
Include <%# page isELIgnored="false"%> on top of your jsp page.
use request.getContextPath() instead of ${pageContext.request.contextPath} in JSP expression language.
<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);
output: willPrintMyProjectcontextPath
For my project's setup, "${pageContext.request.contextPath}"= refers to "src/main/webapp". Another way to tell is by right clicking on your project in Eclipse and then going to Properties: