Java Notes
Complete introduction to JavaServer Pages (JSP) - how JSP works, JSP lifecycle, scripting elements, implicit objects, and building dynamic web pages.
What is JSP?
JavaServer Pages (JSP) is a server-side technology that allows you to embed Java code directly within HTML pages. JSP simplifies the creation of dynamic web content by separating presentation (HTML) from business logic (Java).
Behind the scenes, every JSP page is converted to a Servlet by the JSP container.
How JSP Works — Behind the Scenes
A JSP file like hello.jsp gets converted to hello_jsp.java:
// Auto-generated servlet from hello.jsp
public class hello_jsp extends HttpJspBase {
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
JspWriter out = response.getWriter();
out.write("<html>\n");
out.write("<body>\n");
out.write("<h1>Hello World</h1>\n");
out.write("</body>\n");
out.write("</html>");
}
}JSP Lifecycle
| Phase | Method | Description |
|---|---|---|
| Translation | N/A | JSP → Servlet source code |
| Compilation | N/A | Servlet source → bytecode |
| Loading | N/A | Class loaded by ClassLoader |
| Instantiation | Constructor | Single instance created |
| Initialization | jspInit() | Called once for setup |
| Request Processing | _jspService() | Called for each request |
| Destruction | jspDestroy() | Called during shutdown |
<%-- Override lifecycle methods --%>
<%!
public void jspInit() {
System.out.println("JSP initialized");
}
public void jspDestroy() {
System.out.println("JSP destroyed");
}
%>JSP Scripting Elements
1. Scriptlet <% ... %>
Embeds Java code that executes for each request:
<%
String name = request.getParameter("name");
if (name == null) name = "Guest";
java.util.Date now = new java.util.Date();
int hour = now.getHours();
String greeting;
if (hour < 12) greeting = "Good Morning";
else if (hour < 17) greeting = "Good Afternoon";
else greeting = "Good Evening";
%>
<h1><%= greeting %>, <%= name %>!</h1>
<p>Server time: <%= now %></p>2. Expression <%= ... %>
Outputs a value to the response (shortcut for out.print()):
<p>Today is: <%= new java.util.Date() %></p>
<p>Your IP: <%= request.getRemoteAddr() %></p>
<p>Session ID: <%= session.getId() %></p>
<p>2 + 3 = <%= 2 + 3 %></p>3. Declaration <%! ... %>
Declares instance variables and methods (added to servlet class):
4. Comment <%-- ... --%>
JSP Implicit Objects
JSP provides 9 built-in objects available without declaration:
| Object | Type | Description |
|---|---|---|
request | HttpServletRequest | Client request data |
response | HttpServletResponse | Server response |
out | JspWriter | Output stream |
session | HttpSession | User session |
application | ServletContext | Application context |
config | ServletConfig | Servlet configuration |
pageContext | PageContext | Page scope access |
page | Object | Current servlet instance |
exception | Throwable | Error (in error pages only) |
Using Implicit Objects
JSP Directives
Page Directive
<%@ page language="java"
contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"
import="java.util.*, java.text.*"
session="true"
isThreadSafe="true"
errorPage="error.jsp"
isErrorPage="false" %>Include Directive (Static include at translation time)
<%@ include file="header.jsp" %>
<h1>Main Content</h1>
<%@ include file="footer.jsp" %>Taglib Directive
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>Complete JSP Example: User Registration
register.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head><title>Registration</title></head>
<body>
<h2>User Registration</h2>
<%-- Show errors if any --%>
<%
String error = (String) request.getAttribute("error");
if (error != null) {
%>
<p style="color: red;"><%= error %></p>
<% } %>
<form action="register" method="POST">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Password:</label><br>
<input type="password" name="password" required><br><br>
<label>City:</label><br>
<select name="city">
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
<option value="Bangalore">Bangalore</option>
</select><br><br>
<button type="submit">Register</button>
</form>
</body>
</html>success.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<body>
<h2>Registration Successful!</h2>
<p>Welcome, <%= session.getAttribute("username") %>!</p>
<p>Email: <%= session.getAttribute("email") %></p>
<p>City: <%= session.getAttribute("city") %></p>
<a href="dashboard.jsp">Go to Dashboard</a>
</body>
</html>JSP Action Tags
<%-- Include another page at runtime --%>
<jsp:include page="header.jsp">
<jsp:param name="title" value="Home Page" />
</jsp:include>
<%-- Forward to another page --%>
<jsp:forward page="login.jsp">
<jsp:param name="message" value="Please login first" />
</jsp:forward>
<%-- Use JavaBeans --%>
<jsp:useBean id="user" class="com.example.User" scope="session" />
<jsp:setProperty name="user" property="name" value="John" />
<jsp:setProperty name="user" property="*" /> <%-- auto-populate from request --%>
<p>Name: <jsp:getProperty name="user" property="name" /></p>Common Mistakes
- Putting business logic in JSP — Use servlets for logic, JSP for view only
- Using scriptlets in modern apps — Use EL and JSTL instead
- Not setting page encoding — Character corruption issues
- Declaring variables in scriptlets that should be in declarations — Scope confusion
- Forgetting that JSP becomes a servlet — Debug by looking at generated code
Interview Key Points
- JSP is translated into a Servlet by the container
- JSP lifecycle: Translation → Compilation → Init → Service → Destroy
- 9 implicit objects: request, response, out, session, application, config, pageContext, page, exception
- Scriptlet
<% %>, Expression<%= %>, Declaration<%! %> <%@ page %>,<%@ include %>,<%@ taglib %>are directives- Modern JSP uses EL (
${expr}) and JSTL instead of scriptlets
Summary
In this chapter, we learned about JSP Introduction in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JSP Introduction.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, servlets, jsp, introduction
Related Java Master Course Topics