SlideShare a Scribd company logo
1 of 79
ADVANCED JAVA
PCC-CSE-306G
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD
1
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
2
Course Outcomes:
1. Knowledge of the structure and model of the Java
programming language, (knowledge)
2. 2. Use the Java programming language for various
programming technologies (understanding)
3. 3. Develop software in the Java programming language.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
UNIT-I
SERVLET
• Servlets are the Java programs that runs on the Java-enabled web server or
application server. They are used to handle the request obtained from the web
server, process the request, produce the response, then send response back to the
webserver.
Properties of Servlets :
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from web server.
Execution of Servlets :
Execution of Servlets involves six basic steps:
• The clients send the request to the web server.
• The web server receives the request.
• The web server passes the request to the corresponding servlet.
• The servlet processes the request and generates the response in the form of output.
• The servlet sends the response back to the web server.
• The web server sends the response back to the client and the client browser displays
it on the screen.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
4
UNIT-I
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.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
5
UNIT-I
SERVLET
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
6
SERVLET API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.
The javax.servlet package contains many interfaces and classes that are used by the
servlet or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for
http requests only.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
7
SERVLET API
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
• Servlet
• ServletRequest
• ServletResponse
• RequestDispatcher
• ServletConfig
• ServletContext
• SingleThreadModel
• Filter
• FilterConfig
• FilterChain
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
8
SERVLET INTERFACE
Servlet interface provides common behavior to all the servlets. Servlet
interface defines methods that all servlets must implement. It provides 3 life cycle
methods that are used to initialize the servlet, to service the requests, and to destroy
the servlet and 2 non-life cycle methods.
A generic servlet is a protocol independent Servlet that should always override the
service() method to handle the client request. The service() method accepts two
arguments ServletRequest object and ServletResponse object.
The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace
etc.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
9
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
• public void service(ServletRequest req,ServletResponse res) dispatches the request
to the protected service method by converting the request and response object into
http type.
• protected void service(HttpServletRequest req, HttpServletResponse res) receives
the request from the service method, and dispatches the request to the doXXX()
method depending on the incoming http request type.
• protected void doGet(HttpServletRequest req, HttpServletResponse res) handles
the GET request. It is invoked by the web container.
• protected void doPost(HttpServletRequest req, HttpServletResponse res) handles
the POST request. It is invoked by the web container.
• protected void doHead(HttpServletRequest req, HttpServletResponse res) handles
the HEAD request. It is invoked by the web container.
.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
0
LIFE CYCLE OF SERVLET
A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
1
LIFE CYCLE OF SERVLET
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
2
LIFE CYCLE OF SERVLET
The web container maintains the life cycle of a servlet instance
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
3
LIFE CYCLE OF SERVLET
The web container maintains the life cycle of a servlet instance
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
• As displayed in the previous slide diagram, there are three states of a servlet: new,
ready and end. The servlet is in new state if servlet instance is created. After invoking
the init() method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks. When the web container invokes the destroy() method, it
shifts to the end state.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
4
LIFE CYCLE OF SERVLET
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when
the first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
3) init() method
The init() Method
The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as
with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
5
LIFE CYCLE OF SERVLET
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException { // Initialization code... }
The service() Method
The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException { }
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
6
LIFE CYCLE OF SERVLET
destroy method is invoked
The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:
public void destroy()
ServletConfig is an object containing some initial parameters
or configuration information created by Servlet Container and passed to
the servlet during initialization. ServletConfig is for a particular servlet, that means one
should store servlet specific information in web.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
7
Servlet Collaboration
The exchange of information among servlets of a particular Java web application is
known as Servlet Collaboration. This enables passing/sharing information from
one servlet to the other through method invocations.
Ways of Servlet Collaboration
• Using RequestDispatcher include() and forward() method
• Using HTTPServletResponse sendRedirect() method
• Using ServletContext setAttribute() and getAttribute() methods
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
1
8
Servlet Collaboration
Methods of RequestDispatcher interface
The RequestDispatcher interface provides two methods. They are:
public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to another
resource (servlet, JSP file, or HTML file) on the server.
public void include(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP
page, or HTML file) in the response.
19
• As you see in the above figure, response of
second servlet is sent to the client. Response
of the first servlet is not displayed to the user.
20
21
• As you can see in the above figure, response
of second servlet is included in the response
of the first servlet that is being sent to the
client.
22
Example of RequestDispatcher
interface
• In this example, we are validating the password entered by the user.
If password is servlet, it will forward the request to the
WelcomeServlet, otherwise will show an error message: sorry
username or password error!. In this program, we are cheking for
hardcoded information. But you can check it to the database also
that we will see in the development chapter. In this example, we
have created following files:
• index.html file: for getting input from the user.
• Login.java file: a servlet class for processing the response. If
password is servet, it will forward the request to the welcome
servlet.
• WelcomeServlet.java file: a servlet class for displaying the welcome
message.
• web.xml file: a deployment descriptor file that contains the
information about the servlet.
23
24
25
26
27
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
2
8
Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one of the
following scopes:
• request scope
• session scope
• application scope
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
2
9
Attribute in Servlet
1.There are following 4 attribute specific methods. They are as
follows:public void setAttribute(String name,Object object):sets the
given object in the application scope.
2.public Object getAttribute(String name):Returns the attribute for
the specified name.
3.public Enumeration getInitParameterNames():Returns the names
of the context's initialization parameters as an Enumeration of String
objects.
4.public void removeAttribute(String name):Removes the attribute
with the given name from the servlet context.
Attribute specific methods of ServletRequest, HttpSession and ServletContext interface
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
0
CRUD in Servlet
A CRUD (Create, Read, Update and Delete) application is the most important application
for any project development. In Servlet, we can easily create CRUD application.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
1
CRUD in Servlet
Create "user905" table in Oracle Database with auto incrementing id using sequence.
There are 5 fields in it: id, name, password, email and country.
Programming to be done on compiler
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
2
Annotation
In the Java computer programming language, an annotation is a form of syntactic
metadata that can be added to Java source code. Like Javadoc tags, Java
annotations can be read from source files. Unlike Javadoc tags, Java annotations can
also be embedded in and read from Java class files generated by the Java compiler.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
3
SSI
All the servlets you've seen so far generate full HTML pages. If this were all that servlets
could do, it would still be plenty. Servlets, however, can also be embedded inside HTML
pages with something called server-side include (SSI)functionality. In many servers that
support servlets, a page can be preprocessed by the server to include output from
servlets at certain points inside the page. The tags used for a server-side include look
similar to those used for applets. Currently, the tag syntax varies across server
implementations. This section describes the syntax appropriate for the Java Web
Server. If you see this text, it means that the web server providing this page does not
support the SERVLET tag. docstore.mik.ua/orelly/java-ent/servlet/ch02_04.htm.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
4
LIFECYCLE OF JSP
A JSP life cycle is defined as the process from its creation till the destruction. This is
similar to a servlet life cycle with an additional step which is required to compile a JSP
into servlet.
Paths Followed By JSP
The following are the paths followed by a JSP −
• Compilation
• Initialization
• Execution
• Cleanup
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
5
LIFECYCLE OF JSP
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
6
LIFECYCLE OF JSP
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The
four phases have been described below −
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps −
• Parsing the JSP.
• Turning the JSP into a servlet.
• Compiling the servlet.
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override
the jspInit() method −
public void jspInit(){ // Initialization code... }
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
7
LIFECYCLE OF JSP
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the
JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as
its parameters as follows −
void _jspService(HttpServletRequest request, HttpServletResponse response) { //
Service handling code... }
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup, such as releasing
database connections or closing open files.
The jspDestroy() method has the following form −
public void jspDestroy() { // Your cleanup code goes here. }
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
3
8
The JSP API consists of two packages:
• javax.servlet.jsp
• javax.servlet.jsp.tagext
The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as
follows:
• JspPage
• HttpJspPage
JSP Scriptlet tag (Scripting elements)
• JSP Scriptlet tag (Scripting elements)
• 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
39
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>
40
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>
41
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>
42
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>
43
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 %>
44
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()
method.
The declaration of jsp declaration
tag is placed outside the
_jspService() method.
45
Difference between JSP Scriptlet tag and Declaration tag
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>
46
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
4
7
JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are
processed by the JSP engine during translation of the JSP page. Any other text in the
JSP page is considered as HTML code or plain text.
Example:
<html>
<head>
<title>
My First JSP Page
</title>
</head>
<% int count = 0; %>
<body> Page Count is <% out.println(++count); %> </body> </html>
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
4
8
Implicit Objects
These Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being
explicitly declared. JSP Implicit Objects are also called pre-defined variables. There
are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
4
9
S.No. Object & Description
1
request
This is the HttpServletRequest object associated with the request.
2
response
This is the HttpServletResponse object associated with the response to the client.
3
out
This is the PrintWriter object used to send output to the client.
4
session
This is the HttpSession object associated with the request.
5
application
This is the ServletContext object associated with the application context.
6
config
This is the ServletConfig object associated with the page.
7
pageContext
This encapsulates use of server-specific features like higher performance JspWriters.
8
page
This is simply a synonym for this, and is used to call the methods defined by the translated servlet class.
9
Exception
The Exception object allows the exception data to be accessed by designated JSP.
Following table lists out the nine Implicit Objects that JSP supports −
The request Object
• The request object is an instance of
a javax.servlet.http.HttpServletRequest object. Each time a client
requests a page the JSP engine creates a new object to represent that
request.
• The request object provides methods to get the HTTP header information
including form data, cookies, HTTP methods etc.
The response Object
• The response object is an instance of
a javax.servlet.http.HttpServletResponse object. Just as the server
creates the request object, it also creates an object to represent the
response to the client.
• The response object also defines the interfaces that deal with creating
new HTTP headers. Through this object the JSP programmer can add new
cookies or date stamps, HTTP status codes, etc.
50
The out Object
• The out implicit object is an instance of
a javax.servlet.jsp.JspWriter object and is used to send content in a
response.
• The initial JspWriter object is instantiated differently depending on
whether the page is buffered or not. Buffering can be easily turned
off by using the buffered = 'false' attribute of the page directive.
• The JspWriter object contains most of the same methods as
the java.io.PrintWriter class. However, JspWriter has some
additional methods designed to deal with buffering. Unlike the
PrintWriter object, JspWriter throws IOExceptions.
• Following table lists out the important methods that we will use to
write boolean char, int, double, object, String, etc.
51
The session Object
• The session object is an instance
of javax.servlet.http.HttpSession and behaves exactly the same
way that session objects behave under Java Servlets.
The application Object
• The application object is direct wrapper around
the ServletContext object for the generated Servlet and in reality
an instance of a javax.servlet.ServletContext object.
• This object is a representation of the JSP page through its entire
lifecycle. This object is created when the JSP page is initialized and
will be removed when the JSP page is removed by
the jspDestroy() method.
• By adding an attribute to application, you can ensure that all JSP
files that make up your web application have access to it.
52
The config Object
• The config object is an instantiation of javax.servlet.ServletConfig and is a direct
wrapper around the ServletConfig object for the generated servlet.
• This object allows the JSP programmer access to the Servlet or JSP engine
initialization parameters such as the paths or file locations etc.
• The following config method is the only one you might ever use, and its usage is
trivial −
• config.getServletName(); This returns the servlet name, which is the string
contained in the <servlet-name> element defined in the WEB-INFweb.xml file.
The pageContext Object
• The pageContext object is an instance of a javax.servlet.jsp.PageContext object.
The pageContext object is used to represent the entire JSP page.
• This object is intended as a means to access information about the page while
avoiding most of the implementation details.
• This object stores references to the request and response objects for each request.
The application, config, session, and out objects are derived by accessing
attributes of this object.
53
• The pageContext object also contains information about the directives issued to the JSP page,
including the buffering information, the errorPageURL, and page scope.
• The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more
than 40 methods, about half of which are inherited from the javax.servlet.jsp.JspContext class.
• One of the important methods is removeAttribute. This method accepts either one or two
arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from
all scopes, while the following code only removes it from the page scope −
• pageContext.removeAttribute("attrName", PAGE_SCOPE);
The page Object
• This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
• The page object is really a direct synonym for the this object.
• The exception Object
• The exception object is a wrapper containing the exception thrown from the previous page. It is
typically used to generate an appropriate response to the error condition.
54
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
5
5
jsp directives
These are messages that tells the web container how to translate a JSP page into the
corresponding servlet. These directives provide directions and instructions to the
container, telling it how to handle certain aspects of the JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the
following form −
<%@ directive attribute = "value" %>
There are three types of directives:
• page directive
• include directive
• taglib directive
• Syntax:-
<%@ directive attribute="value" %>
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
5
6
jsp directives
Directives can have a number of attributes which you can list down as key-
value pairs and separated by commas.
The blanks between the @ symbol and the directive name, and between the
last attribute and the closing %>, are optional.
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
5
7
jsp directives
Directives can have a number of attributes which you can list down as key-
value pairs and separated by commas.
The blanks between the @ symbol and the directive name, and between the
last attribute and the closing %>, are optional.
S.N
o.
Directive & Description
1
<%@ page ... %>
Defines page-dependent attributes, such as scripting
language, error page, and buffering requirements.
2
<%@ include ... %>
Includes a file during the translation phase.
3
<%@ taglib ... %>
Declares a tag library, containing custom actions, used in
the page
There are three types of directive tag−
JSP - The page Directive
• The page directive is used to provide instructions to
the container. These instructions pertain to the current
JSP page. You may code page directives anywhere in
your JSP page. By convention, page directives are
coded at the top of the JSP page.
Following is the basic syntax of the page directive −
• <%@ page attribute = "value" %> You can write the
XML equivalent of the above syntax as follows −
• <jsp:directive.page attribute = "value" />
58
The include Directive
• The include directive is used to include a file during the translation
phase. This directive tells the container to merge the content of
other external files with the current JSP during the translation
phase. You may code the include directives anywhere in your JSP
page.
• The general usage form of this directive is as follows −
• <%@ include file = "relative url" > The filename in the include
directive is actually a relative URL. If you just specify a filename with
no associated path, the JSP compiler assumes that the file is in the
same directory as your JSP.
• You can write the XML equivalent of the above syntax as follows −
• <jsp:directive.include file = "relative url" />
59
The taglib Directive
• The JavaServer Pages API allow you to define custom
JSP tags that look like HTML or XML tags and a tag
library is a set of user-defined tags that implement
custom behavior.
• The taglib directive declares that your JSP page uses a
set of custom tags, identifies the location of the library,
and provides means for identifying the custom tags in
your JSP page.
• The taglib directive follows the syntax given below −
• <%@ taglib uri="uri" prefix = "prefixOfTag" >
60
Exception
In JSP, exception is an implicit object of type java.lang.Throwable class.
This object can be used to print the exception. But it can only be used
in error pages.It is better to learn it after page directive. Let's see a
simple example:
error.jsp
• <%@ page isErrorPage="true" %>
• <html>
• <body>
•
• Sorry following exception occured:<%= exception %>
•
• </body>
• </html>
61
Faculty : Dr. Ashima Mehta Date:
Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT-
6
2
JSP specification provides Standard(Action) tags for use within your JSP pages.
These tags are used to remove or eliminate scriptlet code from your JSP page because
scriplet code are technically not recommended nowadays.
It's considered to be bad practice to put java code directly inside your JSP page.
Standard tags begin with the jsp: prefix. There are many JSP Standard Action tag which
are used to perform some specific task.
Action Tag Description
jsp:forward forward the request to a
new page
Usage : <jsp:forward
page="Relative URL" />
jsp:useBean instantiates a JavaBean
Usage : <jsp:useBean
id="beanId" />
jsp:getProperty retrieves a property from a
JavaBean instance.
The following are some JSP Standard Action Tags available:
Expression Language (EL) in JSP
The Expression Language (EL) simplifies the
accessibility of data stored in the Java Bean
component, and other objects like request, session,
application etc.
• There are many implicit objects, operators and
reserve words in EL.
• It is the newly added feature in JSP technology
version 2.0.
Syntax for Expression Language (EL)
• ${ expression }
63
Implicit Objects Usage
pageScope it maps the given attribute name with the value set in the page scope
requestScope it maps the given attribute name with the value set in the request
scope
sessionScope it maps the given attribute name with the value set in the session
scope
applicationScope it maps the given attribute name with the value set in the application
scope
param it maps the request parameter to the single value
paramValues it maps the request parameter to an array of values
header it maps the request header name to the single value
headerValues it maps the request header name to an array of values
cookie it maps the given cookie name to the cookie value
initParam it maps the initialization parameter
pageContext it provides access to many objects request, session etc.
64
MVC in JSP
• MVC stands for Model View and Controller. It is
a design pattern that separates the business
logic, presentation logic and data.
• Controller acts as an interface between View and
Model. Controller intercepts all the incoming
requests.
• Model represents the state of the application i.e.
data. It can also have business logic.
• View represents the presentaion i.e. UI(User
Interface).
65
Advantage of MVC (Model 2) Architecture
• Navigation Control is centralized
• Easy to maintain the large application
66
67
JSTL (JSP Standard Tag Library)
• The JSP Standard Tag Library (JSTL) represents a
set of tags to simplify the JSP development.
• Advantage of JSTL
• Fast Development JSTL provides many tags that
simplify the JSP.
• Code Reusability We can use the JSTL tags on
various pages.
• No need to use scriptlet tag It avoids the use of
scriptlet tag.
68
Tag Name Description
Core tags The JSTL core tag provide variable support, URL management,
flow control, etc. The URL for the core tag
is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c.
Function tags The functions tags provide support for string manipulation and
string length. The URL for the functions tags
is http://java.sun.com/jsp/jstl/functions and prefix is fn.
Formatting tags The Formatting tags provide support for message formatting,
number and date formatting, etc. The URL for the Formatting tags
is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
XML tags The XML tags provide flow control, transformation, etc. The URL
for the XML tags is http://java.sun.com/jsp/jstl/xml and prefix
is x.
SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL
tags is http://java.sun.com/jsp/jstl/sql and prefix is sql.
69
es of tags:
Custom Tags in JSP
Custom tags are user-defined tags. They eliminates the possibility of scriptlet
tag and separates the business logic from the JSP page.
• The same business logic can be used many times by the use of custom tag.
• Advantages of Custom Tags
• The key advantages of Custom tags are as follows:
• Eliminates the need of scriptlet tag The custom tags eliminates the need
of scriptlet tag which is considered bad programming approach in JSP.
• Separation of business logic from JSP The custom tags separate the the
business logic from the JSP page so that it may be easy to maintain.
• Re-usability The custom tags makes the possibility to reuse the same
business logic again and again.
•
70
• import javax.servlet.jsp.tagext.*;
• import javax.servlet.jsp.*;
• import java.io.*;
• public class HelloTag extends SimpleTagSupport
• { public void doTag() throws JspException,
IOException
• { JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!"); } }
71
• Let us compile the above class and copy it in a
directory available in the environment variable
CLASSPATH. Finally, create the following tag
library file: <Tomcat-Installation-
Directory>webappsROOTWEB-INFcustom.tld.
• <taglib> <tlib-version>1.0</tlib-version> <jsp-
version>2.0</jsp-version> <short-name>Example
TLD</short-name> <tag> <name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-
class> <body-content>empty</body-content>
</tag> </taglib>
72
• <%@ taglib prefix = "ex" uri = "WEB-
INF/custom.tld"%>
• <html>
<head>
<title>A sample custom tag</title>
</head>
<body> <ex:Hello/>
</body> </html>
73
2nd Example of JSP Custom Tag
• In this example, we are going to create a custom tag that
prints the current date and time. We are performing action
at the start of tag.
• For creating any custom tag, we need to follow following
steps:
• Create the Tag handler class and perform action at the
start or at the end of the tag.
• Create the Tag Library Descriptor (TLD) file and define tags
• Create the JSP file that uses the Custom tag defined in the
TLD file
•
74
• Call the above JSP and this should produce the
following result −
Hello Custom Tag!
75
• MyTagHandler.java
• package com.javatpoint.sonoo;
• import java.util.Calendar;
• import javax.servlet.jsp.JspException;
• import javax.servlet.jsp.JspWriter;
• import javax.servlet.jsp.tagext.TagSupport;
• public class MyTagHandler extends TagSupport{
•
• public int doStartTag() throws JspException {
• JspWriter out=pageContext.getOut();//returns the instance of JspWriter
• try{
• out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter
• }catch(Exception e){System.out.println(e);}
• return SKIP_BODY;//will not evaluate the body content of the tag
• }
• }
76
• 2) Create the TLD file
• Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained inside the WEB-INF directory.
• File: mytags.tld
• <?xml version="1.0" encoding="ISO-8859-1" ?>
• <!DOCTYPE taglib
• PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
• "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
•
• <taglib>
•
• <tlib-version>1.0</tlib-version>
• <jsp-version>1.2</jsp-version>
• <short-name>simple</short-name>
• <uri>http://tomcat.apache.org/example-taglib</uri>
•
• <tag>
• <name>today</name>
• <tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>
• </tag>
• </taglib>
• 3) Create the JSP file
• Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended to use the uri name instead of full path of
tld file. We will learn about uri later.
• It uses taglib directive to use the tags defined in the tld file.
77
• File: index.jsp
• <%@ taglib uri="WEB-
INF/mytags.tld" prefix="m" %>
• Current Date and Time is: <m:today/>
78
79
Output

More Related Content

Similar to ajava unit 1.pptx

Similar to ajava unit 1.pptx (20)

Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdf
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
Servlet lifecycle
Servlet  lifecycleServlet  lifecycle
Servlet lifecycle
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet and Servlet Life Cycle
Servlet and Servlet Life CycleServlet and Servlet Life Cycle
Servlet and Servlet Life Cycle
 
Major project report
Major project reportMajor project report
Major project report
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
servlet in java
servlet in javaservlet in java
servlet in java
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servlets
ServletsServlets
Servlets
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
servlet_lifecycle.pdf
servlet_lifecycle.pdfservlet_lifecycle.pdf
servlet_lifecycle.pdf
 
LIFE CYCLE OF SERVLET
LIFE CYCLE OF SERVLETLIFE CYCLE OF SERVLET
LIFE CYCLE OF SERVLET
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
 
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
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
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
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
“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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
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
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
_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
 
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
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 

Recently uploaded (20)

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
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🔝
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
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
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
“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...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
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
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
_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
 
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
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 

ajava unit 1.pptx

  • 1. ADVANCED JAVA PCC-CSE-306G Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD 1
  • 2. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 2 Course Outcomes: 1. Knowledge of the structure and model of the Java programming language, (knowledge) 2. 2. Use the Java programming language for various programming technologies (understanding) 3. 3. Develop software in the Java programming language.
  • 3. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 UNIT-I SERVLET • Servlets are the Java programs that runs on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, then send response back to the webserver. Properties of Servlets : • Servlets work on the server-side. • Servlets are capable of handling complex requests obtained from web server. Execution of Servlets : Execution of Servlets involves six basic steps: • The clients send the request to the web server. • The web server receives the request. • The web server passes the request to the corresponding servlet. • The servlet processes the request and generates the response in the form of output. • The servlet sends the response back to the web server. • The web server sends the response back to the client and the client browser displays it on the screen.
  • 4. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 4 UNIT-I 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.
  • 5. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 5 UNIT-I SERVLET
  • 6. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 6 SERVLET API The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol. The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
  • 7. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 7 SERVLET API Interfaces in javax.servlet package There are many interfaces in javax.servlet package. They are as follows: • Servlet • ServletRequest • ServletResponse • RequestDispatcher • ServletConfig • ServletContext • SingleThreadModel • Filter • FilterConfig • FilterChain • ServletRequestListener • ServletRequestAttributeListener • ServletContextListener • ServletContextAttributeListener
  • 8. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 8 SERVLET INTERFACE Servlet interface provides common behavior to all the servlets. Servlet interface defines methods that all servlets must implement. It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods. A generic servlet is a protocol independent Servlet that should always override the service() method to handle the client request. The service() method accepts two arguments ServletRequest object and ServletResponse object. The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
  • 9. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 9 Methods of HttpServlet class There are many methods in HttpServlet class. They are as follows: • public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type. • protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type. • protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container. • protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container. • protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container. .
  • 10. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 0 LIFE CYCLE OF SERVLET A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet. • The servlet is initialized by calling the init() method. • The servlet calls service() method to process a client's request. • The servlet is terminated by calling the destroy() method. • Finally, servlet is garbage collected by the garbage collector of the JVM.
  • 11. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 1 LIFE CYCLE OF SERVLET
  • 12. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 2 LIFE CYCLE OF SERVLET The web container maintains the life cycle of a servlet instance • Servlet class is loaded. • Servlet instance is created. • init method is invoked. • service method is invoked. • destroy method is invoked.
  • 13. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 3 LIFE CYCLE OF SERVLET The web container maintains the life cycle of a servlet instance • Servlet class is loaded. • Servlet instance is created. • init method is invoked. • service method is invoked. • destroy method is invoked. • As displayed in the previous slide diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state.
  • 14. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 4 LIFE CYCLE OF SERVLET 1) Servlet class is loaded The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2) Servlet instance is created The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init() method The init() Method The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets. The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
  • 15. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 5 LIFE CYCLE OF SERVLET When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet. The init method definition looks like this − public void init() throws ServletException { // Initialization code... } The service() Method The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. Here is the signature of this method − public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { }
  • 16. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 6 LIFE CYCLE OF SERVLET destroy method is invoked The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below: public void destroy() ServletConfig is an object containing some initial parameters or configuration information created by Servlet Container and passed to the servlet during initialization. ServletConfig is for a particular servlet, that means one should store servlet specific information in web.
  • 17. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 7 Servlet Collaboration The exchange of information among servlets of a particular Java web application is known as Servlet Collaboration. This enables passing/sharing information from one servlet to the other through method invocations. Ways of Servlet Collaboration • Using RequestDispatcher include() and forward() method • Using HTTPServletResponse sendRedirect() method • Using ServletContext setAttribute() and getAttribute() methods
  • 18. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 1 8 Servlet Collaboration Methods of RequestDispatcher interface The RequestDispatcher interface provides two methods. They are: public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
  • 19. 19
  • 20. • As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user. 20
  • 21. 21
  • 22. • As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client. 22
  • 23. Example of RequestDispatcher interface • In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are cheking for hardcoded information. But you can check it to the database also that we will see in the development chapter. In this example, we have created following files: • index.html file: for getting input from the user. • Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet. • WelcomeServlet.java file: a servlet class for displaying the welcome message. • web.xml file: a deployment descriptor file that contains the information about the servlet. 23
  • 24. 24
  • 25. 25
  • 26. 26
  • 27. 27
  • 28. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 2 8 Attribute in Servlet An attribute in servlet is an object that can be set, get or removed from one of the following scopes: • request scope • session scope • application scope
  • 29. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 2 9 Attribute in Servlet 1.There are following 4 attribute specific methods. They are as follows:public void setAttribute(String name,Object object):sets the given object in the application scope. 2.public Object getAttribute(String name):Returns the attribute for the specified name. 3.public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. 4.public void removeAttribute(String name):Removes the attribute with the given name from the servlet context. Attribute specific methods of ServletRequest, HttpSession and ServletContext interface
  • 30. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 0 CRUD in Servlet A CRUD (Create, Read, Update and Delete) application is the most important application for any project development. In Servlet, we can easily create CRUD application.
  • 31. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 1 CRUD in Servlet Create "user905" table in Oracle Database with auto incrementing id using sequence. There are 5 fields in it: id, name, password, email and country. Programming to be done on compiler
  • 32. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 2 Annotation In the Java computer programming language, an annotation is a form of syntactic metadata that can be added to Java source code. Like Javadoc tags, Java annotations can be read from source files. Unlike Javadoc tags, Java annotations can also be embedded in and read from Java class files generated by the Java compiler.
  • 33. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 3 SSI All the servlets you've seen so far generate full HTML pages. If this were all that servlets could do, it would still be plenty. Servlets, however, can also be embedded inside HTML pages with something called server-side include (SSI)functionality. In many servers that support servlets, a page can be preprocessed by the server to include output from servlets at certain points inside the page. The tags used for a server-side include look similar to those used for applets. Currently, the tag syntax varies across server implementations. This section describes the syntax appropriate for the Java Web Server. If you see this text, it means that the web server providing this page does not support the SERVLET tag. docstore.mik.ua/orelly/java-ent/servlet/ch02_04.htm.
  • 34. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 4 LIFECYCLE OF JSP A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. Paths Followed By JSP The following are the paths followed by a JSP − • Compilation • Initialization • Execution • Cleanup
  • 35. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 5 LIFECYCLE OF JSP
  • 36. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 6 LIFECYCLE OF JSP The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four phases have been described below − JSP Compilation When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page. The compilation process involves three steps − • Parsing the JSP. • Turning the JSP into a servlet. • Compiling the servlet. JSP Initialization When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-specific initialization, override the jspInit() method − public void jspInit(){ // Initialization code... }
  • 37. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 7 LIFECYCLE OF JSP JSP Execution This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP. The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows − void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... } JSP Cleanup The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files. The jspDestroy() method has the following form − public void jspDestroy() { // Your cleanup code goes here. }
  • 38. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 3 8 The JSP API consists of two packages: • javax.servlet.jsp • javax.servlet.jsp.tagext The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as follows: • JspPage • HttpJspPage
  • 39. JSP Scriptlet tag (Scripting elements) • JSP Scriptlet tag (Scripting elements) • 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 39
  • 40. 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> 40
  • 41. 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> 41
  • 42. 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> 42
  • 43. 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> 43
  • 44. 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 %> 44
  • 45. 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() method. The declaration of jsp declaration tag is placed outside the _jspService() method. 45 Difference between JSP Scriptlet tag and Declaration tag
  • 46. 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> 46
  • 47. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 4 7 JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are processed by the JSP engine during translation of the JSP page. Any other text in the JSP page is considered as HTML code or plain text. Example: <html> <head> <title> My First JSP Page </title> </head> <% int count = 0; %> <body> Page Count is <% out.println(++count); %> </body> </html>
  • 48. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 4 8 Implicit Objects These Objects are the Java objects that the JSP Container makes available to the developers in each page and the developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables. There are 9 jsp implicit objects. These objects are created by the web container that are available to all the jsp pages. The available implicit objects are out, request, config, session, application etc.
  • 49. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 4 9 S.No. Object & Description 1 request This is the HttpServletRequest object associated with the request. 2 response This is the HttpServletResponse object associated with the response to the client. 3 out This is the PrintWriter object used to send output to the client. 4 session This is the HttpSession object associated with the request. 5 application This is the ServletContext object associated with the application context. 6 config This is the ServletConfig object associated with the page. 7 pageContext This encapsulates use of server-specific features like higher performance JspWriters. 8 page This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. 9 Exception The Exception object allows the exception data to be accessed by designated JSP. Following table lists out the nine Implicit Objects that JSP supports −
  • 50. The request Object • The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request. • The request object provides methods to get the HTTP header information including form data, cookies, HTTP methods etc. The response Object • The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client. • The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes, etc. 50
  • 51. The out Object • The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send content in a response. • The initial JspWriter object is instantiated differently depending on whether the page is buffered or not. Buffering can be easily turned off by using the buffered = 'false' attribute of the page directive. • The JspWriter object contains most of the same methods as the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions. • Following table lists out the important methods that we will use to write boolean char, int, double, object, String, etc. 51
  • 52. The session Object • The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same way that session objects behave under Java Servlets. The application Object • The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object. • This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method. • By adding an attribute to application, you can ensure that all JSP files that make up your web application have access to it. 52
  • 53. The config Object • The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet. • This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc. • The following config method is the only one you might ever use, and its usage is trivial − • config.getServletName(); This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEB-INFweb.xml file. The pageContext Object • The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to represent the entire JSP page. • This object is intended as a means to access information about the page while avoiding most of the implementation details. • This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object. 53
  • 54. • The pageContext object also contains information about the directives issued to the JSP page, including the buffering information, the errorPageURL, and page scope. • The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of which are inherited from the javax.servlet.jsp.JspContext class. • One of the important methods is removeAttribute. This method accepts either one or two arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from all scopes, while the following code only removes it from the page scope − • pageContext.removeAttribute("attrName", PAGE_SCOPE); The page Object • This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page. • The page object is really a direct synonym for the this object. • The exception Object • The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition. 54
  • 55. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 5 5 jsp directives These are messages that tells the web container how to translate a JSP page into the corresponding servlet. These directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form − <%@ directive attribute = "value" %> There are three types of directives: • page directive • include directive • taglib directive • Syntax:- <%@ directive attribute="value" %>
  • 56. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 5 6 jsp directives Directives can have a number of attributes which you can list down as key- value pairs and separated by commas. The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional.
  • 57. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 5 7 jsp directives Directives can have a number of attributes which you can list down as key- value pairs and separated by commas. The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional. S.N o. Directive & Description 1 <%@ page ... %> Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. 2 <%@ include ... %> Includes a file during the translation phase. 3 <%@ taglib ... %> Declares a tag library, containing custom actions, used in the page There are three types of directive tag−
  • 58. JSP - The page Directive • The page directive is used to provide instructions to the container. These instructions pertain to the current JSP page. You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page. Following is the basic syntax of the page directive − • <%@ page attribute = "value" %> You can write the XML equivalent of the above syntax as follows − • <jsp:directive.page attribute = "value" /> 58
  • 59. The include Directive • The include directive is used to include a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code the include directives anywhere in your JSP page. • The general usage form of this directive is as follows − • <%@ include file = "relative url" > The filename in the include directive is actually a relative URL. If you just specify a filename with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP. • You can write the XML equivalent of the above syntax as follows − • <jsp:directive.include file = "relative url" /> 59
  • 60. The taglib Directive • The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior. • The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides means for identifying the custom tags in your JSP page. • The taglib directive follows the syntax given below − • <%@ taglib uri="uri" prefix = "prefixOfTag" > 60
  • 61. Exception In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to print the exception. But it can only be used in error pages.It is better to learn it after page directive. Let's see a simple example: error.jsp • <%@ page isErrorPage="true" %> • <html> • <body> • • Sorry following exception occured:<%= exception %> • • </body> • </html> 61
  • 62. Faculty : Dr. Ashima Mehta Date: Branch & Semester : CSIT_VI SEM Subject with Code : CLOUD COMPUTING(PCC-IT- 6 2 JSP specification provides Standard(Action) tags for use within your JSP pages. These tags are used to remove or eliminate scriptlet code from your JSP page because scriplet code are technically not recommended nowadays. It's considered to be bad practice to put java code directly inside your JSP page. Standard tags begin with the jsp: prefix. There are many JSP Standard Action tag which are used to perform some specific task. Action Tag Description jsp:forward forward the request to a new page Usage : <jsp:forward page="Relative URL" /> jsp:useBean instantiates a JavaBean Usage : <jsp:useBean id="beanId" /> jsp:getProperty retrieves a property from a JavaBean instance. The following are some JSP Standard Action Tags available:
  • 63. Expression Language (EL) in JSP The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean component, and other objects like request, session, application etc. • There are many implicit objects, operators and reserve words in EL. • It is the newly added feature in JSP technology version 2.0. Syntax for Expression Language (EL) • ${ expression } 63
  • 64. Implicit Objects Usage pageScope it maps the given attribute name with the value set in the page scope requestScope it maps the given attribute name with the value set in the request scope sessionScope it maps the given attribute name with the value set in the session scope applicationScope it maps the given attribute name with the value set in the application scope param it maps the request parameter to the single value paramValues it maps the request parameter to an array of values header it maps the request header name to the single value headerValues it maps the request header name to an array of values cookie it maps the given cookie name to the cookie value initParam it maps the initialization parameter pageContext it provides access to many objects request, session etc. 64
  • 65. MVC in JSP • MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data. • Controller acts as an interface between View and Model. Controller intercepts all the incoming requests. • Model represents the state of the application i.e. data. It can also have business logic. • View represents the presentaion i.e. UI(User Interface). 65
  • 66. Advantage of MVC (Model 2) Architecture • Navigation Control is centralized • Easy to maintain the large application 66
  • 67. 67
  • 68. JSTL (JSP Standard Tag Library) • The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development. • Advantage of JSTL • Fast Development JSTL provides many tags that simplify the JSP. • Code Reusability We can use the JSTL tags on various pages. • No need to use scriptlet tag It avoids the use of scriptlet tag. 68
  • 69. Tag Name Description Core tags The JSTL core tag provide variable support, URL management, flow control, etc. The URL for the core tag is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c. Function tags The functions tags provide support for string manipulation and string length. The URL for the functions tags is http://java.sun.com/jsp/jstl/functions and prefix is fn. Formatting tags The Formatting tags provide support for message formatting, number and date formatting, etc. The URL for the Formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt. XML tags The XML tags provide flow control, transformation, etc. The URL for the XML tags is http://java.sun.com/jsp/jstl/xml and prefix is x. SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags is http://java.sun.com/jsp/jstl/sql and prefix is sql. 69 es of tags:
  • 70. Custom Tags in JSP Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates the business logic from the JSP page. • The same business logic can be used many times by the use of custom tag. • Advantages of Custom Tags • The key advantages of Custom tags are as follows: • Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet tag which is considered bad programming approach in JSP. • Separation of business logic from JSP The custom tags separate the the business logic from the JSP page so that it may be easy to maintain. • Re-usability The custom tags makes the possibility to reuse the same business logic again and again. • 70
  • 71. • import javax.servlet.jsp.tagext.*; • import javax.servlet.jsp.*; • import java.io.*; • public class HelloTag extends SimpleTagSupport • { public void doTag() throws JspException, IOException • { JspWriter out = getJspContext().getOut(); out.println("Hello Custom Tag!"); } } 71
  • 72. • Let us compile the above class and copy it in a directory available in the environment variable CLASSPATH. Finally, create the following tag library file: <Tomcat-Installation- Directory>webappsROOTWEB-INFcustom.tld. • <taglib> <tlib-version>1.0</tlib-version> <jsp- version>2.0</jsp-version> <short-name>Example TLD</short-name> <tag> <name>Hello</name> <tag-class>com.tutorialspoint.HelloTag</tag- class> <body-content>empty</body-content> </tag> </taglib> 72
  • 73. • <%@ taglib prefix = "ex" uri = "WEB- INF/custom.tld"%> • <html> <head> <title>A sample custom tag</title> </head> <body> <ex:Hello/> </body> </html> 73
  • 74. 2nd Example of JSP Custom Tag • In this example, we are going to create a custom tag that prints the current date and time. We are performing action at the start of tag. • For creating any custom tag, we need to follow following steps: • Create the Tag handler class and perform action at the start or at the end of the tag. • Create the Tag Library Descriptor (TLD) file and define tags • Create the JSP file that uses the Custom tag defined in the TLD file • 74
  • 75. • Call the above JSP and this should produce the following result − Hello Custom Tag! 75
  • 76. • MyTagHandler.java • package com.javatpoint.sonoo; • import java.util.Calendar; • import javax.servlet.jsp.JspException; • import javax.servlet.jsp.JspWriter; • import javax.servlet.jsp.tagext.TagSupport; • public class MyTagHandler extends TagSupport{ • • public int doStartTag() throws JspException { • JspWriter out=pageContext.getOut();//returns the instance of JspWriter • try{ • out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter • }catch(Exception e){System.out.println(e);} • return SKIP_BODY;//will not evaluate the body content of the tag • } • } 76
  • 77. • 2) Create the TLD file • Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained inside the WEB-INF directory. • File: mytags.tld • <?xml version="1.0" encoding="ISO-8859-1" ?> • <!DOCTYPE taglib • PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" • "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd"> • • <taglib> • • <tlib-version>1.0</tlib-version> • <jsp-version>1.2</jsp-version> • <short-name>simple</short-name> • <uri>http://tomcat.apache.org/example-taglib</uri> • • <tag> • <name>today</name> • <tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class> • </tag> • </taglib> • 3) Create the JSP file • Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended to use the uri name instead of full path of tld file. We will learn about uri later. • It uses taglib directive to use the tags defined in the tld file. 77
  • 78. • File: index.jsp • <%@ taglib uri="WEB- INF/mytags.tld" prefix="m" %> • Current Date and Time is: <m:today/> 78