JSP (Java Server Pages) is a server-side technology that enables developers to create dynamic, platform-independent web content. JSP pages are essentially HTML files with embedded Java code and special JSP tags. When a client requests a JSP page, the server translates it into a Servlet, compiles it, and executes it to produce an HTML response.
JSP was developed by Sun Microsystems (now Oracle) as part of the Java EE (Enterprise Edition) platform. It runs on any JSP-enabled web server such as Apache Tomcat, JBoss, or GlassFish. JSP simplifies web development by separating presentation logic (HTML/CSS) from business logic (Java code).
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>My First JSP Page</title>
</head>
<body>
<h1>Hello, JSP!</h1>
<p>Current Date and Time: <%= new java.util.Date() %></p>
<%
String name = "World";
out.println("<p>Hello, " + name + "!</p>");
%>
</body>
</html>
JSP and Servlets are both Java-based server-side technologies, but they serve different purposes. Here's a comparison:
| Feature | JSP | Servlet |
|---|---|---|
| Primary Use | Presentation layer (View) | Business/Controller logic |
| File Extension | .jsp | .java (compiled to .class) |
| Code Style | HTML with embedded Java | Java with embedded HTML |
| Compilation | Auto-compiled by container | Must be compiled manually |
| Implicit Objects | 9 built-in implicit objects | Must be created explicitly |
| Custom Tags | Supported (JSTL, custom) | Not supported |
| Maintenance | Easier (HTML-centric) | Harder (Java-centric) |
| Performance | Slightly slower (first request) | Faster (pre-compiled) |
| MVC Role | View | Controller |
Every JSP page goes through a well-defined lifecycle managed by the JSP tl-container (e.g., Tomcat). Understanding this lifecycle is key to writing efficient JSP applications:
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%!
// jspInit() - called once when JSP is first loaded
public void jspInit() {
System.out.println("JSP Initialized");
}
// jspDestroy() - called when JSP is removed from service
public void jspDestroy() {
System.out.println("JSP Destroyed");
}
%>
<html>
<body>
<%
// _jspService() is called for every request
out.println("<h2>Processing request...</h2>");
out.println("<p>Request method: " + request.getMethod() + "</p>");
%>
</body>
</html>
JSP follows a request-response architecture within the Java EE web tier:
On subsequent requests for the same JSP (unchanged), the tl-container skips translation/compilation and directly executes the cached Servlet class - making JSP very efficient after the first request.
Explore 500+ free tutorials across 20+ languages and frameworks.