JSP tags tutorial

There are following JSP tags which need to know every JSP programmer.

  • Scriptlet
  • Declaration
  • Expression
  • Action
  • Directive


This is main tag of JSP. It is used to add request processing logic to page.A JSP page may contain any number of scritptlet tags. Contents of all these tags are moved to _jspService() of auto generated servlet i.e this tag is used to indirectly define _jspService() method.


Syntax to define Scriptlet

//Request processing logic here 
out.println("Hello from StartWithJava.com"); 

Declaration Tag

This tag is used to define data members and methods in the auto generated servlets.

Syntax to define declaration tag.

<%! Data members and methods definition %>

Expression Tag

Expression tag can be used for following two purposes.

  • To write a string or string returning expression to the output stream
  • To assign the value of variable or expression to the properties of HTML elements

Syntax to define expression tag.

<%=expression %>

Example to show value in an input field

<input type="text" name="email" value="<%=mail%>">

Action Tag

These tags are used to perform specific task during request processing.For each action tag code is generated in _jspService() method to perform the task represented by the action.

Most commonly used action tags are

  • <jsp:include>
  • <jsp:forward>

Example to use action tags

<jsp:include page="url of the component"> 
<jsp:forward page="url of the component">

Directive Tag

These tags are used to provide instruction to the translator so that structure of contents of the auto generated servlets can be get modified.

Syntax to define directive tags

<%@ directiveName attribute="value" ...%>

JSP supports three directives.

  • page
  • include
  • taglib

Example to use page directive

//Set content type to text/xml
<%@ page contentType="text/xml"%>

//To import packages
<%@ page import="java.sql.*" %>

Example to use include directive

<%@ include file="header.jsp" >
<%@ include file="footer.jsp" >

Example to use taglib directive
This directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.

<%@ taglib uri="http://www.example.com/custlib" prefix="customTag" %>

Leave a Reply