JSP always make your code easier to handle. If you are familiar with php you can remember there is something that you can include a php page to a another page. Think about a simple html page.
You can divide your php file into few sections like above image. Then you can create separate web pages like header.php, nav.php and footer.php likewise. Then once you need that section, you can include it using php include command.
In JSP there is a mechanism to do that task. JSP can reuse web components. This can be done in two ways.
This is very similar to php include. But in this method you can include any text based file (JSP, HTML, XML or even text file) into your JSP page. The content of another file is included with the current JSP file. In translation it looks like a single servlet. This can be done in two ways as follows.
<%@include file="mango.jsp" %> <jsp:directive.include file="Cherry.jsp"/>
Here is an example to understand about Static include. I have created four files to demonstrate this. You can download NetBeans project file below and try it. Final browser view should be like this.
Download source code
Rules of Static include
- file name attribute cannot be an expression.
- file attribute cannot pass any parameters.
In this way, If you request a JSP page, it sends a request to the object and the output is included in current JSP file. This can be done in two ways using include and forward.
<jsp:include page="url" flush="true" /> <jsp:forward page="url" />
Using includeThis can be done as follows. You can include files using following methods.
<% RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp"); dispatcher.include(request, response); %>
<% pageContext.include("newPage.jsp"); %>
<jsp:forward page="newPage.jsp" flush="true"/>
Using forwardThere are three ways to perform this task.
<% RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp"); dispatcher.forward(request, response); %>
<% pageContext.forward("newPage.jsp"); %>
Here is an example for both Including and forwarding. You can import it and run on NetBeans. Then try to understand what is the different between Static and Dynamic inclusions using the result.