JSP in Java

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 272 of 306

JSP in Java (JavaServer Pages, now officially Jakarta Pages) lets you write HTML pages with small pieces of Java data mixed in. The server turns each .jsp file into a servlet the first time it is requested, so you get servlet power with HTML that is easy to read and edit. JSP is used for the view layer: servlets prepare data, and JSP pages display it.

This lesson covers how JSP works, the Expression Language, implicit objects, directives, scopes and the servlet-plus-JSP (MVC) pattern. The examples run on Tomcat 11 (Jakarta Pages 4.0) in the student-portal app from Java Servlet Basics.


How JSP Works in Java

A JSP file lives in src/main/webapp, next to your static files. Tomcat's JSP engine (Jasper) handles it in three steps.

StepWhenWhat happens
TranslationFirst request (or after the file changes)hello.jsp becomes the Java source hello_jsp.java
CompilationRight after translationThe source is compiled to hello_jsp.class, a servlet
ExecutionEvery requestThe generated servlet's _jspService method writes the HTML
ServletJSP
Written asJava class with HTML in stringsHTML page with Java data in tags
Best forRequest handling, logic, APIsDisplaying HTML
Changes needRebuild and redeploySave the file (Tomcat recompiles it)
student-portal/
└── src/main/webapp/
    ├── hello.jsp                  <- public: /student-portal/hello.jsp
    └── WEB-INF/
        ├── web.xml
        └── views/
            └── course.jsp         <- private: reachable only through a forward

How it works:

  • Everything inside WEB-INF is hidden from browsers. Put JSP views there so users must go through your servlet, which prepares the data first.
  • The generated Java files appear under Tomcat's work/Catalina/localhost/student-portal/org/apache/jsp/ folder, which is useful when you want to see what a JSP really does.

Your First JSP Page

Create src/main/webapp/hello.jsp:

<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<!DOCTYPE html>
<html>
<head><title>Hello JSP</title></head>
<body>
  <h1>Hello from JSP</h1>
  <p>Server time: <%= java.time.LocalTime.now().withNano(0) %></p>
  <p>2 + 3 = ${2 + 3}</p>
</body>
</html>
curl http://localhost:8080/student-portal/hello.jsp

Output:

<!DOCTYPE html>
<html>
<head><title>Hello JSP</title></head>
<body>
  <h1>Hello from JSP</h1>
  <p>Server time: 11:00:42</p>
  <p>2 + 3 = 5</p>
</body>
</html>

How it works:

  • The page directive sets the content type and encoding, exactly like response.setContentType in a servlet.
  • trimDirectiveWhitespaces="true" removes the blank line the directive would otherwise leave at the top of the output.
  • <%= ... %> runs a Java expression and prints the result. ${2 + 3} does the same with the Expression Language, which is shorter and preferred.
  • The first request is slower because Tomcat translates and compiles the page; later requests run the compiled servlet directly.

JSP Scripting Elements: Expressions, Scriptlets and Declarations

JSP has three ways to embed raw Java. They are worth knowing because you will meet them in older projects.

ElementSyntaxBecomes in the generated servlet
Expression<%= value %>out.print(value);
Scriptlet<% statements %>Code inside _jspService
Declaration<%! field or method %>A field or method of the servlet class
Comment<%-- text --%>Nothing (not sent to the browser)
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%! private int pageViews = 0; %>
<%
    pageViews++;
    String[] topics = {"Servlets", "JSP", "JSTL"};
%>
<%-- This comment never reaches the browser --%>
<h2>Web topics</h2>
<ul>
<% for (String topic : topics) { %>
  <li><%= topic %></li>
<% } %>
</ul>
<p>Page views since startup: <%= pageViews %></p>
curl http://localhost:8080/student-portal/scripting.jsp

Output:

<h2>Web topics</h2>
<ul>
  <li>Servlets</li>
  <li>JSP</li>
  <li>JSTL</li>
</ul>
<p>Page views since startup: 1</p>

How it works:

  • The scriptlet's for loop wraps plain HTML, so the <li> line repeats for each topic.
  • pageViews is a field of the one shared servlet instance, so every user and every thread updates it. That makes it unsafe without synchronization, as explained in Servlet Lifecycle in Java.

Note: Modern JSP pages avoid scriptlets. Use the Expression Language for values and JSTL tags for loops and conditions. Logic belongs in servlets or service classes.


Expression Language (EL) in JSP

The Expression Language reads data with ${...}. It looks up attributes by name, calls getters and record accessors, and handles null quietly by printing nothing.

EL operatorExampleResult
Arithmetic${10 div 4}, ${10 mod 3}2.5, 1
Comparison${5 gt 3}, ${marks >= 75}true / false
Logical${a and b}, ${not empty name}true / false
Empty check${empty list}true for null, "" or an empty collection
Conditional${marks >= 40 ? 'Pass' : 'Fail'}Pass
Property${student.name}Calls getName() or name()
Index / key${scores[0]}, ${fees['java']}Element or map value
String join${first += ' ' += last}Concatenated text
<%@ page contentType="text/plain;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%
    // Normally a servlet sets these; scriptlets are used here only to keep the demo in one file
    request.setAttribute("marks", 82);
    request.setAttribute("scores", new int[]{70, 82, 91});
    request.setAttribute("fees", java.util.Map.of("java", 4999, "go", 2999));
    request.setAttribute("emptyList", java.util.List.of());
%>
marks = ${marks}
grade = ${marks >= 90 ? 'A' : marks >= 75 ? 'B' : 'C'}
second score = ${scores[1]}, scores count = ${scores.length}
java fee = ${fees['java']}, go fee = ${fees.go}
average = ${(70 + 82 + 91) div 3}
emptyList empty? ${empty emptyList}
missing attribute = [${noSuchThing}]
course param = ${param.course}
curl "http://localhost:8080/student-portal/el-demo.jsp?course=java"

Output:

marks = 82
grade = B
second score = 82, scores count = 3
java fee = 4999, go fee = 2999
average = 81.0
emptyList empty? true
missing attribute = []
course param = java

How it works:

  • ${marks} searches the page, request, session and application scopes in that order and prints the first match.
  • scores.length works on arrays from Expression Language 6.0 (Tomcat 11) onward.
  • A missing attribute prints an empty string instead of throwing an exception, so a typo shows up as a blank, not an error.
  • div always produces a decimal result, so the average is 81.0.

JSP Implicit Objects

JSP pages get ready-made variables without declaring them. Scriptlets use the Java objects; EL has its own matching names.

Java object (scriptlets)EL equivalentHolds
requestrequestScope, param, header, cookieThe current HttpServletRequest
response—The current HttpServletResponse
sessionsessionScopeThe user's HttpSession
applicationapplicationScope, initParamThe shared ServletContext
out—The JspWriter that writes the page
pageContextpageContext, pageScopeAccess to everything above
config—The page's ServletConfig
exceptionpageContext.exceptionThe error, on error pages only
<%@ page contentType="text/plain;charset=UTF-8" trimDirectiveWhitespaces="true" %>
Method: ${pageContext.request.method}
Context path: ${pageContext.request.contextPath}
User-Agent: ${header['User-Agent']}
Theme cookie: ${cookie.theme.value}
Tags: ${paramValues.tag[0]} and ${paramValues.tag[1]}
Session id length: ${pageContext.session.id.length()}
curl -b "theme=dark" "http://localhost:8080/student-portal/implicit.jsp?tag=java&tag=web"

Output:

Method: GET
Context path: /student-portal
User-Agent: curl/8.5.0
Theme cookie: dark
Tags: java and web
Session id length: 32

How it works:

  • pageContext.request gives EL access to the full request object, including methods such as getContextPath().
  • header['User-Agent'] uses brackets because the name contains a hyphen, which is not allowed after a dot.
  • cookie.theme is a Cookie object, so .value calls getValue().
  • EL can call methods directly, as id.length() shows.

JSP Directives: page, include and taglib

Directives give instructions to the JSP translator. They run once, when the page is translated.

DirectiveExamplePurpose
page<%@ page contentType="..." import="java.util.*" errorPage="/error.jsp" %>Page settings and imports
include<%@ include file="/WEB-INF/fragments/header.jspf" %>Copy a file in at translation time
taglib<%@ taglib prefix="c" uri="jakarta.tags.core" %>Enable a tag library such as JSTL

Shared header and footer fragments keep every page consistent.

<%-- /WEB-INF/fragments/header.jspf --%>
<header><strong>GOCOURSE Student Portal</strong> | ${pageTitle}</header>
<%-- /WEB-INF/fragments/footer.jspf --%>
<footer>© 2026 GOCOURSE</footer>
<%-- src/main/webapp/about.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<% request.setAttribute("pageTitle", "About"); %>
<%@ include file="/WEB-INF/fragments/header.jspf" %>
<main>Free courses and internships for every learner.</main>
<jsp:include page="/WEB-INF/fragments/footer.jspf" />
curl http://localhost:8080/student-portal/about.jsp

Output:

<header><strong>GOCOURSE Student Portal</strong> | About</header>
<main>Free courses and internships for every learner.</main>
<footer>© 2026 GOCOURSE</footer>

How it works:

  • <%@ include %> is static: the header text is pasted into about.jsp before compiling, so it can use the page's variables.
  • <jsp:include> is dynamic: the footer runs as a separate request at runtime and its output is inserted. Use it for fragments that change independently.
  • The .jspf extension marks fragments that are not meant to be requested on their own.

Attribute Scopes in JSP

Attributes can live in four scopes. EL searches them from the smallest to the largest.

ScopeEL mapLives forSet with
PagepageScopeOne JSP pagepageContext.setAttribute
RequestrequestScopeOne request, including forwardsrequest.setAttribute
SessionsessionScopeOne user, across requestssession.setAttribute
ApplicationapplicationScopeThe whole app, all usersapplication.setAttribute
<%@ page contentType="text/plain;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<%
    pageContext.setAttribute("label", "page value");
    request.setAttribute("label", "request value");
    session.setAttribute("label", "session value");
    Integer hits = (Integer) application.getAttribute("hits");
    application.setAttribute("hits", hits == null ? 1 : hits + 1);
%>
label (nearest scope) = ${label}
request label = ${requestScope.label}
session label = ${sessionScope.label}
total hits = ${applicationScope.hits}
curl http://localhost:8080/student-portal/scopes.jsp
curl http://localhost:8080/student-portal/scopes.jsp | tail -n 1

Output:

label (nearest scope) = page value
request label = request value
session label = session value
total hits = 1
total hits = 2

How it works:

  • ${label} finds the page-scope value first, because page is the smallest scope. Use requestScope.label and similar names to pick a scope explicitly.
  • The application counter survives across requests from any client, so the second call shows 2.

Servlet and JSP Together: The MVC Pattern

In MVC, the servlet is the controller: it reads the request and loads data. The JSP is the view: it only displays what it receives. The data objects are the model.

// GreetingServlet.java
@WebServlet("/greet")
public class GreetingServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        request.setAttribute("studentName", name == null || name.isBlank() ? "Learner" : name);
        request.setAttribute("courseCount", 3);
        request.getRequestDispatcher("/WEB-INF/views/greet.jsp").forward(request, response);
    }
}
<%-- /WEB-INF/views/greet.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true" %>
<h1>Hello, ${studentName}!</h1>
<p>You have ${courseCount} active ${courseCount == 1 ? 'course' : 'courses'}.</p>
curl "http://localhost:8080/student-portal/greet?name=Ravi"
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/student-portal/WEB-INF/views/greet.jsp

Output:

<h1>Hello, Ravi!</h1>
<p>You have 3 active courses.</p>
404

How it works:

  • The servlet puts data into request attributes and forwards. The browser still sees /greet.
  • Requesting the JSP directly fails with 404, because files under WEB-INF are not public.

Note: EL does not escape HTML. A name like <script>...</script> would be inserted as real markup. Print user input with <c:out value="${studentName}"/> or ${fn:escapeXml(studentName)} from JSTL, covered in the next lesson.


Real-World Example: JSP in Java for a Course Details Page

This feature shows a course page at /course/java. The servlet loads the course, answers 404 for unknown codes, and forwards to a JSP view that uses a shared header, an error page and EL with records.

// Course.java
package com.gocourse.portal;

import java.util.List;

public record Course(String code, String title, String level, int feeInr, List<String> modules) {}
// CourseDetailServlet.java
package com.gocourse.portal;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/course/*")
public class CourseDetailServlet extends HttpServlet {

    private static final Map<String, Course> COURSES = Map.of(
            "java", new Course("java", "Java Programming", "Beginner to Advanced", 4999,
                    List.of("Java Basics", "OOP", "Collections", "Web Development")),
            "go", new Course("go", "Go Language", "Beginner", 2999,
                    List.of("Go Basics", "Goroutines")));

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String code = request.getPathInfo() == null ? "" : request.getPathInfo().substring(1);
        Course course = COURSES.get(code);
        if (course == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Course not found");
            return;
        }
        request.setAttribute("pageTitle", course.title());
        request.setAttribute("course", course);
        request.setAttribute("enrolled", "true".equals(request.getParameter("enrolled")));
        request.getRequestDispatcher("/WEB-INF/views/course.jsp").forward(request, response);
    }
}
<%-- /WEB-INF/views/course.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true"
         errorPage="/WEB-INF/views/error.jsp" %>
<%@ include file="/WEB-INF/fragments/header.jspf" %>
<main>
  <h1>${course.title}</h1>
  <p>Level: ${course.level} | Fee: ₹${course.feeInr}</p>
  <p>${course.modules.size()} modules: ${course.modules[0]} to ${course.modules[course.modules.size() - 1]}</p>
  <p>${enrolled ? 'You are enrolled.' : 'Enroll today and start learning.'}</p>
  <a href="${pageContext.request.contextPath}/enroll?course=${course.code}">Enroll</a>
</main>
<%-- /WEB-INF/views/error.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" isErrorPage="true" trimDirectiveWhitespaces="true" %>
<h1>Something went wrong</h1>
<p>We could not show this page. Please try again later.</p>
curl http://localhost:8080/student-portal/course/java
curl "http://localhost:8080/student-portal/course/go?enrolled=true" | grep enrolled
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/student-portal/course/rust

Output:

<header><strong>GOCOURSE Student Portal</strong> | Java Programming</header>
<main>
  <h1>Java Programming</h1>
  <p>Level: Beginner to Advanced | Fee: ₹4999</p>
  <p>4 modules: Java Basics to Web Development</p>
  <p>Enroll today and start learning.</p>
  <a href="/student-portal/enroll?course=java">Enroll</a>
</main>
  <p>You are enrolled.</p>
404

How it works:

  1. Controller. CourseDetailServlet reads the course code from the path, rejects unknown codes with 404, and stores the record and flags as request attributes.
  2. Records in EL. ${course.title} calls the record accessor title(). Tomcat 11's Expression Language resolves records automatically, and course.modules.size() calls a method on the list.
  3. Reusable layout. The static include pastes the shared header, which reads the pageTitle attribute set by the servlet.
  4. Safe links. pageContext.request.contextPath builds a link that works under any deployment name, and ₹ renders the rupee sign in the browser.
  5. Error handling. If the view throws an exception, errorPage sends the user to the friendly error.jsp instead of a stack trace. To loop over every module and escape values safely, continue with JSTL in JSP.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about JSP in Java and get answers drawn from it.

Signed-in readers only.