JSP (Java Server Pages)

Dynamic web pages with embedded Java code

📄 What is JSP?

JSP (Java Server Pages) is a technology for creating dynamic web pages by embedding Java code directly into HTML. It simplifies web development by separating presentation from business logic.


<%-- Simple JSP Example --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
    <title>Hello JSP</title>
</head>
<body>
    <h1>Welcome to JSP!</h1>
    <p>Current time: <%= new java.util.Date() %></p>
    <p>Random number: <%= Math.random() * 100 %></p>
</body>
</html>
                                    

Output (in browser):

Welcome to JSP!

Current time: Thu Jan 18 14:30:25 PST 2024

Random number: 73.42

Key JSP Concepts

🏷️

Directives

Page configuration and imports

<%@ page import="java.util.*" %>
<%@ include file="header.jsp" %>

Scriptlets

Embedded Java code blocks

<% 
    String name = "World";
    out.println("Hello " + name);
%>
📤

Expressions

Output Java expressions directly

<%= userName %>
<%= 2 + 3 %>
🎯

Actions

JSP standard action tags

<jsp:include page="menu.jsp" />
<jsp:forward page="login.jsp" />

🔹 JSP Syntax Elements

Different ways to embed Java code in JSP pages:

<%-- JSP Comment (not sent to client) --%>
<!-- HTML Comment (sent to client) -->

<%-- Page Directive --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" 
         import="java.util.*, java.text.*" %>

<html>
<head>
    <title>JSP Syntax Demo</title>
</head>
<body>
    <h2>JSP Syntax Elements</h2>
    
    <%-- Declaration: Define variables and methods --%>
    <%! 
        private int counter = 0;
        private String formatDate(Date date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date);
        }
    %>
    
    <%-- Scriptlet: Java code block --%>
    <% 
        counter++;
        String userName = request.getParameter("name");
        if (userName == null) {
            userName = "Guest";
        }
        Date currentDate = new Date();
    %>
    
    <%-- Expression: Output values --%>
    <p>Welcome, <%= userName %>!</p>
    <p>Page visits: <%= counter %></p>
    <p>Current time: <%= formatDate(currentDate) %></p>
    
    <%-- Conditional logic --%>
    <% if (counter > 5) { %>
        <p style="color: red;">High traffic detected!</p>
    <% } else { %>
        <p style="color: green;">Normal traffic</p>
    <% } %>
    
</body>
</html>

🔹 JSP Implicit Objects

Built-in objects available in JSP pages:

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<body>
    <h2>JSP Implicit Objects Demo</h2>
    
    <%-- request object --%>
    <p>Request Method: <%= request.getMethod() %></p>
    <p>Request URI: <%= request.getRequestURI() %></p>
    <p>Client IP: <%= request.getRemoteAddr() %></p>
    
    <%-- response object --%>
    <% response.setHeader("Custom-Header", "JSP-Demo"); %>
    
    <%-- session object --%>
    <% 
        Integer visitCount = (Integer) session.getAttribute("visits");
        if (visitCount == null) {
            visitCount = 1;
        } else {
            visitCount++;
        }
        session.setAttribute("visits", visitCount);
    %>
    <p>Session ID: <%= session.getId() %></p>
    <p>Visit Count: <%= visitCount %></p>
    
    <%-- application object --%>
    <p>Server Info: <%= application.getServerInfo() %></p>
    <p>Context Path: <%= application.getContextPath() %></p>
    
    <%-- out object --%>
    <% 
        out.println("<p>This is printed using out object</p>");
        out.flush();
    %>
    
    <%-- config object --%>
    <p>Servlet Name: <%= config.getServletName() %></p>
    
    <%-- pageContext object --%>
    <% pageContext.setAttribute("message", "Hello from pageContext!"); %>
    <p>Page Message: <%= pageContext.getAttribute("message") %></p>
    
</body>
</html>

🔹 JSP Standard Actions

Built-in action tags for common operations:

<%-- Include another JSP page --%>
<jsp:include page="header.jsp" />

<%-- Forward to another page --%>
<% if (user == null) { %>
    <jsp:forward page="login.jsp" />
<% } %>

<%-- Use JavaBean --%>
<jsp:useBean id="user" class="com.example.User" scope="session" />
<jsp:setProperty name="user" property="name" value="John Doe" />
<jsp:getProperty name="user" property="name" />

<%-- Include with parameters --%>
<jsp:include page="menu.jsp">
    <jsp:param name="activeTab" value="home" />
</jsp:include>

<%-- Plugin for applets (rarely used now) --%>
<jsp:plugin type="applet" code="MyApplet.class" 
            width="300" height="200">
    <jsp:fallback>
        <p>Your browser doesn't support applets.</p>
    </jsp:fallback>
</jsp:plugin>

🔹 Form Processing with JSP

Handling HTML forms in JSP pages:

🔸 Form Page (form.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
    <title>User Registration</title>
    <style>
        .form-group { margin: 10px 0; }
        input[type="text"], input[type="email"], select { 
            width: 200px; padding: 5px; 
        }
    </style>
</head>
<body>
    <h2>User Registration Form</h2>
    
    <form action="process.jsp" method="post">
        <div class="form-group">
            <label>Name: </label>
            <input type="text" name="name" required>
        </div>
        
        <div class="form-group">
            <label>Email: </label>
            <input type="email" name="email" required>
        </div>
        
        <div class="form-group">
            <label>Age: </label>
            <input type="number" name="age" min="1" max="120">
        </div>
        
        <div class="form-group">
            <label>Country: </label>
            <select name="country">
                <option value="USA">United States</option>
                <option value="UK">United Kingdom</option>
                <option value="CA">Canada</option>
                <option value="AU">Australia</option>
            </select>
        </div>
        
        <div class="form-group">
            <input type="submit" value="Register">
            <input type="reset" value="Clear">
        </div>
    </form>
</body>
</html>

🔸 Processing Page (process.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
    <title>Registration Result</title>
</head>
<body>
    <h2>Registration Successful!</h2>
    
    <%
        // Get form parameters
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String ageStr = request.getParameter("age");
        String country = request.getParameter("country");
        
        // Validate and process data
        if (name != null && !name.trim().isEmpty()) {
    %>
        <div style="border: 1px solid #ccc; padding: 15px; margin: 10px 0;">
            <h3>User Information:</h3>
            <p><strong>Name:</strong> <%= name %></p>
            <p><strong>Email:</strong> <%= email %></p>
            
            <% if (ageStr != null && !ageStr.isEmpty()) { %>
                <p><strong>Age:</strong> <%= ageStr %> years old</p>
            <% } %>
            
            <p><strong>Country:</strong> <%= country %></p>
            
            <p style="color: green;">
                <strong>Registration completed at:</strong> 
                <%= new java.util.Date() %>
            </p>
        </div>
        
        <%
            // Here you would typically save to database
            // Database.saveUser(name, email, age, country);
        %>
        
    <% } else { %>
        <p style="color: red;">Error: Name is required!</p>
    <% } %>
    
    <p><a href="form.jsp">Register Another User</a></p>
</body>
</html>

🔹 JSP vs Servlets

Understanding when to use JSP vs Servlets:

JSP Advantages:

  • Easy HTML integration: Mix HTML and Java seamlessly
  • Rapid development: Faster for presentation layer
  • Automatic compilation: No manual servlet compilation
  • Designer-friendly: Web designers can work with HTML parts

When to use JSP:

  • Presentation layer with dynamic content
  • Reports and data display pages
  • Form-based applications
  • Content management systems

When to use Servlets:

  • Business logic and data processing
  • API endpoints and web services
  • Complex request handling
  • File uploads and downloads

🧠 Test Your Knowledge

Which JSP syntax is used to output a Java expression?