JSP action tags

JSP has come up with a set of standard action tags. The action tags are provided to eliminate java code from the jsp files. The action tags are as follows:
  • include
  • forward
  • useBean
  • setProperty
  • getProperty
The below code is an example of jsp include action tag
<jsp: include page="two.jsp" />
A simple example of include action tag is given below.
File: Two.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Two page</title>
</head>
<body>
This is from Two.jsp
</body>
</html>

File: One.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    
<jsp:include page="Two.jsp"/>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>One page</title>
</head>
<body>
This is from One.jsp
</body>
</html>

Run One.jsp and you get the output as shown below:
Interview Question: What is the difference between include directive and include action action tag?
Answer:
  • When we use jsp:include action tag, two servlets will be generated.
  • Since two servlets are created, include tag may take slightly more amount of time than include directive.
  • If we use include action tag, whenever main jsp file is changed or modified a new servlet will be generated. For include page directive the web container regenerates the servlet when there is a change in the main file.
jsp forward: The forward tag forwards the request to another source. In other words forward action terminates the action of the current page and forwards the request to another resource. Another source can be anything like HTML file, servlet or another JSP file. In the above example in One.jsp instead of "jsp:include" tag replace with the below "forward" tag.
<jsp:forward page="Two.jsp"/>

Then the output will be:
"This is from Two.jsp"

No comments:

Post a Comment