JSP Scripting

JSP (JavaServer Pages) scripting allows you to write Java code within an HTML document. The Java code is executed by the JSP engine on the server-side before the HTML is sent to the client browser. 
Here are some examples of JSP scripting:

1. Embedding Java Code: You can embed Java code within JSP tags <% %>. For example, the following code snippet shows how to use JSP scripting to print the current date and time using Java's Date class:

Code

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<html>
<head>
<title>Current Date and Time</title>
</head>
<body>
<%
Date date = new Date();
out.println("Current Date and Time: " + date.toString());
%>
</body>
</html>




2. JSP Scriptlets: A scriptlet is a block of code that is enclosed within <% %> tags. It can be used to execute any valid Java code. For example, the following code snippet shows how to use a scriptlet to print the sum of two numbers:

Code 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP Scriptlets</title>
</head>
<body>
<%
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
out.println("Sum of " + num1 + " and " + num2 + " is " + sum);
%>
</body>
</html>




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>JSP Scriptlets</title>
</head>
<body>
<%!
public int calculate(int x, int y) {
    return x + y;
}
%>

<%
int result = calculate(10, 20);
out.println("The result is " + result);
%>
</body>
</html>


3. JSP Expressions: A JSP expression is used to insert the value of a Java expression into the output HTML. The expression is enclosed within <%= %> tags. For example, the following code snippet shows how to use a JSP expression to print the value of a variable:

Code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Print a Variable</title>
</head>
<body>
<%
String name = "Prasanjeet";
%>
<p>Welcome <%= name %></p>
</body>
</html>

 



No comments:

Post a Comment