Adv Java - [Java Server Pages: Scripting Elements]

♠ Posted by Unknown in at 08:15

JSP Scripting Elements


Once the directives have been used to setup the scripting environment you can utilize the scripting language elements. JSP1.1. has three scripting language elements – declaration, scriptlets, and expressions. A declaration will declare elements, a scriptlet is a statement fragment, and an expression is a complete language expression. In JSP each scripting element begins with a “<%”. 

The syntax for each is:

<%! Declration %>
<% scriptlet %>
<%= expression %>

White space is optional after “<%!”, “<%”, “<%=”, and before “%>”. All these tags are based upon XML, you could even say that a JSP page can be mapped to a XML document. The XML equivalent syntax for the scripting elements above would be:

<jsp:declaration> declaration </jsp:declaration>
<jsp:scriptlet> scriptlet </jsp:scriptlet>
<jsp:expression> expression </jsp:expression>

In addition, there are two types of comments:

<%-- jsp comment --%>
<!-- html comment -->

The first form allows you to add comments to JSP source pages that will not appear in any form in the HTML that is sent to the client. Of course, the second form of comment is not specific to JSPs – it’s just an ordinary HTML comment. What’s interesting is that you can insert JSP code inside an HTML comment and the comment will be produced in the resulting page, including the result form the JSP code.

Declarations are used to declare variables and methods in the scripting language (Currently Java only) used in a JSP page. The declaration must be a complete Java statement and cannot produce any output in the out stream.

Example of JSP

<%--  Write a JSP program to implement the concept of scripting.
<%-- Below is a JSP Directive --%>
<%@ page import = "java.util.*" %>
<%-- Below are declarations: --%>
<%!
                        long loadTime = System.currentTimeMillis();
                        Date loadDate = new Date();
                        int hitCount = 0;
%>
<HTML>
<BODY>
                        <H1>This page was loaded at <%= loadDate %> </H1>
                        <H1>Hello, world! it's  <%=  new Date() %> </H1>
                        <H2>Here's an object :  <%=  new Object() %> </H2>
                        <H2>This page has been up <%= (System.currentTimeMillis() - loadTime)/1000 %> seconds</H2>
                        <H3> Page has been accessed <%= ++hitCount %> times since M%= loadDate %> </H3>
                        <%
                                                System.out.println("Good Bye");
                                                out.println("Good Night");
                        %>
</BODY>

</HTML>
Image:JSP Scripting Example
Add caption

0 comments:

Post a Comment