JSP include directive

In this post, you will learn:

  • What is the use of include directive in JSP?
  • What are the differences between include directive and action?

JSP include directive?

include directive in JSP, is used by application programmers to get the contents of a page included to the current JSP at the time of translation.

It has following syntax:

<%@ include file=”url of the component to be included” %>

You may recall that <jsp:include …/> action also has the same functionality. Now you should be wondering why are both the action & directive, provided to perform the same task?

Differences between the include directive & action:

1. In case of include action, contents of the specified page are included at the time of request processing where as in case of include directive, contents are included at the time of translation.

2. Include directive provides better performance than the action because inclusion is done only once at the time of translation. Include action provides more flexibility than the directive, as different contents can be included to the response of different requests.

3. Include directive should be used when static contents are to be included and include action should be used when dynamic contents are to be included.

Following diagram describes, how include action & directives are translated to the auto generated servlet.

include_directive

Practical example of the include directive:

First, the index.html :

<form method="post" action="adder.jsp">
First No: <input type="text" name="num1"><br/>
Second No: <input type="text" name="num2"><br/>
<input type="submit" value="add">
</form>

Second, the adder.jsp which uses the include directive to include the contents of index.html to facilitate the addition of another number:

<%
int a=Integer.parseInt(request.getParameter("num1"));
int b=Integer.parseInt(request.getParameter("num2"));
int c=a+b;
out.println("sum is: "+c);
%>
<hr/>
<%@ include file="index.html" %>

Its time to recap the main concepts:

  1. include directive is used to include the static contents to the response of a JSP.
  2. include action is used to include the dynamic contents to the response of a JSP.
  3. Any number of include directives can be used in a JSP.
  4. In case of directive, inclusion is done at the time of translation and in case of action, inclusion is done at the time of request processing.
If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *