In this chapter we are going to look at Syntax of JSP. We will understand simple JSP syntax to write our JSP program.
1. Scriptlet Element:
Scriptlet element is the main JSP element in which you can write any sort of statement, declaration of variable or expression.
Following is the JSP syntax of Scriptlet:
<% JSP code %>
Below is the example of JSP Scriptlet Element:
<html> <head> <title>Hello World</title> </head> <body> Hello World!<br/> <% out.println("Demo of Scriptlet Element"); %> </body> </html>
2. Declaration Element:
Like other programming languages, you can also declare variables in JSP to use later on in your code. To do so, JSP Declaration element is used.
<%! declaration; ... %>
Example of JSP Declaration:
<%! int a = 0; %> <%! int a, b, c; %> <%! Demo obj = new Demo(); %>
3. Expression Element:
Inside Expression element we use simple Java expression that is evaluated and converted into String. Remember, you can’t use semicolon at the end of the line.
Also, you can write any valid expression of Java language.
Following is the JSP syntax of Expression Element:
<%= expression %>
Below is the example of Expression Element:
<html> <head> <title>Hello World</title> </head> <body> <p>Printing today's date: <%= (new java.util.Date()).toLocaleString()%></p> </body> </html>
4. JSP Comment
You can comment statement in JSP like you do in any other programming language. Comment part of JSP is ignored by the JSP container and for that you need to add below syntax:
<%-- This is JSP comment --%>
<html> <head> <title>Hello World</title> </head> <body> <h2>This is Heading H2</h2> <%-- This is commented code --%> </body> </html>
That’s it for JSP syntax, there is a lot more elements in JSP and we will be discussing them in further chapters.