Skip to content

YourNote 401: JSP

Zhamri Che Ani edited this page Apr 30, 2026 · 1 revision

1. What is JSP?

JSP (JavaServer Pages) is used to create dynamic web pages using Java.

Simple idea:

  • HTML + Java → dynamic content
  • Runs on a server like Apache Tomcat

Important:

JSP is actually converted into a Servlet behind the scenes

2. JSP Lifecycle

JSP also has a lifecycle (similar to a servlet):

.jsp → translated to .java (Servlet) → compiled → executed

Methods involved:

  1. _jspInit() → initialization
  2. _jspService() → handles request
  3. _jspDestroy() → cleanup

Students must understand:

JSP = easier way to write Servlets

3. Basic Structure of JSP

Example:

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<h1>Hello World</h1>
</body>
</html>

Looks like HTML but runs Java on the server

4. JSP Elements

a) Scriptlet (Java code)

<% 
    String name = "Zhamri";
%>

b) Expression (output)

<%= name %>

c) Declaration (variables/methods)

<%! int count = 0; %>

Modern best practice:

Avoid scriptlets → use JSTL instead

5. JSP Directives

Control page behavior

<%@ page import="java.util.*" %>

Types:

  • page → settings (import, encoding)
  • include → include file
  • taglib → use JSTL

6. JSP + Servlet Flow

This is what students must understand clearly:

JSP (form) → Servlet (process logic) → JSP (display result)

Example:

  • form.jsp → user input
  • Servlet → process + database
  • result.jsp → display output

7. Implicit Objects

JSP provides built-in objects:

  • request → user data
  • response → output
  • session → user session
  • application → global data
  • out → print output

Example:

<%= request.getParameter("name") %>

8. Session Handling in JSP

<%
    session.setAttribute("user", "Zhamri");
%>

Used for:

  • login system
  • user tracking

9. Forward vs Redirect

Students always confuse this:

Forward (server-side)

request.getRequestDispatcher("result.jsp").forward(request, response);
  • Same request
  • Faster

Redirect (client-side)

response.sendRedirect("result.jsp");
  • New request
  • URL changes

10. Best Practice

❌ Avoid:

  • Java code inside JSP (scriptlet)

✅ Use:

  • JSTL (Java Standard Tag Library)
  • EL (Expression Language)

Example:

${user.name}

Cleaner, industry standard

11. Database with JSP (Indirect Use)

Important point:

  1. JSP should NOT connect directly to DB
  2. Use Servlet or Java class (Model)

Correct flow:

JSP → Servlet → DB → Servlet → JSP

12. Deployment & Running JSP

Students must know:

  • Place .jsp inside webapp/
  • Run using Apache Tomcat
  • Access via:
http://localhost:8080/projectName/file.jsp

13. Common Student Mistakes

  1. Mixing too much Java inside JSP
  2. Forgetting <%@ page %> directive
  3. Wrong file path
  4. Not understanding JSP → Servlet conversion
  5. Trying to do backend logic in JSP

Analogy

  • Servlet = brain (logic)
  • JSP = face (UI)

Clone this wiki locally