Java Lesson 48 – JSP | Dataplexa

JSP (JavaServer Pages)

In the previous lesson, we learned how Servlets handle requests and responses. Servlets are powerful, but writing HTML inside Java code quickly becomes difficult to manage.

This is where JSP (JavaServer Pages) comes in. JSP makes it easier to create dynamic web pages using Java.


What Is JSP?

JSP is a server-side technology that allows you to embed Java code directly inside HTML pages. Instead of generating HTML inside Java classes, JSP lets you write HTML first and add Java logic only where needed.

Behind the scenes, every JSP file is converted into a Servlet by the server. So JSP and Servlets work together.


Why JSP Is Needed

Servlets are excellent for backend logic, but not ideal for page design. JSP solves this problem by separating:

  • Business logic (Servlets)
  • Presentation logic (JSP)

This makes applications easier to read, maintain, and scale.


How JSP Works

The JSP lifecycle looks like this:

  • User requests a JSP page
  • Server converts JSP into a Servlet
  • Servlet executes Java code
  • HTML response is sent to browser

This process happens automatically.


Your First JSP Page

Let us start with a simple JSP example.


<%@ page language="java" contentType="text/html" %>

<html>
<body>

<h2>Welcome to JSP</h2>

<p>This page is generated using JavaServer Pages.</p>

</body>
</html>

JSP Scriptlet

Scriptlets allow you to write Java code inside JSP. They are written using <% %>.


<%
int count = 5;
out.println("Count value is: " + count);
%>

Scriptlets are useful but should be used carefully.


JSP Expressions

JSP expressions display values directly on the page. They use <%= %>.


<p>Current Year: <%= 2025 %></p>

This is commonly used to display dynamic values.


JSP Declarations

Declarations are used to define variables and methods. They use <%! %>.


<%!
int totalUsers = 100;
%>

JSP and Servlets Together

In real applications:

  • Servlets handle business logic
  • JSP handles presentation

Example flow:

  • User submits form
  • Servlet processes data
  • Servlet forwards result to JSP

Forwarding Data from Servlet to JSP


// In Servlet
request.setAttribute("username", "Sreekanth");
request.getRequestDispatcher("welcome.jsp").forward(request, response);

In JSP:


<p>Welcome, <%= request.getAttribute("username") %></p>

Real-World Use Case

JSP is commonly used in:

  • Login dashboards
  • Admin panels
  • Reports and summaries
  • Dynamic web pages

Best Practices

  • Avoid heavy Java logic inside JSP
  • Use JSP mainly for UI
  • Keep business logic in Servlets

Key Takeaways

  • JSP simplifies dynamic web page creation
  • JSP works on top of Servlets
  • Used mainly for presentation

In the next lesson, we will explore Java 8 Features and see how modern Java improves performance and readability.