In this tutorial, we are going to discuss different scripting elements used in JSP. In JSP there are three types of scripting elements. These are shown below:
JSP Expression | It is a small Java code that you can include in a JSP
page. The syntax is <%= some java code %>
|
---|---|
JSP Scriptlet | The syntax for a scriptlet is <% some java code
%> . You can add 1 to many lines of Java code here.
|
JSP Declaration | The syntax for declaration is <%! Variable or
method declaration %> , in here you can declare a
variable or a method for use later in the code.
|
JSP Expression
Using the JSP Expression you can compute a small expression, always a single line, and get the result included in the HTML which is returned to the browser. Using the code we have previously written, let's explore expressions.
The time on the server is <%= new java.util.Date() %>
Here the new java.util.Date()
is processed into the actual date and time shown through HTML on the browser. Let's explore expressions through a couple of more examples.
Converting a string to uppercase <%= new String("Hello World").toUpperCase() %>
.
JSP Scriptlets
This JSP Scripting Element allows you to put in a lot of Java code in your HTML code. This Java code is processed from top to bottom when the page is processed by the web server. Here the result of the code isn't directly combined with the HTML rather you have to use out.println()
to show what you want to mix with HTML. The syntax is pretty much the same only you don't have to put in an equal sign after the opening % sign.
Let's take a look at the code:
<% for(int i = 0; i <= 5; i++) { out.println("I really love counting: " + i); } %>
JSP Declarations
The declarations come in handy when you have a code snippet that you want to execute more than once. Using the declaration, you can declare the method at the beginning of the code and then call the same method whenever you need it on the same page. The syntax is simple:
<%! //declare a variable or a method %>
<%! String makeItLower(String data) { returndata.toLowerCase(); } %>
Example Code
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.