SlideShare uma empresa Scribd logo
1 de 54
Servlets
Servlets
 Java Servlet is a java object file developed as a
component and runs on the server.
 Servlets are programs that run on a Web or application
server and act as a middle layer between a request coming
from a Web browser or other HTTP client and databases or
applications on the HTTP server
 Servlets is a component can be invoked from HTML.
Note:
 Servlets cannot run independently as a main application
like the java applet, the servlet does not have main method.
Servlets
 Servlet do not display a graphical interface to the user.
 A servlet’s work is done at the server and only the results
of the servlet’s processing are returned to the client in the
form of HTML.
 A Servlet is a Java technology-based Web component,
managed by a container that generates dynamic content.
 Like other Java technology-based components, Servlets
are platform-independent Java classes that are compiled
to platform-neutral byte code that can be loaded
dynamically into and run by a Java technology-enabled
Web server.
Predessor of servlet
 In the early days of the web u have to
use the Common Gateway
interface(CGI) to perform server side
processing of forms and interaction with
the datadase.
 Later microsoft ASP technology enable
server side processing using Vbscript,
Javascript.
Difference Between Servlet & CGI
 The advantages of using servlets are their fast
performance and ease of use combined with more power
over traditional CGI (Common Gateway Interface).
 Traditional CGI scripts written in Java have a number of
disadvantages when it comes to performance
 When an HTTP request is made, a new process is created
for each call of the CGI script. This overhead of process
creation can be very system-intensive, especially when the
script does relatively fast operations. Thus, process
creation will take more time than CGI script execution.
 Java servlets solve this, as a servlet is not a separate
process. Each request to be handled by a servlet is
handled by a separate Java thread within the Web server
process, omitting separate process forking (split) by the
HTTP domain.
Difference Between Servlet & CGI
 Simultaneous CGI request causes the CGI script to be
copied and loaded into memory as many times as there
are requests.
 However, with servlets, there are the same amount of
threads as requests, but there will only be one copy of the
servlet class created in memory that stays there also
between requests.
 A servlet can be run by a servlet engine in a restrictive
environment, called a sandbox. This is similar to an applet
that runs in the sandbox of the Web browser. This makes a
restrictive use of potentially harmful servlets possible.
Advantages of Servlets
 Platform Independence:
Servlets are written entirely in java so these are platform
independent.
Servlets can run on any Servlet enabled web server.
 Performance
 Due to interpreted nature of java, programs written in
java are slow.
 But the java Servlets runs very fast. These are due to
the way Servlets run on web server.
 For any program initialization takes significant amount
of time. But in case of Servlets initialization takes place
first time it receives a request and remains in memory till
times out or server shut downs.
 Extensibility
Java Servlets are developed in java which is robust, well-
designed and object oriented language which can be
extended or polymorphed into new objects.
So the java Servlets take all these advantages and can
be extended from existing class to provide the ideal
solutions.
 4. Safety Java provides very good safety features
like memory management, exception handling etc.
Servlets inherits all these features and emerged as
a very powerful web server extension.
 5. Secure Servlets are server side components, so it
inherits the security provided by the web server.
Servlets are also benefited with Java Security
Manager.
Life cycle of a servlet
• Init () Method
• Service () Method
• Destroy() method
Init () Method:-
 During initialization stage of the Servlet life cycle, the web
container initializes the servlet instance by calling the init()
method.
 The container passes an object implementing the ServletConfig
interface via the init() method.
 This configuration object allows the servlet to access name-
value initialization parameters from the web application.
• Service () Method:-
◦ After initialization, the servlet can service client requests. each request
is serviced in its own separate thread.
◦ The Web container calls the service() method of the servlet for every
request.
◦ The service() method determines the kind of request being made and
dispatches it to an appropriate method to handle the request.
◦ The developer of the servlet must provide an implementation for these
methods. If a request for a method that is not implemented by the
servlet is made, the method of the parent class is called, typically
resulting in an error being returned to the requester.
• Destroy() method:-
◦ Finally, the Web container calls the destroy() method that takes the
servlet out of service. The destroy() method, like init(), is called only
once in the lifecycle of a servlet.
Types of servlets
• Generic Servlets:
Generic Servlets are protocal independent that
is they do not contain any inherent support for any
protocal.
Generic Servlets handle request by overriding
the services() method.
• HTTP Servlets:
HTTP Servlets are HTTP protocal specific. This
makes it very useful in a browser environment.
In case of HTTP Servlets, service() method
route the request to another method based on which
HTTP transfer method is used.
Using Tomcat for Servlet Development
 To create servlets, you will need access
to a servlet development environment.
 Tomcat is an open-source product
maintained by the Jakarta Project of the
Apache Software Foundation.
 It contains the class libraries,
documentation, and runtime support that
you will need to create and test servlets.
Servlet API
 Two packages contain the classes and interfaces that are
required to build servlets.
 javax.servlet
 javax.servlet.http.
They constitute the Servlet API.
 These packages are not part of the Java core packages.
Instead, they are standard extensions provided by Tomcat.
 The Servlet API has been in a process of ongoing
development and enhancement. The current servlet
specification is version 2.4,
Simple Servlet program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
public class ServletTemplate extends HttpServlet {
Declaring a class Name of the class
Subclass the httpservlet
class to create a servlet
public void doGet(HttpServletRequest request,
HttpServletResponse response)
You are overriding the doget
method that comes from the
httpservlet class
The parameter is a
httpsevletrequest object that
you are naming request
The parameter is a
httpsevletresponse object that
you are naming response
throws ServletException, IOException
You are declaring that the doget
method can throw two exceptions
ServletException, IOException
Executing Servlet Program
Setting Class path
1. My computer->Properties->Advance->Environment
Variables->
Edit User Variable
Variable name: path
Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program
Filesservlet.jar;
Edit System Variable
Variable name: CLASSPATH
Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program
Filesservlet.jar;%.%;
2. Running the servlet in cmd prompt
C:Documents and Settingseec-cs>cd
C:>cd C:Program FilesApache Tomcat
4.0webappsexamplesWEB-INFclasses
C:Program FilesApache Tomcat
4.0webappsexamplesWEB-INFclasses>javac HelloW
orld.java
C:Program FilesApache Tomcat
4.0webappsexamplesWEB-INFclasses>
3. Start Tomcat
4. Open IE and type below link
 http://localhost:8080/examples/servlet/H
elloWorld
javax.servlet Package
 The javax.servlet package contains a number of
interfaces and classes that establish the framework in
which servlets operate.
 The following table summarizes the core interfaces
that are provided in this package.
 All servlets must implement this interface or extend a
class that implements the interface.
Reading Servlet Parameters
 The ServletRequest interface includes
methods that allow you to read the names and
values of parameters that are included in a
client request
javax.servlet.http package
Classes
HttpServletRequest Interface
 The HttpServletRequest interface enables a servlet to
obtain information about a client request.
HttpServletResponse Interface
The HttpServletResponse interface enables a servlet
to formulate an HTTP response to a client.
HttpSession Interface
 The HttpSession interface enables a servlet to read
and write the state information that is associated with
an HTTP session.
HttpSessionBindingListener Interface
 The HttpSessionBindingListener
interface is implemented by objects that
need to be notified when they are bound
to or unbound from an HTTP session.
Handling HTTP Requests and Responses
 Servlets can be used for handling both the GET Requests
and the POST Requests.
 The HttpServlet class is used for handling HTTP GET /
POST Requests as it has some specialized methods that
can efficiently handle the HTTP requests.
 These methods are:
◦ doGet( )
◦ doPost( )
◦ doPut( )
◦ doDelete( )
◦ doOptions( )
◦ doTrace( )
◦ doHead( )
 An individual developing Servlets for handling HTTP
Requests needs to override one of these methods in
order to process the request and generate a response.
The servlet is invoked dynamically when an end-user
submits a form.
 If Form method attribute value is GET, then doGet( )
method of servlet will be called, if method=”POST”
doPost( ) method of servlet which is mentioned as action
will be called.
 Ex: <form action=”sampleServlet” method=”GET”>
 In above example since method is GET, sampleServlet’s
doGet( ) will be called.
 Both doGet( ) and doPost( ) takes two arguments objects of
HttpServletRequest and HttpServletResponse classes.
 Ex: public void doGet(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException
 public void doPost(HttpServletRequest req,HttpServletResponse
res) throws ServletException, IOException
 In above example req is an object of HttpServletRequest class
which contains the incoming information (information passed by
client program).
 The res is an object of HttpServletResponse class which
contains the outgoing information (response back to client).
Getting request data
 The request object of HttpServletRequest class contains the
incoming request data sent by client program.
 By using the following methods we can get the request parameter
values.
 Request parameters for the servlet are the strings sent by the
client to a servlet container as part of its request.
 The parameters are stored as a set of name-value pairs. Multiple
parameter values can exist for any given parameter name. The
following methods of the ServletRequest interface are available to
access parameters:
◦ getParameter ( )
◦ getParameterNames ( )
◦ getParameterValues ( )
 getParameter ( ) method is used to access single
value, takes name of input parameter as an argument
and returns a string object.
Ex: String s=req.getParameter(“user”);
 getParameterValues ( ) method is used to access
multiple value entered by user in a client program, it
takes name of input parameter as an argument and
returns a array of string object.
 Ex: String [ ] lang=req.getParameterValues
(“language”);
When we want to access all the parameters of a form, we make
use of Enumeration object and its methods as shown below.
Ex: Enumeration en;
String pname;
String pvalue;
en = request.getParameterNames();
while (en.hasMoreElements())
{
pname = (String) en.nextElement();
pvalue= request.getParameterValues(pname);
for(int i=0;i<pvalue.length;i++)
{
out.println(pvalue[i]);
}
}
Cookies
 Cookies are small bits of textual information that a Web
server sends to a browser and that the browser returns
unchanged when visiting the same Web site or domain
later.
 To send cookies to the client, a servlet would create one or
more cookies with the appropriate names and values via
new Cookie(name, value).
 A Cookie is created by calling the Cookie constructor, which
takes two strings: the cookie name and the cookie value.
Neither the name nor the value should contain whitespace
or any of: [ ] ( ) = , " / ? @ : ;
 Ex: Cookie userCookie = new Cookie("user", "uid1234");
 The cookie is added to the Set-Cookie response
header by means of the addCookie method of
HttpServletResponse.
 Cookie userCookie = new Cookie("user", "uid1234");
 response.addCookie(userCookie);
The getXXX( ) method can be used to retrieve the attribute XXX of a cookie
object, which returns the string value. For example getName( ) used to
retrieve the name of a cookie.
The setXXX( ) method is used to set the value of XXX attribute of a cookie,
which accepts the value as argument which need to be set.
Ex: c.setValue(“123”); It sets Value attribute of cookie c as 123.
Servlet-Sessions
 There are a number of problems that arise from the fact that
HTTP is a "stateless" protocol.
 In particular, when you are doing on-line shopping, it is a real
annoyance that the Web server can't easily remember previous
transactions.
 This makes applications like shopping carts very problematic:
when you add an entry to your cart, how does the server know
what's already in your cart? Even if servers did retain contextual
information, you'd still have problems with e-commerce.
 When you move from the page where you specify what you want
to buy (hosted on the regular Web server) to the page that takes
your credit card number and shipping address (hosted on the
secure server that uses SSL), how does the server remember
what you were buying?
 Servlets provide an outstanding
technical solution: the HttpSession API.
 “A session is created each time a client
requests service from a Java servlet.
The servlet processes the request and
responds accordingly, after which the
session is terminated.”
JSP - Java Server Pages
Introduction
 JSP is one of the most powerful, easy-to-use,
and fundamental tools in a Web-site developer's
toolbox.
 JSP combines HTML and XML with Java servlet
(server application extension) and JavaBeans
technologies to create a highly productive
environment for developing and deploying
reliable, interactive, high-performance platform-
independent Web sites.
 JSP facilitates the creation of dynamic content
on the server.
 It is part of the Java platform's integrated
solution for server-side programming, which
provides a portable alternative to other server-
side technologies, such as CGI.
 JSP integrates numerous Java application
technologies, such as Java servlet, JavaBeans,
JDBC, and Enterprise JavaBeans.
 It also separates information presentation from
application logic and fosters a reusable
component model of programming.
Advantages of JSP over Servlets
 Servlet use println statements for printing an HTML
document which is usually very difficult to use. JSP has no
such tedious task to maintain.
 JSP needs no compilation, CLASSPATH setting and
packaging.
 In a JSP page visual content and logic are seperated,
which is not possible in a servlet.
 There is automatic deployment of a JSP; recompilation is
done automatically when changes are made to JSP pages.
 Usually with JSP, Java Beans and custom tags web
application is simplified.
Fundamental JSP Tags
 JSP tags are an important syntax element of Java Server
Pages which start with "<%" and end with "%>" just like
HTML tags. JSP tags normally have a "start tag", a "tag
body" and an "end tag". JSP tags can either be predefined
tags or loaded from an external tag library.
 Fundamental tags used in Java Server Pages are classified
into the following categories:-
 Declaration tag
 Expression tag
 Directive tag
 Scriptlet tag
 Comments
Declaration tag
 The declaration tag is used within a Java Server page to
declare a variable or method that can be referenced by
other declarations, scriptlets, or expressions in a java
server page.
 A declaration tag does not generate any output on its own
and is usually used in association with Expression or
Scriplet Tags.
 Declaration tag starts with "<%!" and ends with "%>"
surrounding the declaration.
Syntax :- <%! Declaration %>
Example: <%! int var = 1; %>
<%! int x, y ; %>
Expression tag
 An expression tag is used within a Java
Server page to evaluate a java expression
at request time.
 The expression enclosed between "<%="
and "%>" tag elements is first converted
into a string and sent inline to the output
stream of the response.
Syntax :- <%= expression %>
Example: <%= new java.util.Date() %>
Directive tag
 Directive tag is used within a Java Server
page to specify directives to the application
server .
 The directives are special messages which
may use name-value pair attributes in the
form attr="value".
Syntax :- <%@directive attribute="value" %>
Where directive may be:
1. page: page is used to provide the information about it.
Example: <%@page language="java" %>
2. include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %>
3. taglib: taglib is used to use the custom tags in the JSP
pages (custom tags allows us to defined our own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag"
%>
Scriptlet tag
 A Scriptlet tag is used within a Java Server
page to execute a java source code scriplet
which is enclosed between "<%" and "%>" tag
elements.
 The output of the java source code scriplet
specified within the Scriptlet tag is executed at
the server end and is inserted in sequence with
rest of the web document for the client to
access through web browser.
Syntax :- <% java code %>
Comments
 Comments tag is used within a Java Server
page for documentation of Java server page
code.
 Comments surrounded with "<%/*" and "*/%"
tag elements are not processed by JSP engine
and therefore do not appear on the client side
web document but can be viewed through the
web browser’s "view source" option.
 Syntax :- <%-- comment -- %>
Request String
 The browser generates a user request string whenever the
submit is selected.
 The User request string consists of the URL and the query
string.
http://localhost:8080/examples/test/reg.jsp?fname=“bob”&lna
me=“smith”
 The getParameter(name) is the method used to parse a
value of a specified field.
<% string firstname = request.getParameter(fname)
string lastname = request.getParameter(lname)
%>
User Sessions
 A JSP program must be able to track a
session as a client moves between HTML
pages and JSP programs.
There are three commonly used methods to
track a session.
1. Using Hidden Field
2. Using Cookies
3. Using JavaBean
Cookies
 Cookies is a small piece of information created by a JSP program that is
stored on the Client’s hard disk by the browser.
 You can create and read a cookie by using methods of the cookie class
and the response object.
Example: how to create a cookie
<HTML>
<HEAD>
<TITLE>JSP PROGRAMMING </TITLE>
</HEAD>
<BODY>
<%! String MyCookieName = “userId”;
String MyCookieValue = “Jk12345”;
Response.addCookie(new Cookie(MyCookieName, MyCookieValue));
%>
</BODY>
</HTML>
HOW TO READ A COOKIE
<HTML>
<HEAD>
<TITLE> JSP Programming</TITLE>
</HEAD>
<BODY>
<%! String MyCookieName=“userID”;
String MyCookieValue;
String Cname,Cvalue;
int found=0;
Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++){
CName=cookies[i].getName();
CValue= cookie[i].getValue();
if(MyCookieName.equals(cookieNames[i])){
found=1;
MyCookieValue=CookieValue;
}
}
if(found==1){ %>
<p> Cookie name =<% MYCookieName%></p>
<p> Cookie Value=<% MyCookieValue %></p>
<&}>
</BODY>
</HTML>
Session Objects
 A JSP database system is able to share
information among JSP programs within
a session by using a session object.
 Each time a session is created, a unique
ID is assigned to the session and stored
as a cookie

Mais conteúdo relacionado

Mais procurados (20)

Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Files in java
Files in javaFiles in java
Files in java
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Java servlets
Java servletsJava servlets
Java servlets
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 

Destaque

Destaque (8)

EJB .
EJB .EJB .
EJB .
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 
Ch 2 lattice & boolean algebra
Ch 2 lattice & boolean algebraCh 2 lattice & boolean algebra
Ch 2 lattice & boolean algebra
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in java
 
Tutorial su JMS (Java Message Service)
Tutorial su JMS (Java Message Service)Tutorial su JMS (Java Message Service)
Tutorial su JMS (Java Message Service)
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Java Mail
Java MailJava Mail
Java Mail
 
JMS - Java Messaging Service
JMS - Java Messaging ServiceJMS - Java Messaging Service
JMS - Java Messaging Service
 

Semelhante a Chapter 3 servlet & jsp

Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
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
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.pptsindhu991994
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and ServletsRaghu nath
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache TomcatAuwal Amshi
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music storeADEEBANADEEM
 
Java Servlets
Java ServletsJava Servlets
Java ServletsNitin Pai
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGPrabu U
 

Semelhante a Chapter 3 servlet & jsp (20)

Java Servlet
Java ServletJava Servlet
Java Servlet
 
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
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
192563547-Servletsjhb,mnjhjhjm,nm,-Pres-ppt.ppt
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
J servlets
J servletsJ servlets
J servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Servlets
ServletsServlets
Servlets
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
SERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMINGSERVER SIDE PROGRAMMING
SERVER SIDE PROGRAMMING
 
Weblogic
WeblogicWeblogic
Weblogic
 
Servlet.pptx
Servlet.pptxServlet.pptx
Servlet.pptx
 

Mais de Jafar Nesargi

Network adpater,cabel,cards ,types, network devices
Network adpater,cabel,cards ,types, network devicesNetwork adpater,cabel,cards ,types, network devices
Network adpater,cabel,cards ,types, network devicesJafar Nesargi
 
An introduction to networking
An introduction to networkingAn introduction to networking
An introduction to networkingJafar Nesargi
 
Computer basics Intro
Computer basics IntroComputer basics Intro
Computer basics IntroJafar Nesargi
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database languageJafar Nesargi
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relationalJafar Nesargi
 
Chapter 4 record storage and primary file organization
Chapter 4 record storage and primary file organizationChapter 4 record storage and primary file organization
Chapter 4 record storage and primary file organizationJafar Nesargi
 
Introduction to-oracle
Introduction to-oracleIntroduction to-oracle
Introduction to-oracleJafar Nesargi
 
Cascading style sheets
Cascading style sheetsCascading style sheets
Cascading style sheetsJafar Nesargi
 
Session1 gateway to web page development
Session1   gateway to web page developmentSession1   gateway to web page development
Session1 gateway to web page developmentJafar Nesargi
 
Record storage and primary file organization
Record storage and primary file organizationRecord storage and primary file organization
Record storage and primary file organizationJafar Nesargi
 
Introduction to-oracle
Introduction to-oracleIntroduction to-oracle
Introduction to-oracleJafar Nesargi
 

Mais de Jafar Nesargi (20)

Network adpater,cabel,cards ,types, network devices
Network adpater,cabel,cards ,types, network devicesNetwork adpater,cabel,cards ,types, network devices
Network adpater,cabel,cards ,types, network devices
 
An introduction to networking
An introduction to networkingAn introduction to networking
An introduction to networking
 
Computer basics Intro
Computer basics IntroComputer basics Intro
Computer basics Intro
 
Css
CssCss
Css
 
Chapter 7 relation database language
Chapter 7 relation database languageChapter 7 relation database language
Chapter 7 relation database language
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relational
 
Chapter 4 record storage and primary file organization
Chapter 4 record storage and primary file organizationChapter 4 record storage and primary file organization
Chapter 4 record storage and primary file organization
 
Chapter3
Chapter3Chapter3
Chapter3
 
Introduction to-oracle
Introduction to-oracleIntroduction to-oracle
Introduction to-oracle
 
Chapter2
Chapter2Chapter2
Chapter2
 
Cascading style sheets
Cascading style sheetsCascading style sheets
Cascading style sheets
 
Session1 gateway to web page development
Session1   gateway to web page developmentSession1   gateway to web page development
Session1 gateway to web page development
 
Introduction to jsp
Introduction to jspIntroduction to jsp
Introduction to jsp
 
Rmi
RmiRmi
Rmi
 
Java bean
Java beanJava bean
Java bean
 
Networking
NetworkingNetworking
Networking
 
Chapter2 j2ee
Chapter2 j2eeChapter2 j2ee
Chapter2 j2ee
 
Chapter 1 swings
Chapter 1 swingsChapter 1 swings
Chapter 1 swings
 
Record storage and primary file organization
Record storage and primary file organizationRecord storage and primary file organization
Record storage and primary file organization
 
Introduction to-oracle
Introduction to-oracleIntroduction to-oracle
Introduction to-oracle
 

Último

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Chapter 3 servlet & jsp

  • 2. Servlets  Java Servlet is a java object file developed as a component and runs on the server.  Servlets are programs that run on a Web or application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server  Servlets is a component can be invoked from HTML. Note:  Servlets cannot run independently as a main application like the java applet, the servlet does not have main method.
  • 3. Servlets  Servlet do not display a graphical interface to the user.  A servlet’s work is done at the server and only the results of the servlet’s processing are returned to the client in the form of HTML.  A Servlet is a Java technology-based Web component, managed by a container that generates dynamic content.  Like other Java technology-based components, Servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
  • 4. Predessor of servlet  In the early days of the web u have to use the Common Gateway interface(CGI) to perform server side processing of forms and interaction with the datadase.  Later microsoft ASP technology enable server side processing using Vbscript, Javascript.
  • 5. Difference Between Servlet & CGI  The advantages of using servlets are their fast performance and ease of use combined with more power over traditional CGI (Common Gateway Interface).  Traditional CGI scripts written in Java have a number of disadvantages when it comes to performance  When an HTTP request is made, a new process is created for each call of the CGI script. This overhead of process creation can be very system-intensive, especially when the script does relatively fast operations. Thus, process creation will take more time than CGI script execution.  Java servlets solve this, as a servlet is not a separate process. Each request to be handled by a servlet is handled by a separate Java thread within the Web server process, omitting separate process forking (split) by the HTTP domain.
  • 6. Difference Between Servlet & CGI  Simultaneous CGI request causes the CGI script to be copied and loaded into memory as many times as there are requests.  However, with servlets, there are the same amount of threads as requests, but there will only be one copy of the servlet class created in memory that stays there also between requests.  A servlet can be run by a servlet engine in a restrictive environment, called a sandbox. This is similar to an applet that runs in the sandbox of the Web browser. This makes a restrictive use of potentially harmful servlets possible.
  • 7. Advantages of Servlets  Platform Independence: Servlets are written entirely in java so these are platform independent. Servlets can run on any Servlet enabled web server.  Performance  Due to interpreted nature of java, programs written in java are slow.  But the java Servlets runs very fast. These are due to the way Servlets run on web server.  For any program initialization takes significant amount of time. But in case of Servlets initialization takes place first time it receives a request and remains in memory till times out or server shut downs.
  • 8.  Extensibility Java Servlets are developed in java which is robust, well- designed and object oriented language which can be extended or polymorphed into new objects. So the java Servlets take all these advantages and can be extended from existing class to provide the ideal solutions.  4. Safety Java provides very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.  5. Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.
  • 9. Life cycle of a servlet • Init () Method • Service () Method • Destroy() method Init () Method:-  During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method.  The container passes an object implementing the ServletConfig interface via the init() method.  This configuration object allows the servlet to access name- value initialization parameters from the web application.
  • 10. • Service () Method:- ◦ After initialization, the servlet can service client requests. each request is serviced in its own separate thread. ◦ The Web container calls the service() method of the servlet for every request. ◦ The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. ◦ The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester. • Destroy() method:- ◦ Finally, the Web container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet.
  • 11.
  • 12. Types of servlets • Generic Servlets: Generic Servlets are protocal independent that is they do not contain any inherent support for any protocal. Generic Servlets handle request by overriding the services() method. • HTTP Servlets: HTTP Servlets are HTTP protocal specific. This makes it very useful in a browser environment. In case of HTTP Servlets, service() method route the request to another method based on which HTTP transfer method is used.
  • 13. Using Tomcat for Servlet Development  To create servlets, you will need access to a servlet development environment.  Tomcat is an open-source product maintained by the Jakarta Project of the Apache Software Foundation.  It contains the class libraries, documentation, and runtime support that you will need to create and test servlets.
  • 14. Servlet API  Two packages contain the classes and interfaces that are required to build servlets.  javax.servlet  javax.servlet.http. They constitute the Servlet API.  These packages are not part of the Java core packages. Instead, they are standard extensions provided by Tomcat.  The Servlet API has been in a process of ongoing development and enhancement. The current servlet specification is version 2.4,
  • 15. Simple Servlet program import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>Hello World!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); } }
  • 16. public class ServletTemplate extends HttpServlet { Declaring a class Name of the class Subclass the httpservlet class to create a servlet
  • 17. public void doGet(HttpServletRequest request, HttpServletResponse response) You are overriding the doget method that comes from the httpservlet class The parameter is a httpsevletrequest object that you are naming request The parameter is a httpsevletresponse object that you are naming response
  • 18. throws ServletException, IOException You are declaring that the doget method can throw two exceptions ServletException, IOException
  • 19. Executing Servlet Program Setting Class path 1. My computer->Properties->Advance->Environment Variables-> Edit User Variable Variable name: path Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program Filesservlet.jar; Edit System Variable Variable name: CLASSPATH Variable Value: C:Program FilesJavajdk1.5.0_03bin;C:Program Filesservlet.jar;%.%;
  • 20. 2. Running the servlet in cmd prompt C:Documents and Settingseec-cs>cd C:>cd C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses>javac HelloW orld.java C:Program FilesApache Tomcat 4.0webappsexamplesWEB-INFclasses>
  • 21. 3. Start Tomcat 4. Open IE and type below link  http://localhost:8080/examples/servlet/H elloWorld
  • 22. javax.servlet Package  The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.  The following table summarizes the core interfaces that are provided in this package.  All servlets must implement this interface or extend a class that implements the interface.
  • 23. Reading Servlet Parameters  The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a client request
  • 25. HttpServletRequest Interface  The HttpServletRequest interface enables a servlet to obtain information about a client request.
  • 26. HttpServletResponse Interface The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
  • 27. HttpSession Interface  The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session.
  • 28. HttpSessionBindingListener Interface  The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session.
  • 29. Handling HTTP Requests and Responses  Servlets can be used for handling both the GET Requests and the POST Requests.  The HttpServlet class is used for handling HTTP GET / POST Requests as it has some specialized methods that can efficiently handle the HTTP requests.  These methods are: ◦ doGet( ) ◦ doPost( ) ◦ doPut( ) ◦ doDelete( ) ◦ doOptions( ) ◦ doTrace( ) ◦ doHead( )
  • 30.  An individual developing Servlets for handling HTTP Requests needs to override one of these methods in order to process the request and generate a response. The servlet is invoked dynamically when an end-user submits a form.  If Form method attribute value is GET, then doGet( ) method of servlet will be called, if method=”POST” doPost( ) method of servlet which is mentioned as action will be called.  Ex: <form action=”sampleServlet” method=”GET”>  In above example since method is GET, sampleServlet’s doGet( ) will be called.
  • 31.  Both doGet( ) and doPost( ) takes two arguments objects of HttpServletRequest and HttpServletResponse classes.  Ex: public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException  public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException  In above example req is an object of HttpServletRequest class which contains the incoming information (information passed by client program).  The res is an object of HttpServletResponse class which contains the outgoing information (response back to client).
  • 32. Getting request data  The request object of HttpServletRequest class contains the incoming request data sent by client program.  By using the following methods we can get the request parameter values.  Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request.  The parameters are stored as a set of name-value pairs. Multiple parameter values can exist for any given parameter name. The following methods of the ServletRequest interface are available to access parameters: ◦ getParameter ( ) ◦ getParameterNames ( ) ◦ getParameterValues ( )
  • 33.  getParameter ( ) method is used to access single value, takes name of input parameter as an argument and returns a string object. Ex: String s=req.getParameter(“user”);  getParameterValues ( ) method is used to access multiple value entered by user in a client program, it takes name of input parameter as an argument and returns a array of string object.  Ex: String [ ] lang=req.getParameterValues (“language”);
  • 34. When we want to access all the parameters of a form, we make use of Enumeration object and its methods as shown below. Ex: Enumeration en; String pname; String pvalue; en = request.getParameterNames(); while (en.hasMoreElements()) { pname = (String) en.nextElement(); pvalue= request.getParameterValues(pname); for(int i=0;i<pvalue.length;i++) { out.println(pvalue[i]); } }
  • 35. Cookies  Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting the same Web site or domain later.  To send cookies to the client, a servlet would create one or more cookies with the appropriate names and values via new Cookie(name, value).  A Cookie is created by calling the Cookie constructor, which takes two strings: the cookie name and the cookie value. Neither the name nor the value should contain whitespace or any of: [ ] ( ) = , " / ? @ : ;  Ex: Cookie userCookie = new Cookie("user", "uid1234");
  • 36.  The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse.  Cookie userCookie = new Cookie("user", "uid1234");  response.addCookie(userCookie);
  • 37. The getXXX( ) method can be used to retrieve the attribute XXX of a cookie object, which returns the string value. For example getName( ) used to retrieve the name of a cookie. The setXXX( ) method is used to set the value of XXX attribute of a cookie, which accepts the value as argument which need to be set. Ex: c.setValue(“123”); It sets Value attribute of cookie c as 123.
  • 38. Servlet-Sessions  There are a number of problems that arise from the fact that HTTP is a "stateless" protocol.  In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions.  This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce.  When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?
  • 39.  Servlets provide an outstanding technical solution: the HttpSession API.  “A session is created each time a client requests service from a Java servlet. The servlet processes the request and responds accordingly, after which the session is terminated.”
  • 40. JSP - Java Server Pages Introduction  JSP is one of the most powerful, easy-to-use, and fundamental tools in a Web-site developer's toolbox.  JSP combines HTML and XML with Java servlet (server application extension) and JavaBeans technologies to create a highly productive environment for developing and deploying reliable, interactive, high-performance platform- independent Web sites.  JSP facilitates the creation of dynamic content on the server.
  • 41.  It is part of the Java platform's integrated solution for server-side programming, which provides a portable alternative to other server- side technologies, such as CGI.  JSP integrates numerous Java application technologies, such as Java servlet, JavaBeans, JDBC, and Enterprise JavaBeans.  It also separates information presentation from application logic and fosters a reusable component model of programming.
  • 42. Advantages of JSP over Servlets  Servlet use println statements for printing an HTML document which is usually very difficult to use. JSP has no such tedious task to maintain.  JSP needs no compilation, CLASSPATH setting and packaging.  In a JSP page visual content and logic are seperated, which is not possible in a servlet.  There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages.  Usually with JSP, Java Beans and custom tags web application is simplified.
  • 43. Fundamental JSP Tags  JSP tags are an important syntax element of Java Server Pages which start with "<%" and end with "%>" just like HTML tags. JSP tags normally have a "start tag", a "tag body" and an "end tag". JSP tags can either be predefined tags or loaded from an external tag library.  Fundamental tags used in Java Server Pages are classified into the following categories:-  Declaration tag  Expression tag  Directive tag  Scriptlet tag  Comments
  • 44. Declaration tag  The declaration tag is used within a Java Server page to declare a variable or method that can be referenced by other declarations, scriptlets, or expressions in a java server page.  A declaration tag does not generate any output on its own and is usually used in association with Expression or Scriplet Tags.  Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration. Syntax :- <%! Declaration %> Example: <%! int var = 1; %> <%! int x, y ; %>
  • 45. Expression tag  An expression tag is used within a Java Server page to evaluate a java expression at request time.  The expression enclosed between "<%=" and "%>" tag elements is first converted into a string and sent inline to the output stream of the response. Syntax :- <%= expression %> Example: <%= new java.util.Date() %>
  • 46. Directive tag  Directive tag is used within a Java Server page to specify directives to the application server .  The directives are special messages which may use name-value pair attributes in the form attr="value". Syntax :- <%@directive attribute="value" %>
  • 47. Where directive may be: 1. page: page is used to provide the information about it. Example: <%@page language="java" %> 2. include: include is used to include a file in the JSP page. Example: <%@ include file="/header.jsp" %> 3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags). Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
  • 48. Scriptlet tag  A Scriptlet tag is used within a Java Server page to execute a java source code scriplet which is enclosed between "<%" and "%>" tag elements.  The output of the java source code scriplet specified within the Scriptlet tag is executed at the server end and is inserted in sequence with rest of the web document for the client to access through web browser. Syntax :- <% java code %>
  • 49. Comments  Comments tag is used within a Java Server page for documentation of Java server page code.  Comments surrounded with "<%/*" and "*/%" tag elements are not processed by JSP engine and therefore do not appear on the client side web document but can be viewed through the web browser’s "view source" option.  Syntax :- <%-- comment -- %>
  • 50. Request String  The browser generates a user request string whenever the submit is selected.  The User request string consists of the URL and the query string. http://localhost:8080/examples/test/reg.jsp?fname=“bob”&lna me=“smith”  The getParameter(name) is the method used to parse a value of a specified field. <% string firstname = request.getParameter(fname) string lastname = request.getParameter(lname) %>
  • 51. User Sessions  A JSP program must be able to track a session as a client moves between HTML pages and JSP programs. There are three commonly used methods to track a session. 1. Using Hidden Field 2. Using Cookies 3. Using JavaBean
  • 52. Cookies  Cookies is a small piece of information created by a JSP program that is stored on the Client’s hard disk by the browser.  You can create and read a cookie by using methods of the cookie class and the response object. Example: how to create a cookie <HTML> <HEAD> <TITLE>JSP PROGRAMMING </TITLE> </HEAD> <BODY> <%! String MyCookieName = “userId”; String MyCookieValue = “Jk12345”; Response.addCookie(new Cookie(MyCookieName, MyCookieValue)); %> </BODY> </HTML>
  • 53. HOW TO READ A COOKIE <HTML> <HEAD> <TITLE> JSP Programming</TITLE> </HEAD> <BODY> <%! String MyCookieName=“userID”; String MyCookieValue; String Cname,Cvalue; int found=0; Cookie[] cookies=request.getCookies(); for(int i=0;i<cookies.length;i++){ CName=cookies[i].getName(); CValue= cookie[i].getValue(); if(MyCookieName.equals(cookieNames[i])){ found=1; MyCookieValue=CookieValue; } } if(found==1){ %> <p> Cookie name =<% MYCookieName%></p> <p> Cookie Value=<% MyCookieValue %></p> <&}> </BODY> </HTML>
  • 54. Session Objects  A JSP database system is able to share information among JSP programs within a session by using a session object.  Each time a session is created, a unique ID is assigned to the session and stored as a cookie