Define JSP and explain the following:
i) Tags ii) Variables iii) Objects
Answer:-
What is JSP?
JSP (JavaServer Pages) is a server-side technology used to create dynamic 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 can interact with databases, session objects, and business logic.
i) Tags in JSP
Tags in JSP are special syntactic constructs used to embed Java code, display content, or control behavior. There are several types:
Types of JSP Tags
Tag Type | Syntax | Purpose |
---|---|---|
Directive tag | <%@ ... %> | Gives instructions to the JSP compiler (e.g., imports, page settings) |
Declaration tag | <%! ... %> | Declares variables or methods accessible throughout the JSP page |
Scriptlet tag | <% ... %> | Contains Java code executed during page processing |
Expression tag | <%= ... %> | Outputs the result of a Java expression |
Action tag | <jsp:...> | Predefined tags for standard operations (e.g., <jsp:include> to include another file) |
Example:
<%@ page language="java" %> <%! int counter = 0; %> <% counter++; %> <p>Page visited <%= counter %> times.</p>
ii) Variables in JSP
Variables in JSP are used to store data temporarily during page processing. They can be:
Types of Variables:
Type | Scope | Declared In |
---|---|---|
Local variables | Inside methods or scriptlets | <% int x = 10; %> |
Instance variables | In declaration tag | <%! int count = 0; %> |
Implicit variables | Automatically provided by JSP engine | e.g., request , response |
Example:
<%! int visits = 0; %> <% visits++; %> <p>Total visits: <%= visits %></p>
iii) Objects in JSP
JSP provides several implicit objects that you can use directly without declaring them. These objects provide access to request data, response control, session management, and more.
Common Implicit Objects
Object | Description |
---|---|
request | Represents the HTTP request |
response | Represents the HTTP response |
out | Sends output to the client |
session | Manages user session data |
application | Shares data across the whole application |
config | Servlet configuration |
pageContext | Accesses page-level data |
page | Refers to the current JSP page (like this in Java) |
exception | Available in error pages only |
Example:
<p>Hello <%= request.getParameter("name") %></p>
If URL is hello.jsp?name=Kushal
, the output will be:
Hello Kushal
Summary
Concept | Description |
---|---|
Tags | Used to embed Java code and control JSP behavior |
Variables | Store data temporarily within the page |
Objects | Built-in references to request, response, session, etc. |