JSP in Java
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.
| Step | When | What happens |
|---|---|---|
| Translation | First request (or after the file changes) | hello.jsp becomes the Java source hello_jsp.java |
| Compilation | Right after translation | The source is compiled to hello_jsp.class, a servlet |
| Execution | Every request | The generated servlet's _jspService method writes the HTML |
| Servlet | JSP | |
|---|---|---|
| Written as | Java class with HTML in strings | HTML page with Java data in tags |
| Best for | Request handling, logic, APIs | Displaying HTML |
| Changes need | Rebuild and redeploy | Save 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-INFis 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
pagedirective sets the content type and encoding, exactly likeresponse.setContentTypein 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.
| Element | Syntax | Becomes 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
forloop wraps plain HTML, so the<li>line repeats for each topic. pageViewsis 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 operator | Example | Result |
|---|---|---|
| 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.lengthworks 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.
divalways produces a decimal result, so the average is81.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 equivalent | Holds |
|---|---|---|
request | requestScope, param, header, cookie | The current HttpServletRequest |
response | — | The current HttpServletResponse |
session | sessionScope | The user's HttpSession |
application | applicationScope, initParam | The shared ServletContext |
out | — | The JspWriter that writes the page |
pageContext | pageContext, pageScope | Access to everything above |
config | — | The page's ServletConfig |
exception | pageContext.exception | The 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.requestgives EL access to the full request object, including methods such asgetContextPath().header['User-Agent']uses brackets because the name contains a hyphen, which is not allowed after a dot.cookie.themeis aCookieobject, so.valuecallsgetValue().- 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.
| Directive | Example | Purpose |
|---|---|---|
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 intoabout.jspbefore 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
.jspfextension 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.
| Scope | EL map | Lives for | Set with |
|---|---|---|---|
| Page | pageScope | One JSP page | pageContext.setAttribute |
| Request | requestScope | One request, including forwards | request.setAttribute |
| Session | sessionScope | One user, across requests | session.setAttribute |
| Application | applicationScope | The whole app, all users | application.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. UserequestScope.labeland 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 underWEB-INFare 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:
- Controller.
CourseDetailServletreads the course code from the path, rejects unknown codes with404, and stores the record and flags as request attributes. - Records in EL.
${course.title}calls the record accessortitle(). Tomcat 11's Expression Language resolves records automatically, andcourse.modules.size()calls a method on the list. - Reusable layout. The static include pastes the shared header, which reads the
pageTitleattribute set by the servlet. - Safe links.
pageContext.request.contextPathbuilds a link that works under any deployment name, and₹renders the rupee sign in the browser. - Error handling. If the view throws an exception,
errorPagesends the user to the friendlyerror.jspinstead of a stack trace. To loop over every module and escape values safely, continue with JSTL in JSP.