🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare
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
sumis declared using a declaration element. - Two variables
num1andnum2are initialized using a scriptlet. - Expressions are used to display the values of
num1,num2, and their sum.
Comments
Post a Comment
Leave Comment