This document discusses servlet technology and JavaServer Pages (JSP) technology. It provides definitions and explanations of servlets, JSPs, cookies, and related classes and interfaces. Some key points include:
- Servlets are Java programs that generate dynamic web content and reside on the server-side. JSPs are similar to servlets but make it easier to separate programming logic from presentation logic.
- The servlet lifecycle involves loading, instantiating, initializing, servicing requests, and destroying the servlet. The servlet interface defines common methods like init(), service(), destroy(), etc.
- Cookies are small pieces of information stored by the web server on the client-side browser
1. SRI VASAVI COLLEGE,ERODE
(Self -Finance Wing)
Department of Computer Science
I-M.Sc (CS)
Advanced Java Programming
Unit-4
Presented by
P.KALAISELVI
Assistant Professor
Department of Computer Science
2. Servlet technology is used to create a web
application (resides at server side and generates
a dynamic web page).
Servlet technology is robust and scalable because
of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was
common as a server-side programming langua
There are many interfaces and classes in the
Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
◦ Servlet can be described in many ways, depending on
the context.
3. ◦ Servlet is a technology which is used to create a web application.
◦ Servlet is an API that provides many interfaces and classes
including documentation.
◦ Servlet is an interface that must be implemented for creating any
Servlet.
◦ Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any
requests.
◦ Servlet is a web component that is deployed on the server to
create a dynamic web page.
4. What is a web application?
◦ A web application is an application accessible from the web. A
web application is composed of web components like Servlet, JSP,
Filter, etc. and other elements such as HTML, CSS, and JavaScript.
The web components typically execute in Web Server and respond
to the HTTP request.
CGI (Common Gateway Interface)
◦ CGI technology enables the web server to call an external
program and pass HTTP request information to the external
program to process the request. For each request, it starts a new
process.
5. Disadvantages of CGI
◦ There are many problems in CGI technology:
◦ If the number of clients increases, it takes more time
for sending the response.
◦ For each request, it starts a process, and the web server
is limited to start processes.
◦ It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
6. There are many advantages of Servlet over CGI.
The web container creates threads for handling
the multiple requests to the Servlet. Threads have
many benefits over the Processes such as they
share a common memory area, lightweight, cost
of communication between the threads are low.
The advantages of Servlet are as follows:
◦ Better performance: because it creates a thread for each
request, not process.
◦ Portability: because it uses Java language.
◦ Robust: JVM manages Servlets, so we don't need to
worry about the memory leak, garbage collection, etc.
◦ Secure: because it uses java language.
7. Life Cycle Of A Servlet
◦ Life cycle of a servlet is managed by web container.
Servlet life cycle steps:
Load Servlet Class.
Create Servlet instance.
Call init() method.
Call service() method.
Call destoy() method.
CGI Servlet
1.CGI is process based. For every
request a new process will be
started.
2.Concurrency problems can’t
occur in CGI because it is process
based.
3.Platform dependent.
4.Can be written in variety of
languages like c, c++, perl.
5.Response time is high.
1.Servlet is thread based. For every
request a new thread will be started.
2.Concurrency problems can occur in
servlet because it is thread based.
3.Platform independent.
4.Can be written only in java.
5.Response time is low.
8. 1.Load Servlet Class: Web container loads the servlet when
the first request is received. This step is executed only
once at the time of first request.
2. Create Servlet instance: After loading the servlet class
web container creates the servlet instance. Only one
instance is created for a servlet and all concurrent
requests are executed on the same servlet instance.
3. Call init() method: After creating the servlet instance web
container calls the servlet’s init method. This method is
used to initialize the servlet before processing first
request. It is called only once by the web container.
4. Call service() method: After initialization process web
container calls service method. Service method is called
for every request. For every request servlet creates a
separate thread.
5.Call destoy() method: This method is called by web
container before removing the servlet instance. Destroy
method asks servlet to releases all the resources
associated with it. It is called only once by the web
container when all threads of the servlet have exited or in
a timeout case.
9. Servlet interface:
◦ Servlet interface contains the common methods for all
servlets i.e. provides the common behaviour for all servlets.
◦ public interface Servlet
◦ Servlet interface is in javax.servlet package
(javax.servlet.Servlet).
Methods of servlet interface:
◦ 1. init(ServletConfig config): It is used to initialize the servlet.
This method is called only once by the web container when it
loads the servlet.
Syntax:
◦ public void init(ServletConfig config)throws ServletException
◦ 2. service(ServletRequest request,ServletResponse
response): It is used to respond to a request. It is called for
every new request by web container.
Syntax:
◦ public void service(ServletRequest req,ServletResponse res)
throws ServletException, IOException
10. ◦ 3. destroy(): It is used to destroy the servlet. This method
is called only once by the web container when all threads
of the servlet have exited or in a timeout case.
Syntax:
public void destroy()
◦ 4. getServletConfig(): It returns a servlet config object.
This config object is passed in init method. Servlet
config object contains initialization parameters and
startup configuration for this servlet.
Syntax:
public ServletConfig getServletConfig()
◦ 5. getServletInfo(): It returns a string of information
about servlet’s author, version, and copyright etc.
Syntax:
public String getServletInfo()
11. Cookie:
◦ A cookie is a small piece of information as a text file stored
on client’s machine by a web application.
How cookie works?
◦ As HTTP is a stateless protocol so there is no way to identify
that it is a new user or previous user for every new request.
In case of cookie a text file with small piece of information is
added to the response of first request. They are stored on
client’s machine. Now when a new request comes cookie is
by default added with the request. With this information we
can identify that it is a new user or a previous user.
Types of cookies:
◦ 1. Session cookies/Non-persistent cookies: These types of
cookies are session dependent i.e. they are accessible as long
as session is open and they are lost when session is closed
by exiting from the web application.
12. ◦ 2. Permanent cookies/Persistent cookies: These types
of cookies are session independent i.e. they are not lost
when session is closed by exiting from the web
application. They are lost when they expire.
Advantages of cookies:
◦ They are stored on client side so don’t need any server
resource.
◦ Easy technique for session management.
Disadvantages of cookies:
◦ Cookies can be disabled from the browser.
◦ Security risk is there because cookies exist as a text file
so any one can open and read user’s information.
Cookie Class:
◦ Cookie class provides the methods and functionality for
session management using cookies. Cookie class is in
javax.servlet.http
Package javax.servlet.http.Cookie.
13. Commonly used constructor of Cookie class:
◦ 1. Cookie(String name,String value): Creates a cookie with
specified name and value pair.
Syntax:
◦ public Cookie(String name,String value)
Commonly used methods of cookie class:
1. setMaxAge(int expiry):Sets the maximum age of the cookie.
Syntax:
◦ Publ
2. getMaxAge(): Returns the maximum age of the cookie. Default
value is -1.
Syntax:
◦ public int getMaxAge()
3. setValue(String newValue): Change the value of the cookie with
new value.
Syntax:
◦ public void setValue(String newValue)
4. getValue(): Returns the value of the cookie.
Syntax:
◦ public String getValue()ic void setMaxAge(int expiry)
5. getName(): Returns the name of the cookie.
Syntax:
◦ public String getName()
14. How to create cookie?
◦ HttpServletResponse interface’s addCookie(Cookie ck) method is
used to add a cookie in response object.
◦ Syntax: public void addCookie(Cookie ck)
◦ Example:
//create cookie object
Cookie cookie=new Cookie(“cookieName”,”cookieValue”);
//add cookie object in the response
response.addCookie(cookie);
How to get cookie?
◦ HttpServletRequest interface’s getCookies() method is used to
get the cookies from request object.
◦ Syntax: public Cookie[] getCookies()
◦ Example:
//get all cookie objects.
Cookie[] cookies = request.getCookies();
//iterate cookies array to get individual cookie objects.
for(Cookie cookie : cookies){
out.println(“Cookie Name: ” + cookie.getName());
out.println(“Cookie Value: ” + cookie.getValue());
}
15. How to remove or delete cookies?
◦ Cookies can be removed by setting its expiration time
to 0 or -1. If expiration time set to 0 than cookie will be
removed immediately. If expiration time set to -1 than
cookie will be removed when browser closed.
◦ Example:
//Remove value from cookie
Cookie cookie = new Cookie(“cookieName”, “”);
//Set expiration time to 0.
cookie.setMaxAge(0);
//add cookie object in the response.
response.addCookie(cookie);
16. HttpServlet class:
◦ HttpServlet class extends the GenericServlet. It is protocol-
dependent.
◦ HttpServlet class is in javax.servlet.http package
(javax.servlet.http.HttpServlet).
Methods of HttpServlet class:
1. service(ServletRequest req,ServletResponse res):Dispatches
the requests to the protected service method. It converts the
request and response object into http type before
dispatching request.
Syntax:
◦ public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
2. service(HttpServletRequest req, HttpServletResponse
res):Receives HTTP requests from the public service method
and dispatches the request to the doXXX methods defined in
this class.
Syntax:
◦ protected void service(HttpServletRequest req,
HttpServletResponse res) throws
ServletException,IOException
17. 3. doGet(HttpServletRequest req, HttpServletResponse res): This
method is called by web container for handling GET requests.
Syntax:
◦ protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
4. doPost(HttpServletRequest req, HttpServletResponse res): This
method is called by web container for handling POST requests.
Syntax:
◦ protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
5. doHead(HttpServletRequest req, HttpServletResponse res): This
method is called by web container for handling HEAD requests.
Syntax:
◦ protected void doHead(HttpServletRequest req, HttpServletResponse
res) throws ServletException,IOException
6. doOptions(HttpServletRequest req, HttpServletResponse
res): This method is called by web container for handling
OPTIONS requests.
Syntax:
protected void doOptions(HttpServletRequest req,
HttpServletResponse res) throws ServletException,IOException
18. 7. doPut(HttpServletRequest req, HttpServletResponse res): This
method is called by web container for handling PUT requests.
Syntax:
◦ protected void doPut(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
8. doTrace(HttpServletRequest req, HttpServletResponse
res): This method is called by web container for handling
TRACE requests.
Syntax:
◦ protected void doTrace(HttpServletRequest req, HttpServletResponse
res) throws ServletException,IOException
9. doDelete(HttpServletRequest req, HttpServletResponse
res): This method is called by web container for handling
DELETE requests.
Syntax:
◦ protected void doDelete(HttpServletRequest req, HttpServletResponse
res) throws ServletException,IOException
10. getLastModified(HttpServletRequest req): It returns the time
the HttpServletRequest object was last modified since
midnight January 1, 1970 GMT. It returns a negative number if
time is unknown.
Syntax:
◦ protected long getLastModified(HttpServletRequest req)
19. ServletInputStream class
◦ ServletInputStream class provides stream to read binary data
such as image etc. from the request object. It is an abstract
class.
◦ The getInputStream() method of ServletRequest interface
returns the instance of ServletInputStream class. So can be
get as:
◦ ServletInputStream sin=request.getInputStream();
Method of ServletInputStream class
◦ There are only one method defined in the ServletInputStream
class.
◦ int readLine(byte[] b, int off, int len) it reads the input stream.
ServletOutputStream class
◦ ServletOutputStream class provides a stream to write binary
data into the response. It is an abstract class.
◦ The getOutputStream() method of ServletResponse interface
returns the instance of ServletOutputStream class. It may be
get as:
◦ ServletOutputStream out=response.getOutputStream();
21. Example to display image using Servlet
◦ In this example, we are using FileInputStream class to
read image and ServletOutputStream class for writing
this image content as a response. To make the
performance faster, we have used BufferedInputStream
and BufferedOutputStream class.
◦ You need to use the content type image/jpeg.
◦ In this example, we are assuming that you have
java.jpg image inside the c:test directory. You may
change the location accordingly.
◦ To create this application, we have created three files:
index.html
DisplayImage.java
web.xml
◦ index.html
This file creates a link that invokes the servlet. The url-
pattern of the servlet is servlet1.
<a href="servlet1">click for photo</a>
22. DisplayImage.javaThis servlet class reads the image from the mentioned directory and
writes the content in the response object using ServletOutputStream and
BufferedOutputStream classes.
package com.javatpoint;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DisplayImage extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException
{
response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("c:testjava.jpg");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}
}
23. JSP technology is used to create web
application just like Servlet technology. It can
be thought of as an extension to Servlet
because it provides more functionality than
servlet such as expression language, JSTL,
etc.
A JSP page consists of HTML tags and JSP
tags. The JSP pages are easier to maintain
than Servlet because we can separate
designing and development. It provides some
additional features such as Expression
Language, Custom Tags, etc.
24. There are many advantages of JSP over the
Servlet. They are as follows:
1) Extension to Servlet
◦ JSP technology is the extension to Servlet technology.
We can use objects, predefined tags, expression
language and Custom all the features of the Servlet in
JSP. In addition to, we can use implicit tags in JSP, that
makes JSP development easy.
2) Easy to maintain
◦ JSP can be easily managed because we can easily
separate our business logic with presentation logic. In
Servlet technology, we mix our business logic with the
presentation logic.
25. 3) Fast Development: No need to recompile and
redeploy
If JSP page is modified, we don't need to
recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we
have to change the look and feel of the
application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags,
JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
26. The JSP pages follow these phases:
◦ Translation of JSP Page
◦ Compilation of JSP Page
◦ Classloading (the classloader loads class file)
◦ Instantiation (Object of the Generated Servlet is
created).
◦ Initialization ( the container invokes jspInit() method).
◦ Request processing ( the container invokes
_jspService() method).
◦ Destroy ( the container invokes jspDestroy() method).
◦ Note: jspInit(), _jspService() and jspDestroy() are the
life cycle methods of JSP.
27. ◦ As depicted in the above diagram, JSP page is translated into
Servlet by the help of JSP translator. The JSP translator is a
part of the web server which is responsible for translating the
JSP page into Servlet. After that, Servlet page is compiled by
the compiler and gets converted into the class file. Moreover,
all the processes that happen in Servlet are performed on JSP
later like initialization, committing response to the browser
and destroy.
28. To work on JSP and create dynamic pages, you will need an environment
where you can develop and run web applications built using JSP. An
environment is basically a set of all the software and tools needed to create
dynamic web pages, test them, and eventually run them in a virtual client-
server. In this lesson, you will learn how to create and set up an environment
to start with JSP programming.
Java Development Kit (JDK) Setup
◦ This is probably the first thing you must do to work under Java supported tools and
technologies. The steps are as follows:
1. Download the Java SDK (Software Development Toolkit)
from https://www.oracle.com/technetwork/java/javase/downloads/index.html, the official
Oracle Java site.
2. After downloading the SDK, follow the instructions of the installation package.
3. After the JDK installation, some folders will be created on your hard drive. These are - bin,
demo, include, jre, lib, src.
4. Once you installed Java on your machine, you have to set the PATH along with
the JAVA_HOME environment variable that will point to a particular directory where Java
(java_install_dir/bin) and javac (java_install_dir) are residing.
5. Please refer to the Java installation tutorial to learn further environment setup steps.
In case you have installed or are using IDEs (Integrated Development Environment) like IntelliJ
IDEA, Eclipse, Borland JBuilder, NetBeans, BlueJ, etc., then this software already knows
where you have installed Java in your system.
29. To know more about Java installation and environment setup,
please refer Java Tutorials.
Setup and Install Apache Tomcat Server
◦ Tomcat is a web server and not an application server. Tomcat is
essentially a collection of several components as well as containers,
which includes a Tomcat JSP engine, a range of different connectors, and
servlet Container, but at its core resides the component that is termed
as Catalina.
Steps to Download and Configure Tomcat:
1. Tomcat is a free web server tool. You can download Tomcat
from http://tomcat.apache.org/download-70.cgi.
2. When you are done downloading the tomcat web server, unzip it in a
particular location where you want. Let suppose you use the E drive to
unzip Tomcat; then, your tomcat path will be E:apache-tomcat-
7.0.41. It is to be noted that by default, your Tomcat will get
configured for running on port 8080, and hence, it can be accessed
using http://localhost:8080.
3. Now, you have to make a new environment variable with the
name CATALINA_HOME, and you have to assign a value to the apache-
tomcat installation directory. Let suppose E:apache-tomcat-7.0.41
4. To start and stop the Tomcat server, you have to use the batch files
offered in %CATALINA_HOME%/bin
startup.bat for starting your server.
shutdown.bat for stopping your server.
5. For more information regarding configuration and running Tomcat
server can be read from here: https://tomcat.apache.org/
30. To create the first JSP page, write some HTML
code as given below, and save it by .jsp
extension. We have saved this file as index.jsp.
Put it in a folder and paste the folder in the web-
apps directory in apache tomcat to run the JSP
page.
index.jsp
◦ Let's see the simple example of JSP where we are using
the scriptlet tag to put Java code in the JSP page. We will
learn scriptlet tag later.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
It will print 10 on the browser.
31. In this section we will discuss about the elements
of JSP.
Structure of JSP Page :
JSPs are comprised of standard HTML tags and JSP
tags. The structure of JavaServer pages are simple
and easily handled by the servlet engine. In
addition to HTML ,you can categorize JSPs as
following -
◦ Directives
◦ Declarations
◦ Scriptlets
◦ Comments
◦ Expressions
32. Directives :
◦ A directives tag always appears at the top of your JSP file. It is
global definition sent to the JSP engine. Directives contain
special processing instructions for the web container. You
can import packages, define error handling pages or the
session information of the JSP page. Directives are defined by
using <%@ and %> tags.
Syntax -
<%@ directive attribute="value" %>
Declarations :
◦ This tag is used for defining the functions and variables to be
used in the JSP. This element of JSPs contains the java
variables and methods which you can call in expression block
of JSP page. Declarations are defined by using <%! and %>
tags. Whatever you declare within these tags will be visible to
the rest of the page.
Syntax -
<%! declaration(s) %>
33. Scriptlets:
◦ In this tag we can insert any amount of valid java code and these codes are
placed in _jspService method by the JSP engine. Scriptlets can be used
anywhere in the page. Scriptlets are defined by using <% and %> tags.
Syntax -
<% Scriptlets%>
Comments :
◦ Comments help in understanding what is actually code doing. JSPs provides
two types of comments for putting comment in your page. First type of
comment is for output comment which is appeared in the output stream on the
browser. It is written by using the <!-- and --> tags.
Syntax -
<!-- comment text -->
◦ Second type of comment is not delivered to the browser. It is written by using
the <%-- and --%> tags.
Syntax -
<%-- comment text --%>
Expressions :
◦ Expressions in JSPs is used to output any data on the generated Zpage. These
data are automatically converted to string and printed on the output stream. It
is an instruction to the web container for executing the code with in the
expression and replace it with the resultant output content. For writing
expression in JSP, you can use <%= and %> tags.
Syntax -
<%= expression %>
34. The jsp directives are messages that tells the
web container how to translate a JSP page into
the corresponding servlet.
There are three types of directives:
◦ page directive
◦ include directive
◦ taglib directive
Syntax of JSP Directive
◦ <%@ directive attribute="value" %>
JSP page directive
◦ The page directive defines attributes that apply to an
entire JSP page.
◦ Syntax of JSP page directive
<%@ page attribute="value" %>
◦
36. 1)import
◦ The import attribute is used to import class,interface
or all the members of a package.It is similar to import
keyword in java class or interface.Example of import
attribute
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
2)contentType
◦ The contentType attribute defines the
MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is
"text/html;charset=ISO-8859-1".
37. ◦ Example of contentType attribute
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
3)extends
◦ The extends attribute defines the parent class that will
be inherited by the generated servlet.It is rarely used.
4)info
◦ This attribute simply sets the information of the JSP
page which is retrieved later by using getServletInfo()
method of Servlet interface.
38. Example of info attribute
<html>
<body>
<%@ page info="composed by Sonoo Jaiswal" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
◦ The web container will create a method getServletInfo() in
the resulting servlet.For example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}
39. 5)buffer
◦ The buffer attribute sets the buffer size in kilobytes to
handle output generated by the JSP page.The default size of
the buffer is 8Kb.
◦ Example of buffer attribute
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
6)language
◦ The language attribute specifies the scripting language used
in the JSP page. The default value is "java".
7)isELIgnored
◦ We can ignore the Expression Language (EL) in jsp by the
isELIgnored attribute. By default its value is false i.e.
Expression Language is enabled by default. We see
Expression Language later.
◦ <%@ page isELIgnored="true" %>//Now EL will be ignored
40. 9)errorPage
◦ The errorPage attribute is used to define the error page, if
exception occurs in the current page, it will be redirected to
the error page.
Example of errorPage attribute
//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>
10)isErrorPage
◦ The isErrorPage attribute is used to declare that the current
page is the error page.
◦ Note: The exception object can only be used in the error
page.
41. Example of isErrorPage attribute
//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
Jsp Include Directive
◦ The include directive is used to include the contents of
any resource it may be jsp file, html file or text file. The
include directive includes the original content of the
included resource at page translation time (the jsp page
is translated only once so it will be better to include
static resource).
42. Advantage of Include directive
◦ Code Reusability
Syntax of include directive
<%@ include file="resourceName" %>
Example of include directive
◦ In this example, we are including the content of the
header.html file. To run this example you must create an
header.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Note: The include directive includes the original
content, so the actual page size grows at runtime.
43. JSP Taglib directive
◦ The JSP taglib directive is used to define a tag library that
defines many tags. We use the TLD (Tag Library Descriptor)
file to define the tags. In the custom tag section we will use
this tag so it will be better to learn it in custom tag.
◦ Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
◦ Example of JSP Taglib directive
◦ In this example, we are using our tag named currentDate. To
use this tag we must specify the taglib directive so the
container may get information about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag"
%>
<mytag:currentDate/>
</body>
</html>
44. In JSP, java code can be written inside the jsp
page using the scriptlet tag. Let's see what are
the scripting elements first.
JSP Scripting elements
◦ The scripting elements provides the ability to insert java
code inside the jsp. There are three types of scripting
elements:
◦ scriptlet tag
◦ expression tag
◦ declaration tag
JSP scriptlet tag
◦ A scriptlet tag is used to execute java source code in
JSP. Syntax is as follows:
<% java source code %>
45. Example of JSP scriptlet tag
◦ In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user
name
◦ In this example, we have created two files index.html
and welcome.jsp. The index.html file gets the
username from the user and the welcome.jsp file prints
the username with the welcome message.
◦ File: index.html
47. JSP expression tag
◦ The code placed within JSP expression tag is written to
the output stream of the response. So you need not
write out.print() to write data. It is mainly used to print
the values of variable or method.
◦ Syntax of JSP expression tag
<%= statement %>
◦ Example of JSP expression tag
◦ In this example of jsp expression tag, we are simply
displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
◦ Note: Do not end your statement with semicolon in case
of expression tag.
48. Example of JSP expression tag that prints current
time
◦ To display the current time, we have used the getTime()
method of Calendar class. The getTime() is an instance
method of Calendar class, so we have called it after getting
the instance of Calendar class by the getInstance() method.
◦ index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %
>
</body>
</html>
Example of JSP expression tag that prints the user
name
◦ In this example, we are printing the username using the
expression tag. The index.html file gets the username and
sends the request to the welcome.jsp file, which displays the
username.
◦ File: index.jsp
50. JSP Declaration Tag
◦ The JSP declaration tag is used to declare fields and
methods.
◦ The code written inside the jsp declaration tag is
placed outside the service() method of auto generated
servlet.
◦ So it doesn't get memory at each request.
Syntax of JSP declaration tag
◦ The syntax of the declaration tag is as follows:
<%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration
tag
Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare
variables not methods.
The jsp declaration tag can declare
variables as well as methods.
The declaration of scriptlet tag is
placed inside the _jspService()
The declaration of jsp declaration tag
is placed outside the _jspService()
51. Example of JSP declaration tag that declares field
◦ In this example of JSP declaration tag, we are declaring
the field and printing the value of the declared field
using the jsp expression tag.
◦ index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares
method
◦ In this example of JSP declaration tag, we are defining
the method which returns the cube of given number and
calling this method from the jsp expression tag. But we
can also use jsp scriptlet tag to call the declared
method.