JavaServer Pages (JSP) is a server-side technology used for creating dynamic web pages in Java-based web applications. It allows developers to embed Java code into HTML and generate dynamic content at runtime. JSP is part of Java EE (Jakarta EE) and is built on top of Servlets, making it an extension of the Java Servlet technology.

Key Features

  • Dynamic HTML content generation using Java code.
  • Separation of presentation & logic with JavaBeans and MVC pattern.
  • Reusable components using JSP tags and JavaBeans.
  • Integration with Servlets for advanced web applications.
  • Session management, form handling, and database connectivity.

Example Syntax:

<%@ page language="java" contentType="text/html" %>
<html>
  <body>
    <h1>Welcome to JSP!</h1>
    <p>The current time is: <%= new java.util.Date() %></p>
  </body>
</html>

<%= expression %> inserts dynamic content into HTML.

Elements & Syntax

JSP ElementDescriptionExample
DirectivesProvide instructions to the JSP engine.<%@ page language="java" contentType="text/html" %>
DeclarationsDeclare variables & methods in Java.<%! int count = 0; %>
ScriptletsJava code inside JSP.<% out.println("Hello, JSP!"); %>
ExpressionsInsert dynamic values.<%= new java.util.Date() %>
CommentsAdd server-side comments.<%-- This is a JSP comment --%>
Implicit ObjectsPredefined objects like request, response, session, etc.<%= request.getParameter("name") %>

JSP Implicit Objects

JSP provides built-in objects for handling requests, responses, and session management.

ObjectDescription
requestHolds HTTP request data (parameters, headers).
responseSends response data to the client.
sessionStores user session data.
applicationStores application-wide data.
outWrites content to the response.
configRetrieves JSP configuration settings.
pageContextProvides information about the page execution.
exceptionCaptures exceptions (used in error pages).

JSP with JavaBeans Example

JavaBean Class (User.java)

package com.example;
 
public class User {
    private String name;
    
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

JSP Page (user.jsp)

<jsp:useBean id="user" class="com.example.User" />
<jsp:setProperty name="user" property="name" value="Alice"/>
<p>Welcome, <jsp:getProperty name="user" property="name"/>!</p>

Uses JavaBean to separate business logic from JSP presentation.

JSP in MVC Architecture

JSP is often used in Model-View-Controller (MVC) pattern:

Example MVC Flow:

  1. User requests login.jsp(View)
  2. Servlet LoginServlet.java processes login → (Controller)
  3. JavaBean User.java handles user data → (Model)
  4. Response sent back to dashboard.jsp