June 26, 2011

The include directive, JSP include action and JSP forward action

JSP Include Directive

The JSP include directive allows including another, outside JSP file (containing text or code) into a JSP. This allows creating modular pages and avoid duplication of content across JSPs. The insertion of the outside JSP content is done during the translation of the JSP to a Java class by the Container.

1) Create a JSP - includeDirectiveTest.jsp - in the WebContent folder of the web application

<html>
<body>

<%@ include file="header.jsp"  %>

This is the body<br/>

<%@ include file="footer.jsp"  %>

</body>
</html>

2) Create 2 JSPs - header.jsp & footer.jsp - also in the WebContent folder of the web application

header.jsp
This is the header<br/>

footer.jsp
This is the footer<br/>

3) Test the code with the following URL in the browser:

http://localhost:8080/WebAppName/includeDirectiveTest.jsp

JSP Include Action

The JSP include action works similar to the include directive with a fundamental difference - instead of inserting the contents of the included outside JSP into the including JSP (at translation time), the JSP include action inserts the response from the included JSP at runtime.

1) Create a new JSP - includeActionTest.jsp - in the WebContent folder of the web application

<html>
<body>
<jsp:include page="header.jsp" />

This is the body<br/>

<jsp:include page="footer.jsp" />

</body>
</html>

2) Test the code with the following URL in the browser:

http://localhost:8080/WebAppName/includeActionTest.jsp


JSP Forward Action

The JSP forward action forwards the request from one JSP page to another.

Similar to the JSP include action, the JSP forward action creates a RequestDispatcher with the page attribute value as an argument to the RequestDispatcher and then invokes the forward() method on the RequestDispatcher.

1) Create a JSP - forwardActionTest.jsp - in the WebContent folder of the web application

<html>
<body>
<jsp:forward page="anotherJsp.jsp" />

</body>
</html>

2) Test the code with the following URL in the browser:

http://localhost:8080/WebAppName/forwardActionTest.jsp

Accessing the forwardActionTest.jsp will cause anotherJsp.jsp to be rendered in the browser.

No comments:

Post a Comment