Writing HTML in Java servlets is painful—Java code is mixed with HTML strings. Web designers who don’t know Java need to modify the look-and-feel. How can we separate presentation from business logic?
JSP (JavaServer Pages) is similar to servlets but centered on look-and-feel. JSP scripts are HTML-like with embedded Java code, compiled into servlets. They enable non-Java staff to maintain the UI separately from business logic.
- JSP script: HTML file with embedded Java (scriptlets, expressions, declarations, directives)
- Lifecycle: Translation (JSP → servlet source) → Compilation (servlet source → .class) → init() → service() → destroy()
- Directives:
<%@ page %>(page settings),<%@ include %>(static includes),<%@ taglib %>(custom tags) - Scripting elements:
<%! %>declarations,<% %>scriptlets,<%= %>expressions - EL (Expression Language):
${bean.property}syntax for accessing Java beans without scriptlets - JSTL: Standard tag library (
<c:if>,<c:forEach>,<c:out>) enabling logic without Java code - Implicit objects: request, response, session, application, out, pageContext, config, page, exception
- Compilation: JSP is compiled into a servlet on first access
- Separation: UI in JSP, business logic in EJB/servlets
- J2EE integration: Can call EJB components, use JNDI, etc.
JSP is perfect when you want physically separate, easily maintainable UI code.
- HTML-centric: Looks like HTML with embedded Java
- Compiles to servlet: Under the hood, it’s a servlet
- Lifecycle: Translation → Compilation → init → service → destroy
- Directives: page, include, taglib — control page behavior
- EL (Expression Language): ${} syntax, auto-scoped attribute lookup
- JSTL: Core, formatting, SQL, XML, functions tag libraries
- Implicit objects: 9 pre-defined objects accessible in any JSP
- No compiler needed: At deployment time
- Non-Java friendly: Web designers can maintain JSPs
- Separate maintenance: UI separated from business logic
- J2EE standard: Part of J2EE platform
- Built from: Servlets — JSP compiles to servlets
- Built from: Java Platforms — JSP is part of J2EE
- Builds into: EJB Container — JSP can call EJBs
- Related: JSP — alternative to servlets for presentation
- Contrasts with: Session Bean — JSP is presentation, EJBs are business logic
- Scriptlet pollution: Avoid too much Java in JSP (use JSTL/EL)
- First-access delay: Compilation happens on first access
- Chapter 22: See EJB with JSP examples there
- Modern alternative: Consider Facelets/Thymeleaf in modern apps