Tuesday, August 12, 2014

Re-usability of JSP



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.

  1. Static
  2. Dynamic

    Static include



    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.

    Dynamic include



    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 include

    This can be done as follows. You can include files using following methods.


       <%
           RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp");
           dispatcher.include(request, response);
       %>
    
    

    Method 2
       
       <%
           pageContext.include("newPage.jsp");
       %>
    
    

    Method 3

        <jsp:forward page="newPage.jsp" flush="true"/>
    
    


    Using forward

    There are three ways to perform this task.

    Method 1

       <%
           RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp");
           dispatcher.forward(request, response);
       %>
    
    

    Method 2
       
       <%
           pageContext.forward("newPage.jsp");
       %>
    
    

    Method 3

        <jsp:forward page="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.