SlideShare a Scribd company logo
1 of 52
Download to read offline
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
 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.
◦ 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.
 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.
 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
 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.
 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.
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.
 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
◦ 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()
 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.
◦ 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.
 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()
 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());
}
 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);
 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
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
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)
 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();
 Methods of ServletOutputStream class
◦ The ServletOutputStream class provides print() and
println() methods that are overloaded.
 void print(boolean b){}
 void print(char c){}
 void print(int i){}
 void print(long l){}
 void print(float f){}
 void print(double d){}
 void print(String s){}
 void println{}
 void println(boolean b){}
 void println(char c){}
 void println(int i){}
 void println(long l){}
 void println(float f){}
 void println(double d){}
 void println(String s){}
 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>
 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();
}
}
 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.
 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.
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.
 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.
◦ 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.
 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.
 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/
 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.
 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
 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) %>
 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 %>
 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" %>
◦
 Attributes of JSP page directive
◦ import
◦ contentType
◦ extends
◦ info
◦ buffer
◦ language
◦ isELIgnored
◦ isThreadSafe
◦ autoFlush
◦ session
◦ pageEncoding
◦ errorPage
◦ isErrorPage
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".
◦ 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.
 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";
}
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
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.
 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).
 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.
 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>
 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 %>
 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

<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
 File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
 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.
 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
html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
 File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
 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()
 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.
 index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

More Related Content

Similar to Advanced Java Servlet Programming

Similar to Advanced Java Servlet Programming (20)

Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
Liit tyit sem 5 enterprise java unit 1 notes 2018
Liit tyit sem 5 enterprise java  unit 1 notes 2018 Liit tyit sem 5 enterprise java  unit 1 notes 2018
Liit tyit sem 5 enterprise java unit 1 notes 2018
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Servlets
ServletsServlets
Servlets
 
Servlets
ServletsServlets
Servlets
 
J servlets
J servletsJ servlets
J servlets
 
Java servlets
Java servletsJava servlets
Java servlets
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Integrating Servlets and JSP (The MVC Architecture)
Integrating Servlets and JSP  (The MVC Architecture)Integrating Servlets and JSP  (The MVC Architecture)
Integrating Servlets and JSP (The MVC Architecture)
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
servlet_lifecycle.pdf
servlet_lifecycle.pdfservlet_lifecycle.pdf
servlet_lifecycle.pdf
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Servlet and Servlet Life Cycle
Servlet and Servlet Life CycleServlet and Servlet Life Cycle
Servlet and Servlet Life Cycle
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Servlet and JSP
Servlet and JSPServlet and JSP
Servlet and JSP
 

More from KALAISELVI P

ADV JAVA UNIT 2 M.SC CS (1).pdf
ADV JAVA UNIT 2 M.SC CS (1).pdfADV JAVA UNIT 2 M.SC CS (1).pdf
ADV JAVA UNIT 2 M.SC CS (1).pdfKALAISELVI P
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc csKALAISELVI P
 
Pks ms access unit 4_bcomcs
Pks ms access unit 4_bcomcsPks ms access unit 4_bcomcs
Pks ms access unit 4_bcomcsKALAISELVI P
 
Pks ms powerpointl unit 3_bcomcs
Pks ms powerpointl unit 3_bcomcsPks ms powerpointl unit 3_bcomcs
Pks ms powerpointl unit 3_bcomcsKALAISELVI P
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)KALAISELVI P
 
Pks ms excel unit 2_bcomcs
Pks ms excel unit 2_bcomcsPks ms excel unit 2_bcomcs
Pks ms excel unit 2_bcomcsKALAISELVI P
 
Pks ms word unit 1_bcomcs
Pks ms word unit 1_bcomcsPks ms word unit 1_bcomcs
Pks ms word unit 1_bcomcsKALAISELVI P
 

More from KALAISELVI P (9)

ADV JAVA UNIT 2 M.SC CS (1).pdf
ADV JAVA UNIT 2 M.SC CS (1).pdfADV JAVA UNIT 2 M.SC CS (1).pdf
ADV JAVA UNIT 2 M.SC CS (1).pdf
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
Pks ms access unit 4_bcomcs
Pks ms access unit 4_bcomcsPks ms access unit 4_bcomcs
Pks ms access unit 4_bcomcs
 
Pks ms powerpointl unit 3_bcomcs
Pks ms powerpointl unit 3_bcomcsPks ms powerpointl unit 3_bcomcs
Pks ms powerpointl unit 3_bcomcs
 
Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)
 
Pks ms excel unit 2_bcomcs
Pks ms excel unit 2_bcomcsPks ms excel unit 2_bcomcs
Pks ms excel unit 2_bcomcs
 
Pks ms word unit 1_bcomcs
Pks ms word unit 1_bcomcsPks ms word unit 1_bcomcs
Pks ms word unit 1_bcomcs
 

Recently uploaded

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 

Recently uploaded (20)

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 

Advanced Java Servlet Programming

  • 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();
  • 20.  Methods of ServletOutputStream class ◦ The ServletOutputStream class provides print() and println() methods that are overloaded.  void print(boolean b){}  void print(char c){}  void print(int i){}  void print(long l){}  void print(float f){}  void print(double d){}  void print(String s){}  void println{}  void println(boolean b){}  void println(char c){}  void println(int i){}  void println(long l){}  void println(float f){}  void println(double d){}  void println(String s){}
  • 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" %> ◦
  • 35.  Attributes of JSP page directive ◦ import ◦ contentType ◦ extends ◦ info ◦ buffer ◦ language ◦ isELIgnored ◦ isThreadSafe ◦ autoFlush ◦ session ◦ pageEncoding ◦ errorPage ◦ isErrorPage
  • 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 
  • 46. <html> <body> <form action="welcome.jsp"> <input type="text" name="uname"> <input type="submit" value="go"><br/> </form> </body> </html>  File: welcome.jsp <html> <body> <% String name=request.getParameter("uname"); out.print("welcome "+name); %> </form> </body> </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
  • 49. html> <body> <form action="welcome.jsp"> <input type="text" name="uname"><br/> <input type="submit" value="go"> </form> </body> </html>  File: welcome.jsp <html> <body> <%= "Welcome "+request.getParameter("uname") %> </body> </html>
  • 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.
  • 52.  index.jsp <html> <body> <%! int cube(int n){ return n*n*n*; } %> <%= "Cube of 3 is:"+cube(3) %> </body> </html>