ipunit3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

CS8651 - INTERNET

PROGRAMMING
UNIT 3- SERVER SIDE PROGRAMMING

1
UNIT III: SYLLABUS
• Servlets: Java Servlet Architecture - Servlet Life Cycle - Form

GET and POST actions

• Session Handling - Understanding Cookies - Installing and

Configuring Apache Tomcat Web Server -

• DATABASE CONNECTIVITY: JDBC perspectives, JDBC

program example

• JSP: Understanding Java Server Pages - JSP Standard Tag Library

(JSTL)-Creating HTML forms by embedding JSP code. 2


SERVLETS - JAVASERVLET ARCHITECTURE-SERVLET
LIFE CYCLE

3
SERVLETS

4
SERVLETS
• 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
SERVLETS - WORKING

6
CGI vs. SERVLETS
• What is CGI?
– Common Gateway Interface (CGI) is a standard for writing programs that
can interact through a Web server with a client running on Web browser.

7
CGI vs. SERVLETS

CGI(Common Gateway
Servlet
Interface)

Servlets are portable and efficient. CGI is not portable

In Servlets, sharing of data is possible. In CGI, sharing of data is not possible.

Servlets can directly communicate with the CGI cannot directly communicate with the
web server. web server.

Servlets are less expensive than CGI. CGI are more expensive than Servlets.

Servlets can handle the cookies. CGI cannot handle the cookies.

8
SERVLETS - ARCHITECTURE

• The components of Servlet Architecture are


– Client
– Web Server
– Web Container: Component in the webserver it interacts with Java servlets
which is responsible for managing the lifecycle of servlets and it also
performs the URL mapping task.
9
SERVLETS - WORKING
• In General,

• But when a page requested by a client is different or may be build


at the time of request (Not in html format) or the server is not
having the file in the requested format(Dynamic Request), the
server need to build the page in the format requested.
• That process is done by the helper application called “Web
Container” which contains the Servlets.
• Servlet is basically a Java file which can take the request from the
client on the internet and it can process the request and provide the
response in the form of HTML.
10
SERVLETS - WORKING
• The client send the request to the server.
• The Web Server receives the request from the client.
• The webserver passes the request to correspondent Servlet in the
Web Container.
• The servlet process the request and generate the response in the
form of output.
• The servlet send the response back to the webserver and back to
client.

11
SERVLETS - LIFE CYCLE
• The web container maintains the life cycle of a servlet instance.
1. Load Servlet
• The life cycle of the servlet are as follows: Class
– Servlet Class is Loaded 2. Create
Servlet
– Servlet Instance is Created Start Instance
3. Call Init
– Init Method is Invoked Method
– Service Method is Invoked
– Destroy Method is Invoked
Ready
4. Call the
Service
Method

4. Call the
End Destroy
Method 12
SERVLETS - LIFE CYCLE

Available for Servicing


Create Initialize
Service Requests

Unavailable
Un available for - Exception
Services Throw

Initialization
Failed
Destroy

Unload

13
SERVLETS - METHODS

Loading Servlet - Initialization - init()

Calls

Process the Request - Service() - toGet(), toPost()

Calls

Unloading the Servlet - destroy()

14
SERVLETS - METHODS
• Servlet Class is Loaded
– The class loader 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.

• 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.

• init method is invoked


– The web container calls the init method only once after creating the servlet
instance.
– The init method is used to initialize the Servlet 15
SERVLETS - METHODS
– Init is available in Javax.Servlet.Servlet.Interface.
public void init(servletconfig config) throws ServletException
{
}

• Servlet Method is Invoked


– The web container calls the service method each time when the request for
servlet is received.
– If the servlet is initialized , it calls the servlet method.
Public void service (SerletRequest request, Servlet Response response) throws
ServletException, IOException

• Destroy Method is Invoked


– The web container calls the destroy method before removing the servlet
16
instance from the service.
APACHE TOMCAT INSTALLATION
• Tomcat is a Web Server that can run Java Web Applications like
Java Servlets, Java Server Pages (JSP), Java Expression Language
and Java Web socket.
• Tomcat is a powerful production-ready server that is used by many
small, medium and big companies.
• https://tomcat.apache.org/download-80.cgi - Link to download the
Apache Tomcat Web Server.
• Binary Distributions -> 32-bit/64-bit Windows Service
Installer (pgp, sha512)

17
APCHE TOMCAT INSTALLATION

18
APCHE TOMCAT INSTALLATION
• Before start installation, need to setup JAVA_HOME or
JRE_HOME and CATALINA_HOME so that you can do
some maintenance operations on the Tomcat server like
Starting and Stopping the Server.

19
PARAMETERS, GET AND POST METHODS

• The parameters are the way in which a client or user can send
information to the Http Server.
• For example, in a login screen, we need to send to the server,
the user and the password so that it validates them.

20
PARAMETERS, GET AND POST METHODS

• The first thing we are going to do is to create in our site a page


"login.html" with the following content:

• Then, we create a Servlet which receives the request in /login ,


which is the indicated direction in the action attribute of the
tag <form> of login.html 21
PARAMETERS, GET AND POST METHODS

• Then Start the Webserver.


• Once the server starts, type http://localhost:8080/first-
servlet/login.html

• Then, we create a Servlet which receives the request in /login ,


which is the indicated direction in the action attribute of the
tag <form> of login.html 22
SESSION HANDLING
• Session simply means a particular interval of time.
• Session Tracking is a way to maintain state (data) of an user.
• It is also known as session management in servlet.
• Http protocol is a stateless so we need to maintain state using
session tracking techniques.
• Each time user requests to the server, server treats the request
as the new request.
• So we need to maintain the state of an user to recognize to
particular user.

23
SESSION HANDLING

• Session Tracking is used to recognize the particular user and


their data.
• Session Tracking Techniques
– There are four techniques used in Session tracking:
• Cookies
• Hidden Form Field
• URL Rewriting
• HttpSession
24
COOKIES IN SERVLET

• A cookie is a small piece of information that is persisted


between the multiple client requests.
• Cookies are text files stored on the client computer and they
are kept for various information tracking purpose.
• Java Servlets transparently supports HTTP cookies.
• Cookies can be used by a server to indicate session IDs,
shopping cart contents, login credentials, user preferences,
and more.

25
COOKIES IN SERVLET

• Server script sends a set of cookies to the browser. For


example name, age, or identification number etc.

• Browser stores this information on local machine for future


use.

• When next time browser sends any request to web server then
it sends those cookies information to the server and server uses
that information to identify the user. 26
TYPES OF COOKIE

• There are 2 types of cookies in servlets.


• Non-persistent cookie
– It is valid for single session only.
– It is removed each time when user closes the browser
• Persistent cookie
– It is valid for multiple session .
– It is not removed each time when user closes the browser.
– It is removed only if user logout or sign-out.

27
COOKIES

Advantage of Cookies
• Simplest technique of maintaining the state.
• Cookies are maintained at client side.
Disadvantage of Cookies
• It will not work if cookie is disabled from the
browser.
• Only textual information can be set in Cookie object.

28
COOKIES
Cookie class
• javax.servlet.http.Cookie class provides the functionality of
using cookies.
How to create Cookie?

Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Cookie ck=new Cookie("user","");//deleting value of cookie


ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

29
DATABASE CONNECTIVITY - JAVA JDBC

• JDBC stands for Java Database Connectivity.


• JDBC is a Java API to connect and execute the query with
the database.
• JDBC API uses JDBC drivers to connect with the database.
• There are four types of JDBC drivers:
– JDBC-ODBC Bridge Driver,
– Native Driver,
– Network Protocol Driver, and
– Thin Driver

30
DATABASE CONNECTIVITY - JAVA JDBC

• JDBC API is a Java API that can access any kind of tabular
data, especially data stored in a Relational Database.
• JDBC works with Java on a variety of platforms, such as
Windows, Mac OS, and the various versions of UNIX.
Why Should We Use JDBC?
• Before JDBC, ODBC API was the database API to connect
and execute the query with the database.
• But, ODBC API uses ODBC driver which is written in C
language (i.e. platform dependent and unsecured).

31
JDBC VS ODBC

32
JDBC - DRIVERS

• JDBC Driver is a software component that enables java

application to interact with the database.

• There are 4 types of JDBC drivers:

– JDBC-ODBC bridge driver

– Native-API driver (partially java driver)

– Network Protocol driver (fully java driver)

– Thin driver (fully java driver)


33
JDBC-ODBC bridge driver

34
Native-API driver

35
Native-API driver

36
Thin driver

37
DATABASE CONNECTIVITY

• There are 5 steps to connect any java application with the


database using JDBC. These steps are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection

38
UNDERSTANDING JSP

• Java Server Pages (JSP) is a technology for developing

Webpages that supports dynamic content.

• This helps developers insert java code in HTML pages by

making use of special JSP tags, most of which start with <%

and end with %>.

• A Java Server Pages component is a type of Java servlet that is

designed to fulfil the role of a user interface for a Java web

application.
39
UNDERSTANDING JSP

• Web developers write JSPs as text files that combine HTML


or XHTML code, XML elements, and embedded JSP actions
and commands.
• Using JSP, we can collect input from users through Webpage
forms, present records from a database or another source, and
create Webpages dynamically.
• JSP tags can be used for a variety of purposes, such as
retrieving information from a database or registering user
preferences, accessing JavaBeans components, passing
control between pages, and sharing information between
requests, pages etc. 40
WHY USE JSP?

• Java Server Pages often serve the same purpose as programs


implemented using the Common Gateway Interface (CGI).
• But JSP offers several advantages in comparison with the CGI:
– JSP are always compiled before they are processed by the
server unlike CGI/Perl which requires the server to load
an interpreter and the target script each time the page is
requested.
– Java Server Pages are built on top of the Java Servlets API,
so like Servlets, JSP also has access to all the powerful
Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP,
etc. 41
THE LIFECYCLE OF A JSP PAGE

• 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).

42
THE LIFECYCLE OF A JSP PAGE

43
THE LIFECYCLE OF A JSP PAGE

• 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.

44
CREATING A SIMPLE JSP PAGE

hello.jsp
<html>
<body>
<% out.print(2*5); %>
</body>
</html>

Put it in a folder and paste the folder in the web-apps directory


in apache tomcat to run the JSP page.

45
JSP PROCESSING

• As with a normal page, your browser sends an HTTP request


to the web server.
• The web server recognizes that the HTTP request is for a JSP
page and forwards it to a JSP engine.
• This is done by using the URL
(http://localhost:8888/myapplication/hello.jsp) or JSP page
which ends with .jsp instead of .html.
• The JSP engine loads the JSP page from disk and converts it
into a servlet content.

46
JSP PROCESSING

• This conversion is very simple in which all template text is


converted to println( ) statements and all JSP elements are
converted to Java code.
• This code implements the corresponding dynamic behavior of
the page.
• The JSP engine compiles the servlet into an executable class
and forwards the original request to a servlet engine.
• A part of the web server called the servlet engine loads the
Servlet class and executes it.

47
JSP PROCESSING

• During execution, the servlet produces an output in HTML


format.
• The output is further passed on to the web server by the servlet
engine inside an HTTP response.
• The web server forwards the HTTP response to your browser
in terms of static HTML content.
• Finally, the web browser handles the dynamically generated
HTML page inside the HTTP response exactly as if it were a
static page

48
JSP PROCESSING

49
JSTL

• The Java Server Pages Standard Tag Library (JSTL) is a


collection of useful JSP tags which encapsulates the core
functionality common to many JSP applications.
• JSTL has support for common, structural tasks such as
iteration and conditionals, tags for manipulating XML
documents, and SQL tags, Etc.,
• It also provides a framework for integrating the existing
custom tags with the JSTL tags.

50
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.

51

You might also like