JSP Basics and Scriptlets
JSP Basics and Scriptlets
Writing HTML inside Java strings is painful. JSP (JavaServer Pages) solves this by letting you write HTML with embedded Java expressions. The container compiles JSP into a servlet behind the scenes.
Your First JSP Page
A JSP file lives in webapp/ and has a .jsp extension. You can mix HTML and Java directly:
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head><title>Welcome</title></head>
<body>
<h1>Hello, <%= request.getParameter("name") %>!</h1>
</body>
</html>
Scriptlet Tags
Scriptlets let you embed Java code blocks inside JSP:
<%
List<String> fruits = List.of("Apple", "Banana", "Cherry");
for (String fruit : fruits) {
%>
<p>I like <%= fruit %></p>
<%
}
%>
Expression tags <%= expr %> output the value of a Java expression. Scriptlet tags <% code %> run arbitrary Java code. Avoid scriptlets in production - they mix logic and presentation and are hard to maintain.
JSP Expression Language
Expression Language (EL) is the preferred way to access data in JSP. It is cleaner and safer than scriptlets:
<p>User: ${sessionScope.user.name}</p>
<p>Cart items: ${sessionScope.cart.itemCount}</p>
<p>Default: ${missingValue "fallback"}</p>
EL reads from page, request, session, and application scopes automatically. Use the scope prefix to be explicit: ${requestScope.key}, ${sessionScope.key}.
JSP vs Servlets
Use servlets for logic (validation, business rules, routing). Use JSP for presentation (HTML output). This separation is the core of the MVC pattern that underpins most Java web frameworks.
Key Points
- JSP files are compiled into servlets by the container.
- Scriptlets
<% %>embed Java code; expressions<%= %>output values. - Expression Language
${...}is cleaner and preferred over scriptlets. - JSP is for presentation; servlets are for logic.
- Always separate concerns following the MVC pattern.