📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
The scripting elements provide the ability to insert Java code inside the JSP.
- JSP expressions
- JSP scriptlets
- JSP declarations
1. JSP expressions
The Syntax of JSP Expression Tag
<%= expression %>
JSP Expression Tag Examples
<html>
<body>
Converting a string to uppercase:
<%=new String("Hello World").toUpperCase()%>
</body>
</html>
2. JSP scriptlets
<% statement; [statement; …] %>
Example of JSP scriptlet tag
In this example, we are displaying a HelloWorld message.
```jsp
<html>
<body>
<% out.print("HelloWorld"); %>
</body>
</html>
3. JSP declarations
The Syntax of the JSP Declaration Tag
<%! Declaration %>
JSP Declaration Tag Example
<html>
<body>
<%!
int cube(int n){
return n * n * n;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
Combining All Scripting Elements
JSP allows you to combine scripting elements to create dynamic content efficiently. Here is an example that combines declarations, scriptlets, and expressions:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Combined Example</title>
</head>
<body>
<%
int num1 = 5;
int num2 = 3;
%>
<h1>Sum of <%= num1 %> and <%= num2 %> is: <%= sum(num1, num2) %></h1>
</body>
</html>
<%!
public int sum(int a, int b) {
return a + b;
}
%>
In this example:
- A method
sum
is declared using a declaration element. - Two variables
num1
andnum2
are initialized using a scriptlet. - Expressions are used to display the values of
num1
,num2
, and their sum.
Comments
Post a Comment
Leave Comment