Popular Searches
Popular Course Categories
Popular Courses

Understanding JSP Scriptlets, Expressions, and Declarations

Understanding JSP Scriptlets, Expressions, and Declarations

JavaServer Pages (JSP) Development

Understanding JSP Scriptlets, Expressions, and Declarations

Course: Advanced Java Training

Topic: Understanding JSP Scriptlets, Expressions, and Declarations

Course Link: Advanced Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to JSP Scripting Elements

JavaServer Pages (JSP), known as Jakarta Server Pages in modern Jakarta EE environments, is a server-side technology used to create dynamic web pages. It allows developers to combine HTML markup with dynamic values and server-side application data. A JSP page is processed by a JSP container, which translates the page into a servlet implementation and compiles it when required.

JSP provides three traditional scripting elements for embedding Java code into a page: scriptlets, expressions, and declarations. Each element has a different purpose and is processed according to its role in the generated servlet.

  • Scriptlets: Execute Java statements while processing a request.
  • Expressions: Evaluate a Java expression and write its value into the response.
  • Declarations: Declare fields or methods that belong to the generated JSP servlet class.

These scripting elements are important for understanding legacy JSP applications. In modern JSP development, Expression Language (EL), JSTL, servlets, and Java classes are generally preferred because they keep presentation separate from application logic.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Define JSP scripting elements and explain their purpose.
  • Understand the syntax of scriptlets, expressions, and declarations.
  • Write Java statements inside JSP scriptlets.
  • Display dynamic values using JSP expressions.
  • Declare variables and methods using JSP declarations.
  • Understand the difference between local variables and servlet instance fields.
  • Explain how JSP scripting elements relate to the generated servlet.
  • Identify common syntax and compilation errors.
  • Recognize thread-safety risks associated with shared JSP fields.
  • Refactor scriptlet-based code into cleaner MVC-style applications.

3. What Are JSP Scripting Elements?

JSP scripting elements are special JSP syntax structures that allow Java code to interact with template content. The JSP container processes these elements when generating the servlet implementation.

Scripting Element Syntax Main Purpose Typical Use
Scriptlet <% ... %> Execute Java statements Conditions, loops, and request-time processing in legacy pages
Expression <%= ... %> Write an expression's value to the response Displaying a calculated or retrieved value
Declaration <%! ... %> Declare fields and methods in the generated servlet class Legacy page-level fields or helper methods

Although all three elements contain Java code, they do not behave identically. Their placement in the generated servlet affects variable scope, execution, output, and concurrency.

4. Understanding JSP Scriptlets

4.1 Definition

A JSP scriptlet is a block of Java statements embedded in a JSP page. Its code is executed when the generated servlet processes a request. A scriptlet can contain local variable declarations, conditional statements, loops, method calls, and other valid Java statements.

4.2 Syntax

<%
    // Java statements go here
%>

The opening tag <% starts the scriptlet, and %> ends it. Unlike a JSP expression, a scriptlet does not automatically print the result of a statement. Output must be produced explicitly or through the surrounding template.

4.3 Example: Displaying a Message

<%
    String message = "Welcome to Advanced Java";
    out.println(message);
%>

Explanation:

  • A local variable named message stores a string.
  • The out implicit object writes content to the JSP response output.
  • The browser receives the generated output as part of the response.

4.4 Example: Using an If-Else Statement

<%
    int marks = 78;

    if (marks >= 40) {
        out.println("Result: Pass");
    } else {
        out.println("Result: Fail");
    }
%>

This example checks whether the marks meet the passing threshold. The selected message is written to the response. In a real application, the marks would normally be calculated or retrieved by a Java service rather than hard-coded in a JSP.

4.5 Example: Using a Loop

<%
    for (int i = 1; i <= 5; i++) {
        out.println("<p>Number: " + i + "</p>");
    }
%>

The loop runs five times and writes five HTML paragraph elements. The browser renders those elements as separate lines of content.

4.6 Mixing Scriptlets with HTML

Scriptlets can be combined with static HTML, allowing a page to conditionally display template content.

<%
    boolean loggedIn = true;
%>

<html>
<body>
    <%
        if (loggedIn) {
    %>
        <h2>Welcome back!</h2>
    <%
        } else {
    %>
        <h2>Please log in.</h2>
    <%
        }
    %>
</body>
</html>

This is valid as a scripting example, but it becomes difficult to maintain when large amounts of Java code are mixed with HTML. A controller and a tag-based view are generally better for new applications.

5. Understanding JSP Expressions

5.1 Definition

A JSP expression evaluates a single Java expression and inserts its result into the response output. The value is converted to its textual representation by the JSP processing mechanism.

5.2 Syntax

<%= expression %>

A JSP expression does not require a semicolon at the end because it represents an expression rather than a sequence of Java statements.

5.3 Example: Displaying a String

<p>Course: <%= "Advanced Java Training" %></p>

The string value is inserted into the generated HTML response.

5.4 Example: Displaying a Calculation

<p>Total: <%= 100 + 250 %></p>
<p>Discount: <%= 500 * 0.10 %></p>

The first expression evaluates to 350, while the second evaluates to 50.0. These values are included in the response as text.

5.5 Example: Displaying the Current Date and Time

<p>Current server time:
    <%= new java.util.Date() %>
</p>

This example displays the date and time produced by the server when the page is processed. The exact result depends on the server's clock and time-zone configuration.

5.6 Example: Displaying a Variable

<%
    String studentName = "Aarav";
%>

<p>Student Name: <%= studentName %></p>

The scriptlet declares a local variable, and the expression writes its value to the response. The variable is available here because the scriptlet and expression are translated into the same JSP service-processing context.

5.7 Important Expression Rules

  • The expression must contain a valid Java expression.
  • Do not place a statement such as if or for directly inside an expression.
  • Do not add a trailing semicolon to a normal JSP expression.
  • The expression's result is written into the response.
  • Expressions do not automatically escape HTML-sensitive characters.

Security warning: Never assume that a JSP expression safely renders untrusted input. Directly inserting user-supplied text into HTML can create a cross-site scripting (XSS) vulnerability. Use appropriate output encoding or trusted escaping tags.

6. Understanding JSP Declarations

6.1 Definition

A JSP declaration defines a field or method in the generated JSP servlet class. Unlike a scriptlet, which is placed inside the request-processing method, a declaration is placed at class level.

6.2 Syntax

<%!
    // Field or method declaration
%>

Declarations do not directly produce output. Their fields and methods may be referenced by scriptlets and expressions in the same JSP page, subject to normal Java access and scope rules.

6.3 Example: Declaring a Variable

<%!
    int pageVisits = 0;
%>

This declares a field on the generated servlet instance. It is not a separate local variable for each request. If the JSP servlet instance is shared across requests, concurrent requests can access the same field.

Important: A field like pageVisits is not a reliable or thread-safe way to count visitors. Multiple requests may access or modify it concurrently, and the value may reset when the JSP is recompiled or the application restarts. Use a suitable counter service or carefully designed concurrent data structure if shared counting is genuinely required.

6.4 Example: Declaring a Method

<%!
    public String getCourseName() {
        return "Advanced Java";
    }
%>

<p>Course: <%= getCourseName() %></p>

The declaration defines a method on the generated servlet class. The JSP expression calls that method and inserts its returned string into the response.

6.5 Example: Declaring a Constant

<%!
    private static final String COURSE_NAME =
        "Advanced Java Training";
%>

<p>Course: <%= COURSE_NAME %></p>

This example declares a constant and displays it. Although a constant is safer than mutable shared state, application-wide constants and reusable business logic are generally better placed in ordinary Java classes.

7. Detailed Comparison of Scriptlets, Expressions, and Declarations

Feature Scriptlet Expression Declaration
Syntax <% ... %> <%= ... %> <%! ... %>
Purpose Execute Java statements Write a value to the response Define fields or methods
Generated location Inside the request-processing method As output-writing code in the request-processing method At class level in the generated servlet
Typical execution During request processing During request processing Field initialization follows Java class and instance initialization rules
Direct output Only if code writes output Yes, the evaluated value is written No
Can declare a local variable? Yes No; it evaluates an expression Can declare a field at class level
Can define a method? Not as a method declaration in the method body No Yes
Concurrency consideration Local variables are generally request-local Depends on the data accessed Mutable fields may be shared across concurrent requests
Modern recommendation Avoid in new view code Prefer EL for ordinary view data Move reusable logic to Java classes

8. How JSP Scripting Elements Work Internally

A JSP container processes scripting elements while translating a JSP page into a servlet implementation. The exact generated source is container-dependent, but the conceptual mapping helps explain their different behavior.

Scriptlet Mapping

<%
    String name = "Aarav";
%>

Conceptually, this code becomes a local variable declaration inside the generated request-processing method.

Expression Mapping

<%= name %>

Conceptually, the container generates code that evaluates the expression and writes its result to the output writer.

Declaration Mapping

<%!
    private String getMessage() {
        return "Welcome";
    }
%>

Conceptually, this method becomes a method of the generated servlet class, outside the request-processing method.

The JSP specification defines the required behavior, but developers should not depend on implementation-specific generated source details.

9. Understanding Variable Scope and Thread Safety

One of the most important differences between scriptlets and declarations is where their variables live.

Local Variable in a Scriptlet

<%
    int total = 10;
    total = total + 5;
%>

<p>Total: <%= total %></p>

The variable total is local to the request-processing method. It is not a field shared across all requests to the JSP servlet.

Mutable Field in a Declaration

<%!
    int total = 10;
%>

<%
    total++;
%>

<p>Total: <%= total %></p>

This example uses a mutable field shared by requests handled by the same servlet instance. Concurrent requests can update it at the same time, potentially producing race conditions and unpredictable results. Avoid this pattern for request-specific values.

Best Practices for State

  • Use local variables for temporary request-processing calculations.
  • Use request attributes to pass data from a servlet controller to a JSP view.
  • Use session attributes only for suitable user-session data.
  • Use application-scoped storage or a service for genuinely shared application data, with appropriate concurrency controls.
  • Do not store passwords, private user data, or other sensitive values in shared fields.

10. JSP Implicit Objects Used with Scriptlets

JSP provides implicit objects that can be accessed directly in scripting elements. They are supplied by the JSP container and do not need to be declared by the developer.

Object Purpose Example
request Provides information about the current HTTP request request.getParameter("name")
response Represents the HTTP response response.setContentType("text/html")
out Writes output to the response out.println("Welcome")
session Represents the current HTTP session, if enabled session.getAttribute("user")
application Provides access to the web application's servlet context application.getAttribute("siteName")
pageContext Provides access to page context and JSP-related facilities pageContext.getRequest()
config Provides servlet configuration information config.getServletName()
page Refers to the current generated JSP servlet object Used rarely in normal page code

Example: Reading a Request Parameter

<%
    String username = request.getParameter("username");

    if (username == null || username.isBlank()) {
        username = "Guest";
    }
%>

<p>Welcome, <%= username %>!</p>

This example reads a query or form parameter and supplies a fallback when the value is absent. In production, the value must also be encoded appropriately before being inserted into HTML. A servlet controller and an escaping tag are preferable to direct rendering.

11. Complete JSP Example Using All Three Elements

The following example demonstrates a scriptlet, an expression, and a declaration within one JSP page. It is intended for learning syntax rather than as a recommended production design.

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>

<%!
    private String getCourseLevel() {
        return "Advanced";
    }
%>

<%
    String courseName = "Java Web Development";
    int duration = 30;
    int completedDays = 12;
    int remainingDays = duration - completedDays;
%>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSP Scripting Example</title>
</head>
<body>
    <h1>Course Information</h1>

    <p>Course: <%= courseName %></p>
    <p>Level: <%= getCourseLevel() %></p>
    <p>Duration: <%= duration %> days</p>
    <p>Completed: <%= completedDays %> days</p>
    <p>Remaining: <%= remainingDays %> days</p>

    <%
        if (remainingDays > 0) {
    %>
        <p>Your course is in progress.</p>
    <%
        } else {
    %>
        <p>Your course is complete.</p>
    <%
        }
    %>
</body>
</html>

Code Explanation

  1. The page directive sets the response content type and character encoding.
  2. The declaration defines a method named getCourseLevel().
  3. The scriptlet creates local variables and calculates the number of remaining days.
  4. The expressions insert the course details and calculated values into the response.
  5. The conditional scriptlet selects a message based on the remaining days.

12. Common Mistakes and Troubleshooting

Problem Reason Solution
JSP compilation error Invalid Java syntax or mismatched JSP delimiters Check opening and closing tags and verify Java syntax.
Expression does not compile A statement was used instead of an expression Use a valid Java expression and remove an unnecessary semicolon.
Scriptlet variable is undefined Variable scope or declaration order is incorrect Declare the local variable in a compatible scope before use.
Method cannot be found Method declaration is missing or its signature is incorrect Verify the declaration syntax and method name.
Unexpected shared value A declaration field is shared between requests Use a local variable or properly managed application component.
Incorrect output Wrong expression, data type, or calculation Check the expression and inspect server logs.
HTML appears as text Output has been escaped or encoded differently than intended Check the rendering context and intended output encoding.
Untrusted input creates unsafe markup Input is printed without context-appropriate encoding Use an escaping mechanism and validate input.
Changes do not appear Stale deployment or browser cache Refresh the browser and verify the deployed application.

13. Best Practices for JSP Scripting Elements

  • Understand scriptlets, expressions, and declarations to maintain existing JSP applications.
  • Avoid embedding complex business logic in JSP files.
  • Prefer Expression Language and JSTL for view-level rendering and iteration.
  • Use servlets or framework controllers to validate and process requests.
  • Use Java service classes for reusable business logic.
  • Avoid mutable instance fields in JSP declarations because requests may be processed concurrently.
  • Encode untrusted output to prevent cross-site scripting.
  • Use clear names and consistent formatting.
  • Handle null values and invalid user input.
  • Keep Java web dependencies compatible with the selected servlet container.

14. Modern Alternative: Expression Language and JSTL

For new JSP pages, developers should usually prepare values in a controller and display them with EL. JSTL can handle common presentation operations without embedding Java statements in the page.

Servlet Controller

request.setAttribute("courseName", "Advanced Java");
request.setAttribute("courseDuration", 30);
request.getRequestDispatcher("/course.jsp")
       .forward(request, response);

JSP View Using EL

<%@ page contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Course Details</title>
</head>
<body>
    <h1>Course Details</h1>
    <p>Course: ${requestScope.courseName}</p>
    <p>Duration: ${requestScope.courseDuration} days</p>
</body>
</html>

This approach separates request handling from presentation. For untrusted or user-generated values, use context-appropriate output encoding; EL alone does not guarantee safe HTML rendering.

15. Practical Exercises

  1. Create a JSP page that uses a scriptlet to declare a local variable and display a message.
  2. Use an expression to display the result of a mathematical calculation.
  3. Create a declaration that defines a method returning a course name.
  4. Build a JSP page that uses an if-else statement to display a result.
  5. Use a loop to display the numbers from 1 to 10.
  6. Read a request parameter and display a greeting with appropriate output encoding.
  7. Compare a local scriptlet variable with a declaration field.
  8. Refactor a scriptlet-based course page to use a servlet controller and EL.
  9. Create a JSP page that displays student details prepared by a controller.
  10. Identify and correct a concurrency risk caused by a mutable declaration field.

16. Interview Questions and Answers

Q1. What are JSP scripting elements?

Answer: JSP scripting elements are constructs that embed Java code in JSP pages. The three traditional elements are scriptlets, expressions, and declarations.

Q2. What is the syntax of a JSP scriptlet?

Answer: A scriptlet uses <% ... %> and contains Java statements executed during request processing.

Q3. What is the syntax of a JSP expression?

Answer: A JSP expression uses <%= ... %> and writes the evaluated expression's value to the response output.

Q4. What is the syntax of a JSP declaration?

Answer: A JSP declaration uses <%! ... %> to declare fields or methods in the generated servlet class.

Q5. Does a JSP expression require a semicolon?

Answer: No. A standard JSP expression represents a single Java expression, so a trailing semicolon is not required.

Q6. Do scriptlets automatically display their values?

Answer: No. A scriptlet executes statements. To write output, it must use an output mechanism such as the JSP out object, or the page must use a separate expression or template element.

Q7. What is the difference between a scriptlet variable and a declaration field?

Answer: A variable declared inside a scriptlet is normally local to the generated request-processing method. A field declared with <%! ... %> belongs to the generated servlet class and may be shared across concurrent requests handled by the same instance.

Q8. Can a JSP declaration define a method?

Answer: Yes. A declaration can define a method that is available to other scripting elements in the same JSP page.

Q9. Why can declaration fields be dangerous?

Answer: Mutable fields may be accessed by multiple requests concurrently. Unsynchronized updates can cause race conditions and incorrect results.

Q10. What is the difference between JSP scripting and Expression Language?

Answer: Scripting elements embed Java code directly in JSP. EL provides a simpler way to access data and properties for presentation, usually without writing Java statements.

Q11. Are JSP scriptlets recommended for new applications?

Answer: Generally, no. EL, JSTL, servlets, and Java classes usually produce cleaner and more maintainable code.

Q12. How can you prevent XSS when displaying dynamic data?

Answer: Validate inputs and encode untrusted values according to the output context. Use a trusted escaping tag or library rather than printing raw user-provided values.

17. Quick Revision Checklist

  • <% ... %> represents a scriptlet.
  • <%= ... %> represents an expression.
  • <%! ... %> represents a declaration.
  • Scriptlets execute Java statements during request processing.
  • Expressions evaluate a value and write it to the response.
  • Declarations define class-level fields and methods.
  • Scriptlet local variables and declaration fields have different scopes.
  • Mutable declaration fields can introduce concurrency problems.
  • JSP pages are translated into servlet implementations by the container.
  • EL and JSTL are generally preferred for presentation logic.
  • Output encoding is necessary when displaying untrusted values.
  • Controllers and Java classes should handle request processing and business logic.

18. Conclusion

Understanding JSP scriptlets, expressions, and declarations helps developers read, debug, and maintain Java web applications. Scriptlets execute Java statements, expressions display evaluated values, and declarations define fields or methods in the generated servlet class. Although these constructs remain important for understanding existing JSP code, modern applications benefit from using servlets or framework controllers, Java service classes, Expression Language, and JSTL to separate application logic from presentation.

By learning the syntax, scope, execution behavior, and limitations of each scripting element, developers can avoid common compilation errors, reduce concurrency risks, and build more maintainable web applications.

19. Further Learning

Explore the Advanced Java Training Course to learn more about JSP, Servlets, JDBC, and enterprise web application development.

To learn more about the course, visit the Course Demo Registration Page or the JustAcademy Website.

Official references: Jakarta Server Pages Specification and Jakarta EE Guide to Servlets and Server Pages.

Previous Next
whatsapp