YourNote 401: JSP - zhamri/CSC584-Enterprise_Programming GitHub Wiki
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
JSP also has a lifecycle (similar to a servlet):
.jsp → translated to .java (Servlet) → compiled → executed
Methods involved:
-
_jspInit()→ initialization -
_jspService()→ handles request -
_jspDestroy()→ cleanup
Students must understand:
JSP = easier way to write Servlets
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
<%
String name = "Zhamri";
%><%= name %><%! int count = 0; %>Modern best practice:
Avoid scriptlets → use JSTL instead
Control page behavior
<%@ page import="java.util.*" %>Types:
- page → settings (import, encoding)
- include → include file
- taglib → use JSTL
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
JSP provides built-in objects:
-
request→ user data -
response→ output -
session→ user session -
application→ global data -
out→ print output
Example:
<%= request.getParameter("name") %><%
session.setAttribute("user", "Zhamri");
%>Used for:
- login system
- user tracking
Students always confuse this:
request.getRequestDispatcher("result.jsp").forward(request, response);- Same request
- Faster
response.sendRedirect("result.jsp");- New request
- URL changes
❌ Avoid:
- Java code inside JSP (scriptlet)
✅ Use:
- JSTL (Java Standard Tag Library)
- EL (Expression Language)
Example:
${user.name}Cleaner, industry standard
Important point:
- JSP should NOT connect directly to DB
- Use Servlet or Java class (Model)
Correct flow:
JSP → Servlet → DB → Servlet → JSP
Students must know:
- Place
.jspinside webapp/ - Run using Apache Tomcat
- Access via:
http://localhost:8080/projectName/file.jsp
- Mixing too much Java inside JSP
- Forgetting <%@ page %> directive
- Wrong file path
- Not understanding JSP → Servlet conversion
- Trying to do backend logic in JSP
- Servlet = brain (logic)
- JSP = face (UI)