Thursday, 6 September 2018

JSP Scripting Elements


JSP scripting elements let you insert Java code into the servlet that will be generated
from the JSP page. There are three forms:
  1. Expressions of the form <%= Java Expression %>, which are evaluated and inserted into the servlet's output.
  2. Scriptlets of the form <% Java Code %>, which are inserted into the servlet's _jspService method (called by service).
  3. Declarations of the form <%! Field/Method Declaration %>, which are inserted into the body of the servlet class, outside any existing methods.

Expressions

A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
Following is the syntax of JSP Expression:
<%= expression %>
You can write XML equivalent of the above syntax as follows.
<jsp:expression>
expression
</jsp:expression>
Following is the simple example for JSP Expression.
<html>
<head><title>Expression Test</title></head>
<body>
<p>
Today's date is: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
This would generate following result.
Today's date: 11-Sep-2010 21:24:25

Scriptlets

A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
Syntax of Scriptlet:
<% code fragment %>
You can write XML equivalent of the above syntax as follows:
 <jsp:scriptlet>
code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

Declarations

A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file.
Following is the syntax of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>
You can write XML equivalent of the above syntax as follows:
 <jsp:declaration>
code fragment
</jsp:declaration>
Following is the simple example for JSP Declarations.
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

Enjoy Learning.

1 comment:

  1. We will help you to learn more about website development with Headless Wordpress Themes a 100% faster website for SEO and avoid Google webmaster issue with our headless wordpress themes.

    ReplyDelete