Define JSP. Explain the different types of JSP tags by taking suitable example.

Definition of JSP:

JSP (JavaServer Pages) is a server-side technology used to create dynamic, platform-independent web content. It allows embedding Java code directly into HTML pages using special JSP tags. JSP files are compiled into servlets by the server and executed to generate dynamic web pages, typically as part of Java EE (Jakarta EE) applications.


Types of JSP Tags

JSP provides several types of tags, categorized into the following:


1. Directive Tags

These provide global information to the JSP engine and affect the overall structure of the JSP page.

Syntax:

<%@ directive attribute="value" %>

Types of Directive Tags:

  • <%@ page %> – Defines page-dependent attributes like contentType, language, import, etc. Example: <%@ page language="java" contentType="text/html" %> <%@ page import="java.util.Date" %>
  • <%@ include %> – Includes a static file during the translation phase. Example: <%@ include file="header.jsp" %>
  • <%@ taglib %> – Declares a tag library (used in JSTL). Example: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

2. Declaration Tags

Used to declare variables and methods that are inserted into the servlet’s class (outside methods).

Syntax:

<%! declaration %>

Example:

<%! int counter = 0; %>
<%! public int getCounter() { return ++counter; } %>

3. Scriptlet Tags

Used to write Java code inside the JSP page. Code is inserted into the _jspService() method.

Syntax:

<% code %>

Example:

<%
  int x = 10;
  out.println("Value of x: " + x);
%>

4. Expression Tags

Used to output Java values directly to the client. The value is automatically printed to the response.

Syntax:

<%= expression %>

Example:

<%= new java.util.Date() %>

5. Action Tags

Used to control the behavior of the JSP engine. These are XML-based tags for JSP-specific actions.

Common Action Tags:

  • <jsp:include> – Includes another JSP or resource at request time. Example: <jsp:include page="footer.jsp" />
  • <jsp:forward> – Forwards the request to another resource. Example: <jsp:forward page="home.jsp" />
  • <jsp:useBean> – Instantiates a JavaBean. Example: <jsp:useBean id="user" class="com.example.User" scope="session" /> <jsp:setProperty name="user" property="name" value="Kushal" /> <jsp:getProperty name="user" property="name" />

Summary Table

Tag TypeSyntax ExamplePurpose
Directive<%@ page import="java.util.*" %>Set global page info
Declaration<%! int x = 0; %>Declare variables/methods
Scriptlet<% out.println(x); %>Java logic inside JSP
Expression<%= new Date() %>Output Java expressions
Action<jsp:include page="file.jsp" />Include, forward, use beans, etc.

Leave a Reply

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