JSP Syntax

This tutorial explains the basic elements used in the JSP pages. Following table lists these JSP elements with syntax.

JSP TagDescriptionSyntax
DirectiveSpecifies translation time instruction to JSP engine. There are there types of directives: page,include and taglib directives.<%@Directives%>, <%@page..%>, <%@include..%>, <%@taglib..%>
DeclarationIt is used to declare and define variables and methods. Variables or methods must be declared before you use it in the JSP file.<%!some java code>
ScriptletsTags are used to embed java code in JSP page. Allows to write free-form java code in JSP page.<%count++%>
ExpressionUsed to print value in the output html file. The value of expression element is converted to String. 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.<%=an expression%>
ActionProvides request time instructions to the JSP engine.<jsp:actionname/>
CommentUsed for documentation and contains texts or statements that JSP container ignores.<%–Any text–%>

The following example shows use of Declaration,Comment,Expression,Scriptlets tags at one place:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%!int fontSize=10;%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%---- addition Program --%><br>
<% int a = 5;
   int b = 3;

   int result = a+b;%><br>
   <font color="green" size="<%= fontSize %>"><br>

   <% out.print(" Total=" +result); %><br>
   </font>
</body>
</html>

Details of the above code:

  1. <%!int fontSize=10;%> is a declaration of variable fontSize
  2. <%—- addition Program –%> is a comment
  3. <% int a = 5;int b = 3; int result = a+b;%> is a Scriptlet.
  4. <%= fontSize %> is an Expression.

Execute the above code in Eclipse and the output would be:

jsp_syntaxexample_demo

Previous Tutorial :  Create JSP Page in Eclipse   ||  Next Tutorial :  JSP Actions

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*