SlideShare a Scribd company logo
1 of 122
Unit – III SERVER SIDE PROGRAMMING
Presented By
K.Karthick M.E(Ph.D.)
Assistant Professor/CSE,
Kongunadu College of Engineering And Technology.
What is a web application?
• A web application is an application accessible from the web. A web
application is composed of web components like Servlet, JSP, Filter,
etc. and other elements such as HTML, CSS, and JavaScript. The web
components typically execute in Web Server and respond to the HTTP
request.
• CGI (Common Gateway Interface)
• CGI technology enables the web server to call an external program
and pass HTTP request information to the external program to
process the request. For each request, it starts a new process.
• Disadvantages of CGI
• There are many problems in CGI technology:
• If the number of clients increases, it takes more time for sending the
response.
• For each request, it starts a process, and the web server is limited to
start processes.
• It uses platform dependent language e.g. C, C++, perl.
Server-side Scripting
• Sever-side scripting acts as an interface for the client and also limit
the user access the resources on web server.
• It can also collects the user’s characteristics in order to customize
response.
Why Server Side Programming
• Though it is technically feasible to implement almost any business
logic using client-side programs, logically or functionally it server no
purpose when it comes to enterprises application (e.g., banking, air
ticketing, e-shopping, etc).
• To further explain, going by the client-side programming logic; a bank
having 10,000customers would mean that each customer would have
a copy of the program(s) in his or her PC (and now even mobiles)
which translates to 10,000 programs!
• In addition, there are issues like security, resource pooling, concurrent
access and manipulations to the database which simply cannot be
handled by client-side programs. The answer to most of the issues
cited above is-“Server Side Programming”
Advantages of Server Side Programs
• Some of the advantages of Server Side programs are as follows:
• 1. All programs reside in one machine called server. Any number of remote
machines (called clients) can access the server programs.
• ii. New functionalities to existing programs can be added at the server side
which the clients can take advantage of without having to change anything.
• iii. Migrating to newer versions, architectures, design patterns, adding
patches, switching to new databases can be done at the server side
without having to bother about client’s hardware or software capabilities.
• iv. Issues relating to enterprise applications like resource management,
concurrency, session management, security and performance are managed
by the server side applications.
• v. They are portable and possess the capability to generate dynamic and
user-based content (e.g., displaying transaction information of credit card
or debit card depending on user’s choice).
• Types of Server Side Programs
• The following are the different types of server side programs:
• (a) Active Server Pages (ASP)
• (b) Java Servlets
• (c) Java Server Pages (JSP)
• (d) Enterprise JavaBeans (EJB)
• (e)PHP
• There are many advantages of Servlet over CGI. The web container creates
threads for handling the multiple requests to the Servlet. Threads have
many benefits over the Processes such as they share a common memory
area, lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:
• Better performance: because it creates a thread for each request, not
process.
• Portability: because it uses Java language.
• Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
• Secure: because it uses java language.
What are Servlets?
• Java Servlets are programs that run on a Web or Application server
and act as a middle layer between a requests coming from a Web
browser or other HTTP client and databases or applications on the
HTTP server.
• Using Servlets, you can collect input from users through web page
forms, present records from a database or another source, and create
web pages dynamically.
• Java Servlets often serve the same purpose as programs implemented
using the Common Gateway Interface (CGI). But Servlets offer several
advantages in comparison with the CGI.
• Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet.
It can communicate with applets, databases, or other software via the
sockets and RMI mechanisms that you have seen already.
Servlets Architecture
What is Servlet Container?
• In Java, Servlet container (also known as a Web container) generates
dynamic web pages. So servlet container is the essential part of the
web server that interacts with the java servlets. Servlet Container
communicates between client Browsers and the servlets.
• Servlet Container managing the life cycle of servlet. Servlet
container loading the servlets into memory, initializing and invoking
servlet methods and to destroy them. There are a lot of Servlet
Containers like Jboss, Apache Tomcat, WebLogic etc.
How does this Servlet Container work?
• A client browser accesses a Web server or HTTP server for a page.
• The Web server redirects the request to the servlet container (Servlets are
HTTP listeners that run inside the servlet container).
• The servlet container redirects the request to the appropriate servlet.
• The servlet is dynamically retrieved and loaded into the address space of
the container, if it is not in the container. The servlet container invokes
servlet init () method once when the servlet is loaded first time for
initialization.
• The servlet container invokes the service () methods of the servlet to
process the HTTP request, i.e., read data in the request and formulate a
response. The servlet remains in the container’s address space and can
process other HTTP requests.
• Web servlet generates data (HTML page, picture …) return the dynamically
generated results to the correct location.
What is SERVLET API?
• Before creating the first servlet, you need to understand
the Servlet API and Tomcat Servlet container. The Servlet API provides
interfaces and classes that are required to built servlets. These
interfaces and classes are group into the following two packages :
• • javax.servlet
• • javax.servlet.http
Interfaces Description
Servlet Declares life cycle methods that all servlets must implement.
ServletConfig Allows servlets to get initialization parameters
ServletContext Allows servlets to communicate with its servlet container.
ServletRequest Provides client request information to a servlet.
ServletResponse Assist a servlet in sending a response to the client.
Classes Description
GenericServlet Provides a basic implementation of the Servlet interface
for protocol independent servlets
ServletlnputStream Provides an input stream for reading binary data from a client request.
ServletOutputStream Provides an output stream for sending binary data to the client.
ServletException Defines a general exception, a servlet can throw when it encounters
difficulty.
UnavailableException Indicates that a servlet is not available to service client request.
Servlets Tasks
• Servlets perform the following major tasks −
• Read the explicit data sent by the clients (browsers). This includes an HTML form
on a Web page or it could also come from an applet or a custom HTTP client
program.
• Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so
forth.
• Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or computing
the response directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or XML),
binary (GIF images), Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML),
setting cookies and caching parameters, and other such tasks.
Servlets Packages
• Java Servlets are Java classes run by a web server that has an interpreter
that supports the Java Servlet specification.
• Servlets can be created using
the javax.servlet and javax.servlet.http packages, which are a standard
part of the Java's enterprise edition, an expanded version of the Java class
library that supports large-scale development projects.
• These classes implement the Java Servlet and JSP specifications. At the
time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
• Java servlets have been created and compiled just like any other Java class.
After you install the servlet packages and add them to your computer's
Classpath, you can compile servlets with the JDK's Java compiler or any
other current compiler.
• Setting up Java Development Kit
• This step involves downloading an implementation of the Java
Software Development Kit (SDK) and setting up PATH environment
variable appropriately.
• You can download SDK from Oracle's Java site − Java SE Downloads.
• Once you download your Java implementation, follow the given
instructions to install and configure the setup. Finally set PATH and
JAVA_HOME environment variables to refer to the directory that
contains java and javac, typically java_install_dir/bin and
java_install_dir respectively.
• 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.
• 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.
• 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 {
• }
• The doGet() Method
• A GET request results from a normal request for a URL or from an
HTML form that has no METHOD specified and it should be handled
by doGet() method.
• public void doGet(HttpServletRequest request, HttpServletResponse
response)
• throws ServletException, IOException {
• // Servlet code
• }
• The doPost() Method
• A POST request results from an HTML form that specifically lists POST
as the METHOD and it should be handled by doPost() method.
• public void doPost(HttpServletRequest request, HttpServletResponse
response)
• throws ServletException, IOException {
• // Servlet code
• }
• The destroy() Method
• The destroy() method is called only once at the end of the life cycle of
a servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts
to disk, and perform other such cleanup activities.
• After the destroy() method is called, the servlet object is marked for
garbage collection. The destroy method definition looks like this −
• public void destroy() {
• // Finalization code...
• }
Architecture Diagram
• The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the
servlet container.
• The servlet container loads the servlet before invoking the service()
method.
• Then the servlet container handles multiple requests by spawning
multiple threads, each thread executing the service() method of a
single instance of the servlet.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends
HttpServlet {
private String message;
public void init() throws
ServletException {
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException,
IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out =
response.getWriter();
out.println("<h1>" + message +
"</h1>");
}
public void destroy() {
// do nothing.
}
}
<servlet>
<servlet-
name>HelloWorld</servlet-
name>
<servlet-
class>HelloWorld</servlet-
class></servlet>
<servlet-mapping>
<servlet-
name>HelloWorld</servlet-
name>
<url-pattern>/HelloWorld</url-
pattern></servlet-mapping>
Types of Servlets
• There is a possibility of developing ‘n’ types of servlets, like
httpservlet, ftpservlet, smtpservlet etc. for all
these protocol specific servlet classes GenericServlet is the common
super class containing common properties and logics. So,
GenericServlet is not a separate type of servlet.
• As of now Servlet API is giving only one subclass to GenericServlet i.e
HttpServlet class because all web servers are designed based on
the protocol http.
What is HTTP?
• The Hypertext Transfer Protocol (HTTP) is designed to enable
communications between clients and servers.
• HTTP works as a request-response protocol between a client and
server.
• Example: A client (browser) sends an HTTP request to the server; then
the server returns a response to the client. The response contains
status information about the request and may also contain the
requested content.
• HTTP Methods
• GET
• POST
• PUT
• HEAD
• DELETE
• PATCH
• OPTIONS
• CONNECT
• TRACE
• The two most common HTTP methods are: GET and POST
• The GET Method
• GET is used to request data from a specified resource.
• Note that the query string (name/value pairs) is sent in the URL of a
GET request:
• /test/demo_form.php?name1=value1&name2=value2
• Some notes on GET requests:
• GET requests can be cached
• GET requests remain in the browser history
• GET requests can be bookmarked
• GET requests should never be used when dealing with sensitive data
• GET requests have length restrictions
• GET requests are only used to request data (not modify)
• The POST Method
• POST is used to send data to a server to create/update a resource.
• The data sent to the server with POST is stored in the request body of
the HTTP request:
• POST /test/demo_form.php HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
GET POST
1) In case of Get request, only limited
amount of data can be sent because data
is sent in header.
In case of post request, large amount of
data can be sent because data is sent in
body.
2) Get request is not secured because
data is exposed in URL bar.
Post request is secured because data is
not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
4) Get request is idempotent . It means
second request will be ignored until
response of first request is delivered
Post request is non-idempotent.
5) Get request is more efficient and used
more than Post.
Post request is less efficient and used
less than get.
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.
• HTTP is stateless that means each request is considered as the new
request. It is shown in the figure given below:
• Why use Session Tracking?
• To recognize the user It is used to recognize the particular user.
• Session Tracking Techniques
• There are four techniques used in Session tracking:
• Cookies
• Hidden Form Field
• URL Rewriting
• HttpSession
SESSION TRACKING
• HTTP is a stateless protocol. Each request is independent of the previous one.
• However, in some applications, it is necessary to save state information so that information can
be collected from several interactions between a browser and a server.
• Sessions provide such a mechanism. A session can be created via the getSession( ) method of
HttpServletRequest.An HttpSession object is returned.
• This object can store a set of bindings that associate names with objects.
• The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of
HttpSession manage these bindings.
• It is important to note that session state is shared among all the servlets that are associated with
a particular client.
• The following servlet illustrates how to use session state. The
getSession( ) method gets the current session.
• A new session is created if one does not already exist. The
getAttribute( ) method is called to obtain the object that is bound to
the name “date”.
• That object is a Date object that encapsulates the date and time
when this page was last accessed. (Of course, there is no such binding
when the page is first accessed.)
• A Date object encapsulating the current date and time is then created.
The setAttribute( ) method is called to bind the name “date” to this
object
• import java.io.*;
• import javax.servlet.*;
• import javax.servlet.http.*;
• public class DateServlet extends HttpServlet {
• public void doGet(HttpServletRequest request,HttpServletResponse response)
• throws ServletException, IOException
{
HttpSession hs = request.getSession(true); response.setContentType("text/html");
• PrintWriter pw = response.getWriter(); pw.print("<B>");
• Date date = (Date)hs.getAttribute("date");
• if(date != null)
• {
• pw.print("Last access: " + date + "<br>");
• } date = new Date();
• hs.setAttribute("date", date); pw.println("Current date: " +
date);
• } }
Cookies in Servlet
• A cookie is a small piece of information that is persisted between the
multiple client requests.
• A cookie has a name, a single value, and optional attributes such as a
comment, path and domain qualifiers, a maximum age, and a version
number.
How Cookie works:
• By default, each request is considered as a new request. In cookies
technique, we add cookie with response from the servlet. So cookie is
stored in the cache of the browser. After that if request is sent by the
user, cookie is added with request by default. Thus, we recognize the
user as the old user.
• Types of Cookie
• There are 2 types of cookies in servlets.
• Non-persistent cookie
• Persistent cookie
• 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 signout.
• 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.
Cookie class
• javax.servlet.http.Cookie class provides the functionality of using
cookies. It provides a lot of useful methods for cookies.
• Constructor of Cookie class
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String
value)
constructs a cookie with a
specified name and value.
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in
seconds.
public String getName() Returns the name of the cookie. The
name cannot be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
• How to create Cookie?
• Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie obje
ct
• response.addCookie(ck);//adding cookie in the response
• How to delete Cookie?// it is mainly used to logout or sign out the
user
• 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
How to get Cookies?
• Cookie ck[]=request.getCookies();
• for(int i=0;i<ck.length;i++){
• out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
• //printing name and value of cookie
• }
• <form action="servlet1" method="post">
• Name:<input type="text" name="userName"/><br/>
• <input type="submit" value="go"/>
• </form>
Hidden Form Field
• In case of Hidden Form Field a hidden (invisible) textfield is used for
maintaining the state of an user.
• In such case, we store the information in the hidden field and get it
from another servlet. This approach is better if we have to submit
form in all the pages and we don't want to depend on the browser.
• <input type="hidden" name="uname" value="Vimal Jaiswal">
• Real application of hidden form field
• It is widely used in comment form of a website. In such case, we store page
id or page name in the hidden field so that each page can be uniquely
identified.
• Advantage of Hidden Form Field
• It will always work whether cookie is disabled or not.
• Disadvantage of Hidden Form Field:
• It is maintained at server side.
• Extra form submission is required on each pages.
• Only textual information can be used.
Example of using Hidden Form Field
URL Rewriting
• In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource. We can send parameter
name/value pairs using the following format:
• url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can
use getParameter() method to obtain a parameter value.
• Advantage of URL Rewriting
• It will always work whether cookie is disabled or not (browser
independent).
• Extra form submission is not required on each pages.
• Disadvantage of URL Rewriting
• It will work only with links.
• It can send Only textual information.
•
HttpSession interface
• In such case, container creates a session id for each user.The
container uses this id to identify the particular user.An object of
HttpSession can be used to perform two tasks:
• bind objects
• view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
• How to get the HttpSession object ?
• The HttpServletRequest interface provides two methods to get the
object of HttpSession:
• public HttpSession getSession():Returns the current session
associated with this request, or if the request does not have a
session, creates one.
• public HttpSession getSession(boolean create):Returns the current
HttpSession associated with this request or, if there is no current
session and create is true, returns a new session.
• Commonly used methods of HttpSession interface
• public String getId():Returns a string containing the unique identifier
value.
• public long getCreationTime():Returns the time when this session
was created, measured in milliseconds since midnight January 1, 1970
GMT.
• public long getLastAccessedTime():Returns the last time the client
sent a request associated with this session, as the number of
milliseconds since midnight January 1, 1970 GMT.
• public void invalidate():Invalidates this session then unbinds any
objects bound to it.
JSP
• Java Server Pages (JSP) is a server-side programming technology that
enables the creation of dynamic, platform-independent method for
building Web-based applications using a combination of HTML, XML,
and Java code.
• JSP have access to the entire family of Java APIs, including the JDBC
API to access enterprise databases.
• JavaServer 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 %>.
Facts About JSP
• JSP stands for Java Server Pages.
• JSP is a technology to build dynamic web applications.
• JSP is a part of Java Enterprise Edition (Java EE).
• JSP is similar to HTML pages, but they also contain Java code executed on
the server side.
• Server-side scripting means the JSP code is processed on the web server
rather than the client machine.
• A JSP page is a file with a ".jsp" extension that can contain a combination
of HTML Tags and JSP codes.
• To create a web page, JSP uses a combination of HTML or XML markup, JSP
tags, expressions, and Java code.
• JSP tags begin with <% and end with %>.
• JSP expressions are used to insert dynamic content into the page and
begin with <%= and end with %>.
• JSP can use JavaBeans to store and retrieve data.
• JSP requires a Java development environment and a Java Servlet
Container such as Apache Tomcat or Jetty.
• JSP is widely used in the industry for creating enterprise web
applications.
• JSP is an improved extended version of Servlet technology.
Why to Learn 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.
• Performance is significantly better because JSP allows embedding Dynamic
Elements in HTML Pages itself instead of having separate CGI files.
• 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.
• JavaServer 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.
• JSP pages can be used in combination with servlets that handle the
business logic, the model supported by Java servlet template engines.
The difference between Servlet and JSP
Servlet JSP
Servlet is a java code. JSP is a HTML based code.
Writing code for servlet is harder than
JSP as it is HTML in java.
JSP is easy to code as it is java in HTML.
Servlet plays a controller role in the
hasMVC approach.
JSP is the view in the MVC approach for
showing output.
Servlet is faster than JSP.
JSP is slower than Servlet because the
first step in the has JSP lifecycle is the
translation of JSP to java code and then
compile.
Servlet can accept all protocol
requests.
JSP only accepts HTTP requests.
In Servlet, we can override the
service() method.
In JSP, we cannot override its service()
method.
In Servlet by default session management is not
enabled, user have to enable it explicitly.
In JSP session management is automatically
enabled.
In Servlet we have to implement everything like
business logic and presentation logic in just one
servlet file.
In JSP business logic is separated from
presentation logic by using JavaBeansclient-side.
Modification in Servlet is a time-consuming
compiling task because it includes reloading,
recompiling, JavaBeans and restarting the server.
JSP modification is fast, just need to click the
refresh button.
It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.
There is no method for running JavaScript on the
client side in Servlet.
While running the JavaScript at the client side in
JSP, the client-side validation is used.
Packages are to be imported on the top of the
program.
Packages can be imported into the JSP
program(i.e bottom , middleclient-side, or top )
Applications of JSP
• JSP vs. Active Server Pages (ASP)
• The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it is
portable to other operating systems and non-Microsoft Web servers.
• JSP vs. Pure Servlets
• It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
• JSP vs. Server-Side Includes (SSI)
• SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.
• JSP vs. JavaScript
• JavaScript can generate HTML dynamically on the client but can hardly interact with the
web server to perform complex tasks like database access and image processing etc.
• JSP vs. Static HTML
• Regular HTML, of course, cannot contain dynamic information.
JSP Environment
• JSP environment is a set of tools and technologies used to create dynamic web
pages using JavaServer Pages (JSP) technology. It includes the following
components:
• JSP Engine: A software component that reads and executes JSP files. It converts
JSP code into servlets, which are then executed on the server and generate the
final HTML.
• Web Server: A software that receives requests from clients and sends responses.
It is responsible for handling HTTP requests and responses.
• Java Runtime Environment (JRE): This software provides the necessary
environment for running Java applications, including JSP pages.
• Additional Libraries and Frameworks: Additional tools and libraries, such as
JavaBeans, JavaServer Faces, and Spring framework, can be used to develop JSP
applications.
• Development Tools: Integrated development environments (IDEs), such as
Eclipse, IntelliJ IDEA, and NetBeans, are used to write, test, and debug JSP code.
JSP - Architecture
• JSP architecture is a 3-tier architecture that separates a web
application's presentation, logic, and data layers. The presentation
layer, or client side, is responsible for displaying the user interface and
handling user interaction.
• The logic layer, or server-side, is responsible for processing user
requests and handling business logic. The data layer is responsible for
storing and retrieving data from a database or other storage system.
This separation of concerns allows for better maintainability and
scalability of the application.
• A JSP-based web application requires a JSP engine, also known as a
web container, to process and execute the JSP pages. The web
container is a web server component that manages the execution of
web programs such as servlets, JSPs, and ASPs.
• When a client sends a request for a JSP page, the web container
intercepts it and directs it to the JSP engine. The JSP engine then
converts the JSP page into a servlet class, compiles it, and creates an
instance of the class. The service method of the servlet class is then
called, which generates the dynamic content for the JSP page.
• The web container also manages the lifecycle of the JSP pages and
servlets, handling tasks such as instantiating, initializing and
destroying them. Additionally, it provides security, connection
pooling, and session management services to the JSP-based web
application.
Components of Web container
• JSP architecture is a web application development model that defines the
structure and organization of a JSP-based web application. It typically
consists of the following components:
• JSP pages: These are the main building blocks of a JSP application. They
contain a combination of HTML, XML, and JSP elements (such as scriptlets,
expressions, and directives) that generate dynamic content.
• Servlets: JSP pages are converted into servlets by the JSP engine. Servlets
are Java classes that handle HTTP requests and generate dynamic content.
• JSP engine (web container): This web server component is responsible for
processing JSP pages. It converts JSP pages into servlets, compiles them,
and runs them in the Java Virtual Machine (JVM).
•
• JavaBeans: These are reusable Java classes that encapsulate business
logic and data. They are used to store and retrieve information from a
database or other data sources.
• JSTL (JavaServer Pages Standard Tag Library): This is a set of
predefined tags that can be used in JSP pages to perform common
tasks such as iterating over collections, conditional statements, and
internationalization.
• Custom Tag Libraries: JSP allows the creation of custom tags that can
be used on JSP pages. These reusable Java classes encapsulate
complex logic and can generate dynamic content cleanly and
consistently.
JSP life cycle
• A JSP page life cycle is defined as a process from its translation phase
to the destruction phase. This lesson describes the various stages of a
JSP page life cycle.
• The life cycle of a JSP page can be divided into the following phase:
• Translation Phase
• Compilation Phase
• Initialization Phase
• Execution Phase
• Destruction(Cleanup) Phase
Translation Phase
• When a user navigates to a page ending with a .jsp extension in their
web browser, the web browser sends an HTTP request to the
webserver.
• The webserver checks if a compiled version of the JSP page already
exists.
• If the JSP page's compiled version does not exist, the file is sent to
the JSP Servlet engine, which converts it into servlet content
(with .java extension). This process is known as translation.
• The web container automatically translates the JSP page into a
servlet. So as a developer, you don't have to worry about converting it
manually.
Compilation Phase
• In case the JSP page was not compiled previously or at any point in
time, then the JSP page is compiled by the JSP engine.
• In this compilation phase, the Translated .java file of the servlet is
compiled into the Java servlet .class file.
Initialization Phase
• In this Initialization phase: Here, the container will:
• Load the equivalent servlet class.
• Create instance.
• Call the jspInit() method for initializing the servlet instance.
• This initialization is done only once with the servlet's init method
where database connection, opening files, and creating lookup tables
are done.
• Execution phase
• This Execution phase is responsible for all JSP interactions and logic
executions for all requests until the JSP gets destroyed. As the
requested JSP page is loaded and initiated, the JSP engine has to
invoke the _jspService() method. This method is invoked as per the
requests, responsible for generating responses for the associated
requests, and responsible for all HTTP methods.
• Destruction(Cleanup) Phase
• This destruction phase is invoked when the JSP has to be cleaned up
from use by the container. The jspDestroy() method is invoked. You
can incorporate and write cleanup codes inside this method for
releasing database connections or closing any file.
• 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...
• }
• 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...
• }
• The _jspService() method of a JSP is invoked on request basis. This is
responsible for generating the response for that request and this
method is also responsible for generating responses to all seven of
the HTTP methods, i.e, GET, POST, DELETE, etc.
• 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.
• }
• JSP SCRIPTING ELEMENTS:
• 3 types of scripting elements:
• Scrip let tag
• Expression tag
• Declaration tag
• To insert java code inside jsp
JSP - Syntax
• Elements of JSP
• The Scriptlet
• A scriptlet can contain any number of JAVA language statements,
variable or method declarations, or expressions that are valid in the
page scripting language.
• Following is the syntax of Scriptlet −
• <% code fragment %>
• <jsp:scriptlet>
• code fragment
• </jsp:scriptlet>
• JSP Declarations
• A declaration declares one or more variables or methods that you can
use in Java code later in the JSP file. You must declare the variable or
method before you use it in the JSP file.
• Following is the syntax for JSP Declarations −
• <%! declaration; [ declaration; ]+ ... %>
• Example:
• <%! int i = 0; %>
• <%! int a, b, c; %>
• <%! Circle a = new Circle(2.0); %>
• JSP Expression
• A JSP expression element contains a scripting language expression
that is evaluated, converted to a String, and inserted where the
expression appears in the JSP file.
• <%= expression %>
• JSP Comments
• JSP comment marks text or statements that the JSP container should
ignore. A JSP comment is useful when you want to hide or "comment
out", a part of your JSP page.
• Following is the syntax of the JSP comments −
• <%-- This is JSP comment --%>
• <html>
• <head><title>A Comment Test</title></head>
• <body>
• <h2>A Test of Comments</h2>
• <%-- This comment will not be visible in the page source --%>
• </body>
• </html>
• JSP Directives
• A JSP directive affects the overall structure of the servlet class. It
usually has the following form −
• <%@ directive attribute="value" %>
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
JavaBean
• A JavaBean is a Java class that should follow the following
conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties,
known as getter and setter methods.
What is JavaBeans in JSP?
• Bean means component. Components mean reusable objects. JavaBean is
a reusable component. Java Bean is a normal java class that may declare
properties, setter, and getter methods in order to represent a particular
user form on the server-side. JavaBean is a java class that is developed with
a set of conventions. The conventions are:
• The class should be public and must not be final, abstract.
• Recommend to implement serializable.
• Must have direct/indirect param constructor.
• Member variables should be non-static and private.
• Every bean property should have one setter method and one getter
method with the public modifier.
• Working of JavaBeans in JSP
• First, the browser sends the request for the JSP page. Then the JSP
page accesses Java Bean and invokes the business logic. After
invoking the business logic Java Bean connects to the database and
gets/saves the data. At last, the response is sent to the browser which
is generated by the JSP.
• Advantages of Java Beans
• It is easy to reuse the software components.
• The properties and methods of Java Bean can be exposed to another
application.
• Disadvantages of Java Beans
• JavaBeans are mutable objects so it cannot take advantage of immutable
objects.
• JavaBeans will be in an inconsistent state because of creating the setter
and getter method for each property separately.
• Java Bean Properties
• getPropertyName(): This method is used to read the property which is also
called accessor.
• setPropertyName(): This method is used to write the property which is
also called mutator.
• package mypack;
• public class Employee implements java.io.Serializable
• {
• private int id;
• private String name;
• public Employee(){}
• public void setId(int id)
• {
• this.id=id;
• }
• public int getId()
• {return id;
• }
• public void setName(String name)
• {
• this.name=name;
• }
• public String getName(){return name;}
• }
• package mypack;
• public class Test{
• public static void main(String args[]){
• Employee e=new Employee();//object is created
• e.setName("Arjun");//setting value to the object
• System.out.println(e.getName());
• }}
JSP - Standard Tag Library (JSTL) Tutorial
• The JavaServer 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,
internationalization tags, and SQL tags. It also provides a framework
for integrating the existing custom tags with the JSTL tags.
• Install JSTL Library
• To begin working with JSP tages you need to first install the JSTL
library. If you are using the Apache Tomcat container, then follow
these two steps −
• Step 1 − Download the binary distribution from Apache Standard
Taglib and unpack the compressed file.
• Step 2 − To use the Standard Taglib from its Jakarta Taglibs
distribution, simply copy the JAR files in the distribution's 'lib'
directory to your application's webappsROOTWEB-
INFlib directory.
• To use any of the libraries, you must include a <taglib> directive at the
top of each JSP that uses the library.
• Classification of The JSTL Tags
• The JSTL tags can be classified, according to their functions, into the
following JSTL tag library groups that can be used when creating a JSP
page −
• Core Tags
• Formatting tags
• SQL tags
• XML tags
• JSTL Functions
Core Tags
• The core group of tags are the most commonly used JSTL tags.
Following is the syntax to include the JSTL Core library in your JSP −
• <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
Formatting Tags
• The JSTL formatting tags are used to format and display text, the date,
the time, and numbers for internationalized Websites. Following is
the syntax to include Formatting library in your JSP −
• <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
SQL Tags
• The JSTL SQL tag library provides tags for interacting with relational
databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
• Following is the syntax to include JSTL SQL library in your JSP −
• <%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
XML tags
• The JSTL XML tags provide a JSP-centric way of creating and
manipulating the XML documents. Following is the syntax to include
the JSTL XML library in your JSP.
• The JSTL XML tag library has custom tags for interacting with the XML
data. This includes parsing the XML, transforming the XML data, and
the flow control based on the XPath expressions.
• <%@ taglib prefix = "x"
• uri = "http://java.sun.com/jsp/jstl/xml" %>
MVC Framework - Introduction
• The Model-View-Controller (MVC) is an architectural pattern that
separates an application into three main logical components:
the model, the view, and the controller.
• Each of these components are built to handle specific development
aspects of an application.
• MVC is one of the most frequently used industry-standard web
development framework to create scalable and extensible projects.
• Model
• The Model component corresponds to all the data-related logic that
the user works with. This can represent either the data that is being
transferred between the View and Controller components or any
other business logic-related data.
• For example, a Customer object will retrieve the customer
information from the database, manipulate it and update it data back
to the database or use it to render data.
• View
• The View component is used for all the UI logic of the application. For
example, the Customer view will include all the UI components such
as text boxes, dropdowns, etc. that the final user interacts with.
• Controller
• Controllers act as an interface between Model and View components
to process all the business logic and incoming requests, manipulate
data using the Model component and interact with the Views to
render the final output.
• For example, the Customer controller will handle all the interactions
and inputs from the Customer View and update the database using
the Customer Model.
• The same controller will be used to view the Customer data.
ASP.NET MVC
• ASP.NET supports three major development models: Web Pages, Web
Forms and MVC (Model View Controller).
• ASP.NET MVC framework is a lightweight, highly testable presentation
framework that is integrated with the existing ASP.NET features, such
as master pages, authentication, etc. Within .NET, this framework is
defined in the System.Web.Mvc assembly.
• The latest version of the MVC Framework is 5.0. We use Visual Studio
to create ASP.NET MVC applications which can be added as a
template in Visual Studio.
• Implementation
• We are going to create a Student object acting as a
model.StudentView will be a view class which can print student
details on console and StudentController is the controller class
responsible to store data in Student object and update
view StudentView accordingly.
• MVCPatternDemo, our demo class, will use StudentController to
demonstrate use of MVC pattern.
WEB TECHNOLOGY Unit-3.pptx

More Related Content

What's hot

REST vs GraphQL
REST vs GraphQLREST vs GraphQL
REST vs GraphQLSquareboat
 
Microservice architecture design principles
Microservice architecture design principlesMicroservice architecture design principles
Microservice architecture design principlesSanjoy Kumar Roy
 
Cloud Computing Environment using Cluster as a service
Cloud Computing Environment using Cluster as a serviceCloud Computing Environment using Cluster as a service
Cloud Computing Environment using Cluster as a serviceANUSUYA T K
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design PatternSanae BEKKAR
 
6. Microservices architecture.pptx
6. Microservices architecture.pptx6. Microservices architecture.pptx
6. Microservices architecture.pptxdatapro2
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design PatternsHaim Michael
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)Manisha Keim
 
GraphQL API Gateway and microservices
GraphQL API Gateway and microservicesGraphQL API Gateway and microservices
GraphQL API Gateway and microservicesMohammed Shaban
 
Java web application development
Java web application developmentJava web application development
Java web application developmentRitikRathaur
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using JavascriptBansari Shah
 
Power Platform Architecture Corrections
Power Platform Architecture CorrectionsPower Platform Architecture Corrections
Power Platform Architecture CorrectionsYusuke Ohira
 

What's hot (20)

Graphql
GraphqlGraphql
Graphql
 
REST vs GraphQL
REST vs GraphQLREST vs GraphQL
REST vs GraphQL
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
Microservice architecture design principles
Microservice architecture design principlesMicroservice architecture design principles
Microservice architecture design principles
 
Cloud Computing Environment using Cluster as a service
Cloud Computing Environment using Cluster as a serviceCloud Computing Environment using Cluster as a service
Cloud Computing Environment using Cluster as a service
 
Web Servers (ppt)
Web Servers (ppt)Web Servers (ppt)
Web Servers (ppt)
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
Introduction to Design Pattern
Introduction to Design  PatternIntroduction to Design  Pattern
Introduction to Design Pattern
 
Web engineering lecture 1
Web engineering lecture 1Web engineering lecture 1
Web engineering lecture 1
 
6. Microservices architecture.pptx
6. Microservices architecture.pptx6. Microservices architecture.pptx
6. Microservices architecture.pptx
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
GraphQL API Gateway and microservices
GraphQL API Gateway and microservicesGraphQL API Gateway and microservices
GraphQL API Gateway and microservices
 
Java web application development
Java web application developmentJava web application development
Java web application development
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Client side scripting using Javascript
Client side scripting using JavascriptClient side scripting using Javascript
Client side scripting using Javascript
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Web servers
Web serversWeb servers
Web servers
 
Api types
Api typesApi types
Api types
 
Power Platform Architecture Corrections
Power Platform Architecture CorrectionsPower Platform Architecture Corrections
Power Platform Architecture Corrections
 

Similar to WEB TECHNOLOGY Unit-3.pptx

Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music storeADEEBANADEEM
 
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 Connectivitypkaviya
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptVMahesh5
 
Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Gera Paulos
 
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 tanujaparihar
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servletsAamir Sohail
 
Intorduction to struts
Intorduction to strutsIntorduction to struts
Intorduction to strutsAnup72
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptxMattMarino13
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)slire
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIPRIYADARSINISK
 

Similar to WEB TECHNOLOGY Unit-3.pptx (20)

Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 
JAVA
JAVAJAVA
JAVA
 
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
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)
 
Servlets
ServletsServlets
Servlets
 
Servlet programming
Servlet programmingServlet programming
Servlet programming
 
Ecom 1
Ecom 1Ecom 1
Ecom 1
 
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
 
Servlet classnotes
Servlet classnotesServlet classnotes
Servlet classnotes
 
Servlet programming
Servlet programmingServlet programming
Servlet programming
 
Servlets
ServletsServlets
Servlets
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
 
Intorduction to struts
Intorduction to strutsIntorduction to struts
Intorduction to struts
 
BITM3730Week12.pptx
BITM3730Week12.pptxBITM3730Week12.pptx
BITM3730Week12.pptx
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 

More from karthiksmart21

WEB TECHNOLOGY Unit-2.pptx
WEB TECHNOLOGY Unit-2.pptxWEB TECHNOLOGY Unit-2.pptx
WEB TECHNOLOGY Unit-2.pptxkarthiksmart21
 
WEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxWEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxkarthiksmart21
 
WEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptxWEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptxkarthiksmart21
 
MOBILE COMPUTING Unit 3.pptx
MOBILE COMPUTING Unit 3.pptxMOBILE COMPUTING Unit 3.pptx
MOBILE COMPUTING Unit 3.pptxkarthiksmart21
 
MOBILE COMPUTING Unit 4.pptx
 MOBILE COMPUTING Unit 4.pptx MOBILE COMPUTING Unit 4.pptx
MOBILE COMPUTING Unit 4.pptxkarthiksmart21
 
MOBILE COMPUTING Unit 2.pptx
MOBILE COMPUTING Unit 2.pptxMOBILE COMPUTING Unit 2.pptx
MOBILE COMPUTING Unit 2.pptxkarthiksmart21
 
MOBILE COMPUTING Unit 1.pptx
MOBILE COMPUTING Unit 1.pptxMOBILE COMPUTING Unit 1.pptx
MOBILE COMPUTING Unit 1.pptxkarthiksmart21
 
MOBILE COMPUTING Unit 5.pptx
MOBILE COMPUTING Unit 5.pptxMOBILE COMPUTING Unit 5.pptx
MOBILE COMPUTING Unit 5.pptxkarthiksmart21
 

More from karthiksmart21 (9)

WEB TECHNOLOGY Unit-2.pptx
WEB TECHNOLOGY Unit-2.pptxWEB TECHNOLOGY Unit-2.pptx
WEB TECHNOLOGY Unit-2.pptx
 
WEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxWEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptx
 
WEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptxWEB TECHNOLOGY Unit-4.pptx
WEB TECHNOLOGY Unit-4.pptx
 
MOBILE COMPUTING Unit 3.pptx
MOBILE COMPUTING Unit 3.pptxMOBILE COMPUTING Unit 3.pptx
MOBILE COMPUTING Unit 3.pptx
 
MOBILE COMPUTING Unit 4.pptx
 MOBILE COMPUTING Unit 4.pptx MOBILE COMPUTING Unit 4.pptx
MOBILE COMPUTING Unit 4.pptx
 
MOBILE COMPUTING Unit 2.pptx
MOBILE COMPUTING Unit 2.pptxMOBILE COMPUTING Unit 2.pptx
MOBILE COMPUTING Unit 2.pptx
 
MOBILE COMPUTING Unit 1.pptx
MOBILE COMPUTING Unit 1.pptxMOBILE COMPUTING Unit 1.pptx
MOBILE COMPUTING Unit 1.pptx
 
MOBILE COMPUTING Unit 5.pptx
MOBILE COMPUTING Unit 5.pptxMOBILE COMPUTING Unit 5.pptx
MOBILE COMPUTING Unit 5.pptx
 
Unit 1
Unit 1Unit 1
Unit 1
 

Recently uploaded

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture designssuser87fa0c1
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 

Recently uploaded (20)

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
pipeline in computer architecture design
pipeline in computer architecture  designpipeline in computer architecture  design
pipeline in computer architecture design
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 

WEB TECHNOLOGY Unit-3.pptx

  • 1. Unit – III SERVER SIDE PROGRAMMING Presented By K.Karthick M.E(Ph.D.) Assistant Professor/CSE, Kongunadu College of Engineering And Technology.
  • 2.
  • 3. What is a web application? • A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server and respond to the HTTP request.
  • 4. • CGI (Common Gateway Interface) • CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.
  • 5. • Disadvantages of CGI • There are many problems in CGI technology: • If the number of clients increases, it takes more time for sending the response. • For each request, it starts a process, and the web server is limited to start processes. • It uses platform dependent language e.g. C, C++, perl.
  • 6. Server-side Scripting • Sever-side scripting acts as an interface for the client and also limit the user access the resources on web server. • It can also collects the user’s characteristics in order to customize response.
  • 7.
  • 8. Why Server Side Programming • Though it is technically feasible to implement almost any business logic using client-side programs, logically or functionally it server no purpose when it comes to enterprises application (e.g., banking, air ticketing, e-shopping, etc). • To further explain, going by the client-side programming logic; a bank having 10,000customers would mean that each customer would have a copy of the program(s) in his or her PC (and now even mobiles) which translates to 10,000 programs! • In addition, there are issues like security, resource pooling, concurrent access and manipulations to the database which simply cannot be handled by client-side programs. The answer to most of the issues cited above is-“Server Side Programming”
  • 9. Advantages of Server Side Programs • Some of the advantages of Server Side programs are as follows: • 1. All programs reside in one machine called server. Any number of remote machines (called clients) can access the server programs. • ii. New functionalities to existing programs can be added at the server side which the clients can take advantage of without having to change anything. • iii. Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about client’s hardware or software capabilities. • iv. Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by the server side applications. • v. They are portable and possess the capability to generate dynamic and user-based content (e.g., displaying transaction information of credit card or debit card depending on user’s choice).
  • 10. • Types of Server Side Programs • The following are the different types of server side programs: • (a) Active Server Pages (ASP) • (b) Java Servlets • (c) Java Server Pages (JSP) • (d) Enterprise JavaBeans (EJB) • (e)PHP
  • 11. • There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The advantages of Servlet are as follows: • Better performance: because it creates a thread for each request, not process. • Portability: because it uses Java language. • Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc. • Secure: because it uses java language.
  • 12. What are Servlets? • Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server. • Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. • Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
  • 13. • Performance is significantly better. • Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. • Servlets are platform-independent because they are written in Java. • Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. • The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.
  • 14.
  • 16. What is Servlet Container? • In Java, Servlet container (also known as a Web container) generates dynamic web pages. So servlet container is the essential part of the web server that interacts with the java servlets. Servlet Container communicates between client Browsers and the servlets. • Servlet Container managing the life cycle of servlet. Servlet container loading the servlets into memory, initializing and invoking servlet methods and to destroy them. There are a lot of Servlet Containers like Jboss, Apache Tomcat, WebLogic etc.
  • 17. How does this Servlet Container work?
  • 18. • A client browser accesses a Web server or HTTP server for a page. • The Web server redirects the request to the servlet container (Servlets are HTTP listeners that run inside the servlet container). • The servlet container redirects the request to the appropriate servlet. • The servlet is dynamically retrieved and loaded into the address space of the container, if it is not in the container. The servlet container invokes servlet init () method once when the servlet is loaded first time for initialization. • The servlet container invokes the service () methods of the servlet to process the HTTP request, i.e., read data in the request and formulate a response. The servlet remains in the container’s address space and can process other HTTP requests. • Web servlet generates data (HTML page, picture …) return the dynamically generated results to the correct location.
  • 19. What is SERVLET API? • Before creating the first servlet, you need to understand the Servlet API and Tomcat Servlet container. The Servlet API provides interfaces and classes that are required to built servlets. These interfaces and classes are group into the following two packages : • • javax.servlet • • javax.servlet.http
  • 20. Interfaces Description Servlet Declares life cycle methods that all servlets must implement. ServletConfig Allows servlets to get initialization parameters ServletContext Allows servlets to communicate with its servlet container. ServletRequest Provides client request information to a servlet. ServletResponse Assist a servlet in sending a response to the client. Classes Description GenericServlet Provides a basic implementation of the Servlet interface for protocol independent servlets ServletlnputStream Provides an input stream for reading binary data from a client request. ServletOutputStream Provides an output stream for sending binary data to the client. ServletException Defines a general exception, a servlet can throw when it encounters difficulty. UnavailableException Indicates that a servlet is not available to service client request.
  • 21. Servlets Tasks • Servlets perform the following major tasks − • Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. • Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. • Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. • Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. • Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.
  • 22. Servlets Packages • Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. • Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects. • These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1. • Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current compiler.
  • 23. • Setting up Java Development Kit • This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately. • You can download SDK from Oracle's Java site − Java SE Downloads. • Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
  • 24. • 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.
  • 25.
  • 26. • 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. • 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.
  • 27. • The init method definition looks like this − • public void init() throws ServletException { • // Initialization code... • }
  • 28. • 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 { • }
  • 29. • The doGet() Method • A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method. • public void doGet(HttpServletRequest request, HttpServletResponse response) • throws ServletException, IOException { • // Servlet code • }
  • 30. • The doPost() Method • A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method. • public void doPost(HttpServletRequest request, HttpServletResponse response) • throws ServletException, IOException { • // Servlet code • }
  • 31. • The destroy() Method • The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. • After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this − • public void destroy() { • // Finalization code... • }
  • 32. Architecture Diagram • The following figure depicts a typical servlet life-cycle scenario. • First the HTTP requests coming to the server are delegated to the servlet container. • The servlet container loads the servlet before invoking the service() method. • Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.
  • 33.
  • 34. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } }
  • 36. Types of Servlets • There is a possibility of developing ‘n’ types of servlets, like httpservlet, ftpservlet, smtpservlet etc. for all these protocol specific servlet classes GenericServlet is the common super class containing common properties and logics. So, GenericServlet is not a separate type of servlet. • As of now Servlet API is giving only one subclass to GenericServlet i.e HttpServlet class because all web servers are designed based on the protocol http.
  • 37.
  • 38. What is HTTP? • The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. • HTTP works as a request-response protocol between a client and server. • Example: A client (browser) sends an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.
  • 39. • HTTP Methods • GET • POST • PUT • HEAD • DELETE • PATCH • OPTIONS • CONNECT • TRACE • The two most common HTTP methods are: GET and POST
  • 40. • The GET Method • GET is used to request data from a specified resource. • Note that the query string (name/value pairs) is sent in the URL of a GET request: • /test/demo_form.php?name1=value1&name2=value2 • Some notes on GET requests: • GET requests can be cached • GET requests remain in the browser history • GET requests can be bookmarked • GET requests should never be used when dealing with sensitive data • GET requests have length restrictions • GET requests are only used to request data (not modify)
  • 41. • The POST Method • POST is used to send data to a server to create/update a resource. • The data sent to the server with POST is stored in the request body of the HTTP request: • POST /test/demo_form.php HTTP/1.1 Host: w3schools.com name1=value1&name2=value2
  • 42. GET POST 1) In case of Get request, only limited amount of data can be sent because data is sent in header. In case of post request, large amount of data can be sent because data is sent in body. 2) Get request is not secured because data is exposed in URL bar. Post request is secured because data is not exposed in URL bar. 3) Get request can be bookmarked. Post request cannot be bookmarked. 4) Get request is idempotent . It means second request will be ignored until response of first request is delivered Post request is non-idempotent. 5) Get request is more efficient and used more than Post. Post request is less efficient and used less than get.
  • 43. 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. • HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
  • 44.
  • 45. • Why use Session Tracking? • To recognize the user It is used to recognize the particular user. • Session Tracking Techniques • There are four techniques used in Session tracking: • Cookies • Hidden Form Field • URL Rewriting • HttpSession
  • 46. SESSION TRACKING • HTTP is a stateless protocol. Each request is independent of the previous one. • However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. • Sessions provide such a mechanism. A session can be created via the getSession( ) method of HttpServletRequest.An HttpSession object is returned. • This object can store a set of bindings that associate names with objects. • The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings. • It is important to note that session state is shared among all the servlets that are associated with a particular client.
  • 47. • The following servlet illustrates how to use session state. The getSession( ) method gets the current session. • A new session is created if one does not already exist. The getAttribute( ) method is called to obtain the object that is bound to the name “date”. • That object is a Date object that encapsulates the date and time when this page was last accessed. (Of course, there is no such binding when the page is first accessed.) • A Date object encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name “date” to this object
  • 48. • import java.io.*; • import javax.servlet.*; • import javax.servlet.http.*; • public class DateServlet extends HttpServlet { • public void doGet(HttpServletRequest request,HttpServletResponse response) • throws ServletException, IOException { HttpSession hs = request.getSession(true); response.setContentType("text/html"); • PrintWriter pw = response.getWriter(); pw.print("<B>"); • Date date = (Date)hs.getAttribute("date"); • if(date != null) • { • pw.print("Last access: " + date + "<br>"); • } date = new Date(); • hs.setAttribute("date", date); pw.println("Current date: " + date); • } }
  • 49. Cookies in Servlet • A cookie is a small piece of information that is persisted between the multiple client requests. • A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. How Cookie works: • By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.
  • 50.
  • 51. • Types of Cookie • There are 2 types of cookies in servlets. • Non-persistent cookie • Persistent cookie • 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 signout.
  • 52. • 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.
  • 53. Cookie class • javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies. • Constructor of Cookie class Constructor Description Cookie() constructs a cookie. Cookie(String name, String value) constructs a cookie with a specified name and value.
  • 54. Method Description public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. public String getName() Returns the name of the cookie. The name cannot be changed after creation. public String getValue() Returns the value of the cookie. public void setName(String name) changes the name of the cookie. public void setValue(String value) changes the value of the cookie.
  • 55. • How to create Cookie? • Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie obje ct • response.addCookie(ck);//adding cookie in the response • How to delete Cookie?// it is mainly used to logout or sign out the user • 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
  • 56. How to get Cookies? • Cookie ck[]=request.getCookies(); • for(int i=0;i<ck.length;i++){ • out.print("<br>"+ck[i].getName()+" "+ck[i].getValue()); • //printing name and value of cookie • }
  • 57.
  • 58. • <form action="servlet1" method="post"> • Name:<input type="text" name="userName"/><br/> • <input type="submit" value="go"/> • </form>
  • 59.
  • 60. Hidden Form Field • In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user. • In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser. • <input type="hidden" name="uname" value="Vimal Jaiswal">
  • 61. • Real application of hidden form field • It is widely used in comment form of a website. In such case, we store page id or page name in the hidden field so that each page can be uniquely identified. • Advantage of Hidden Form Field • It will always work whether cookie is disabled or not. • Disadvantage of Hidden Form Field: • It is maintained at server side. • Extra form submission is required on each pages. • Only textual information can be used.
  • 62. Example of using Hidden Form Field
  • 63. URL Rewriting • In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format: • url?name1=value1&name2=value2&?? • A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.
  • 64.
  • 65. • Advantage of URL Rewriting • It will always work whether cookie is disabled or not (browser independent). • Extra form submission is not required on each pages. • Disadvantage of URL Rewriting • It will work only with links. • It can send Only textual information. •
  • 66. HttpSession interface • In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks: • bind objects • view and manipulate information about a session, such as the session identifier, creation time, and last accessed time.
  • 67.
  • 68. • How to get the HttpSession object ? • The HttpServletRequest interface provides two methods to get the object of HttpSession: • public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one. • public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
  • 69. • Commonly used methods of HttpSession interface • public String getId():Returns a string containing the unique identifier value. • public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. • public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. • public void invalidate():Invalidates this session then unbinds any objects bound to it.
  • 70. JSP • Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications using a combination of HTML, XML, and Java code. • JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. • JavaServer 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 %>.
  • 71. Facts About JSP • JSP stands for Java Server Pages. • JSP is a technology to build dynamic web applications. • JSP is a part of Java Enterprise Edition (Java EE). • JSP is similar to HTML pages, but they also contain Java code executed on the server side. • Server-side scripting means the JSP code is processed on the web server rather than the client machine. • A JSP page is a file with a ".jsp" extension that can contain a combination of HTML Tags and JSP codes. • To create a web page, JSP uses a combination of HTML or XML markup, JSP tags, expressions, and Java code.
  • 72. • JSP tags begin with <% and end with %>. • JSP expressions are used to insert dynamic content into the page and begin with <%= and end with %>. • JSP can use JavaBeans to store and retrieve data. • JSP requires a Java development environment and a Java Servlet Container such as Apache Tomcat or Jetty. • JSP is widely used in the industry for creating enterprise web applications. • JSP is an improved extended version of Servlet technology.
  • 73. Why to Learn 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. • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having separate CGI files. • 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. • JavaServer 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. • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
  • 74. The difference between Servlet and JSP Servlet JSP Servlet is a java code. JSP is a HTML based code. Writing code for servlet is harder than JSP as it is HTML in java. JSP is easy to code as it is java in HTML. Servlet plays a controller role in the hasMVC approach. JSP is the view in the MVC approach for showing output. Servlet is faster than JSP. JSP is slower than Servlet because the first step in the has JSP lifecycle is the translation of JSP to java code and then compile. Servlet can accept all protocol requests. JSP only accepts HTTP requests. In Servlet, we can override the service() method. In JSP, we cannot override its service() method.
  • 75. In Servlet by default session management is not enabled, user have to enable it explicitly. In JSP session management is automatically enabled. In Servlet we have to implement everything like business logic and presentation logic in just one servlet file. In JSP business logic is separated from presentation logic by using JavaBeansclient-side. Modification in Servlet is a time-consuming compiling task because it includes reloading, recompiling, JavaBeans and restarting the server. JSP modification is fast, just need to click the refresh button. It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects. There is no method for running JavaScript on the client side in Servlet. While running the JavaScript at the client side in JSP, the client-side validation is used. Packages are to be imported on the top of the program. Packages can be imported into the JSP program(i.e bottom , middleclient-side, or top )
  • 76. Applications of JSP • JSP vs. Active Server Pages (ASP) • The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers. • JSP vs. Pure Servlets • It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. • JSP vs. Server-Side Includes (SSI) • SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like. • JSP vs. JavaScript • JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc. • JSP vs. Static HTML • Regular HTML, of course, cannot contain dynamic information.
  • 77. JSP Environment • JSP environment is a set of tools and technologies used to create dynamic web pages using JavaServer Pages (JSP) technology. It includes the following components: • JSP Engine: A software component that reads and executes JSP files. It converts JSP code into servlets, which are then executed on the server and generate the final HTML. • Web Server: A software that receives requests from clients and sends responses. It is responsible for handling HTTP requests and responses. • Java Runtime Environment (JRE): This software provides the necessary environment for running Java applications, including JSP pages. • Additional Libraries and Frameworks: Additional tools and libraries, such as JavaBeans, JavaServer Faces, and Spring framework, can be used to develop JSP applications. • Development Tools: Integrated development environments (IDEs), such as Eclipse, IntelliJ IDEA, and NetBeans, are used to write, test, and debug JSP code.
  • 78.
  • 79. JSP - Architecture • JSP architecture is a 3-tier architecture that separates a web application's presentation, logic, and data layers. The presentation layer, or client side, is responsible for displaying the user interface and handling user interaction. • The logic layer, or server-side, is responsible for processing user requests and handling business logic. The data layer is responsible for storing and retrieving data from a database or other storage system. This separation of concerns allows for better maintainability and scalability of the application.
  • 80. • A JSP-based web application requires a JSP engine, also known as a web container, to process and execute the JSP pages. The web container is a web server component that manages the execution of web programs such as servlets, JSPs, and ASPs. • When a client sends a request for a JSP page, the web container intercepts it and directs it to the JSP engine. The JSP engine then converts the JSP page into a servlet class, compiles it, and creates an instance of the class. The service method of the servlet class is then called, which generates the dynamic content for the JSP page. • The web container also manages the lifecycle of the JSP pages and servlets, handling tasks such as instantiating, initializing and destroying them. Additionally, it provides security, connection pooling, and session management services to the JSP-based web application.
  • 81. Components of Web container • JSP architecture is a web application development model that defines the structure and organization of a JSP-based web application. It typically consists of the following components: • JSP pages: These are the main building blocks of a JSP application. They contain a combination of HTML, XML, and JSP elements (such as scriptlets, expressions, and directives) that generate dynamic content. • Servlets: JSP pages are converted into servlets by the JSP engine. Servlets are Java classes that handle HTTP requests and generate dynamic content. • JSP engine (web container): This web server component is responsible for processing JSP pages. It converts JSP pages into servlets, compiles them, and runs them in the Java Virtual Machine (JVM). •
  • 82. • JavaBeans: These are reusable Java classes that encapsulate business logic and data. They are used to store and retrieve information from a database or other data sources. • JSTL (JavaServer Pages Standard Tag Library): This is a set of predefined tags that can be used in JSP pages to perform common tasks such as iterating over collections, conditional statements, and internationalization. • Custom Tag Libraries: JSP allows the creation of custom tags that can be used on JSP pages. These reusable Java classes encapsulate complex logic and can generate dynamic content cleanly and consistently.
  • 83. JSP life cycle • A JSP page life cycle is defined as a process from its translation phase to the destruction phase. This lesson describes the various stages of a JSP page life cycle. • The life cycle of a JSP page can be divided into the following phase: • Translation Phase • Compilation Phase • Initialization Phase • Execution Phase • Destruction(Cleanup) Phase
  • 84.
  • 85. Translation Phase • When a user navigates to a page ending with a .jsp extension in their web browser, the web browser sends an HTTP request to the webserver. • The webserver checks if a compiled version of the JSP page already exists. • If the JSP page's compiled version does not exist, the file is sent to the JSP Servlet engine, which converts it into servlet content (with .java extension). This process is known as translation. • The web container automatically translates the JSP page into a servlet. So as a developer, you don't have to worry about converting it manually.
  • 86. Compilation Phase • In case the JSP page was not compiled previously or at any point in time, then the JSP page is compiled by the JSP engine. • In this compilation phase, the Translated .java file of the servlet is compiled into the Java servlet .class file.
  • 87. Initialization Phase • In this Initialization phase: Here, the container will: • Load the equivalent servlet class. • Create instance. • Call the jspInit() method for initializing the servlet instance. • This initialization is done only once with the servlet's init method where database connection, opening files, and creating lookup tables are done.
  • 88. • Execution phase • This Execution phase is responsible for all JSP interactions and logic executions for all requests until the JSP gets destroyed. As the requested JSP page is loaded and initiated, the JSP engine has to invoke the _jspService() method. This method is invoked as per the requests, responsible for generating responses for the associated requests, and responsible for all HTTP methods. • Destruction(Cleanup) Phase • This destruction phase is invoked when the JSP has to be cleaned up from use by the container. The jspDestroy() method is invoked. You can incorporate and write cleanup codes inside this method for releasing database connections or closing any file.
  • 89.
  • 90.
  • 91. • 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
  • 92. • public void jspInit(){ • // Initialization code... • } • 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 −
  • 93. • void _jspService(HttpServletRequest request, HttpServletResponse response) { • // Service handling code... • } • The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE, etc.
  • 94. • 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. • }
  • 95. • JSP SCRIPTING ELEMENTS: • 3 types of scripting elements: • Scrip let tag • Expression tag • Declaration tag • To insert java code inside jsp
  • 96. JSP - Syntax • Elements of JSP • The Scriptlet • A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. • Following is the syntax of Scriptlet − • <% code fragment %> • <jsp:scriptlet> • code fragment • </jsp:scriptlet>
  • 97. • JSP Declarations • A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. • Following is the syntax for JSP Declarations − • <%! declaration; [ declaration; ]+ ... %> • Example: • <%! int i = 0; %> • <%! int a, b, c; %> • <%! Circle a = new Circle(2.0); %>
  • 98. • JSP Expression • A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. • <%= expression %> • JSP Comments • JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out", a part of your JSP page. • Following is the syntax of the JSP comments − • <%-- This is JSP comment --%>
  • 99. • <html> • <head><title>A Comment Test</title></head> • <body> • <h2>A Test of Comments</h2> • <%-- This comment will not be visible in the page source --%> • </body> • </html>
  • 100. • JSP Directives • A JSP directive affects the overall structure of the servlet class. It usually has the following form − • <%@ directive attribute="value" %> 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
  • 101.
  • 102. JavaBean • A JavaBean is a Java class that should follow the following conventions: • It should have a no-arg constructor. • It should be Serializable. • It should provide methods to set and get the values of the properties, known as getter and setter methods.
  • 103. What is JavaBeans in JSP? • Bean means component. Components mean reusable objects. JavaBean is a reusable component. Java Bean is a normal java class that may declare properties, setter, and getter methods in order to represent a particular user form on the server-side. JavaBean is a java class that is developed with a set of conventions. The conventions are: • The class should be public and must not be final, abstract. • Recommend to implement serializable. • Must have direct/indirect param constructor. • Member variables should be non-static and private. • Every bean property should have one setter method and one getter method with the public modifier.
  • 104. • Working of JavaBeans in JSP • First, the browser sends the request for the JSP page. Then the JSP page accesses Java Bean and invokes the business logic. After invoking the business logic Java Bean connects to the database and gets/saves the data. At last, the response is sent to the browser which is generated by the JSP.
  • 105. • Advantages of Java Beans • It is easy to reuse the software components. • The properties and methods of Java Bean can be exposed to another application. • Disadvantages of Java Beans • JavaBeans are mutable objects so it cannot take advantage of immutable objects. • JavaBeans will be in an inconsistent state because of creating the setter and getter method for each property separately. • Java Bean Properties • getPropertyName(): This method is used to read the property which is also called accessor. • setPropertyName(): This method is used to write the property which is also called mutator.
  • 106. • package mypack; • public class Employee implements java.io.Serializable • { • private int id; • private String name; • public Employee(){} • public void setId(int id) • { • this.id=id; • } • public int getId() • {return id; • } • public void setName(String name) • { • this.name=name; • } • public String getName(){return name;} • }
  • 107. • package mypack; • public class Test{ • public static void main(String args[]){ • Employee e=new Employee();//object is created • e.setName("Arjun");//setting value to the object • System.out.println(e.getName()); • }}
  • 108. JSP - Standard Tag Library (JSTL) Tutorial • The JavaServer 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, internationalization tags, and SQL tags. It also provides a framework for integrating the existing custom tags with the JSTL tags.
  • 109. • Install JSTL Library • To begin working with JSP tages you need to first install the JSTL library. If you are using the Apache Tomcat container, then follow these two steps − • Step 1 − Download the binary distribution from Apache Standard Taglib and unpack the compressed file. • Step 2 − To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR files in the distribution's 'lib' directory to your application's webappsROOTWEB- INFlib directory. • To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses the library.
  • 110. • Classification of The JSTL Tags • The JSTL tags can be classified, according to their functions, into the following JSTL tag library groups that can be used when creating a JSP page − • Core Tags • Formatting tags • SQL tags • XML tags • JSTL Functions
  • 111. Core Tags • The core group of tags are the most commonly used JSTL tags. Following is the syntax to include the JSTL Core library in your JSP − • <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
  • 112. Formatting Tags • The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Websites. Following is the syntax to include Formatting library in your JSP − • <%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
  • 113. SQL Tags • The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server. • Following is the syntax to include JSTL SQL library in your JSP − • <%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
  • 114. XML tags • The JSTL XML tags provide a JSP-centric way of creating and manipulating the XML documents. Following is the syntax to include the JSTL XML library in your JSP. • The JSTL XML tag library has custom tags for interacting with the XML data. This includes parsing the XML, transforming the XML data, and the flow control based on the XPath expressions. • <%@ taglib prefix = "x" • uri = "http://java.sun.com/jsp/jstl/xml" %>
  • 115. MVC Framework - Introduction • The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. • Each of these components are built to handle specific development aspects of an application. • MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects.
  • 116.
  • 117.
  • 118. • Model • The Model component corresponds to all the data-related logic that the user works with. This can represent either the data that is being transferred between the View and Controller components or any other business logic-related data. • For example, a Customer object will retrieve the customer information from the database, manipulate it and update it data back to the database or use it to render data. • View • The View component is used for all the UI logic of the application. For example, the Customer view will include all the UI components such as text boxes, dropdowns, etc. that the final user interacts with.
  • 119. • Controller • Controllers act as an interface between Model and View components to process all the business logic and incoming requests, manipulate data using the Model component and interact with the Views to render the final output. • For example, the Customer controller will handle all the interactions and inputs from the Customer View and update the database using the Customer Model. • The same controller will be used to view the Customer data.
  • 120. ASP.NET MVC • ASP.NET supports three major development models: Web Pages, Web Forms and MVC (Model View Controller). • ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with the existing ASP.NET features, such as master pages, authentication, etc. Within .NET, this framework is defined in the System.Web.Mvc assembly. • The latest version of the MVC Framework is 5.0. We use Visual Studio to create ASP.NET MVC applications which can be added as a template in Visual Studio.
  • 121. • Implementation • We are going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly. • MVCPatternDemo, our demo class, will use StudentController to demonstrate use of MVC pattern.