Servlet API life cycle methods
init(): called when servlet is instantiated; must return before any other methods will be called
service(): method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later)
destroy(): called when server shuts down
J2EE : Java servlet and its types, environmentjoearunraja2
The server-side extensions are nothing but the technologies that are used to create dynamic Web pages. Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web server. To meet this requirement, independent Web server providers offer some proprietary solutions in the form of APIs (Application Programming Interface).
These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is also one of the component APIs of Java Platform Enterprise Edition (nowadays known as – ‘Jakarta EE’) which sets standards for creating dynamic Web applications in Java.
Today we all are aware of the need to create dynamic web pages i.e. the ones that can change the site contents according to the time or can generate the content according to the request received by the client. If you like coding in Java, then you will be happy to know that using Java there also exists a way to generate dynamic web pages and that way is Java Servlet. But before we move forward with our topic let’s first understand the need for server-side extensions.
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, and then send a response back to the web server. Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new request received.
Servlets, as written in Java, are platform independent.
Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate process. There is only a single instance that handles all requests concurrently. This also saves the memory and allows a Servlet to easily manage the client state.
It is a server-side component, so Servlet inherits the security provided by the Web server.
The API designed for Java Servlet automatically acquires the advantages of the Java platforms such as platform-independent and portability. In addition, it obviously can use the wide range of APIs created on Java platforms such as JDBC to access the database.
Many Web servers that are suitable for personal use or low-traffic websites are offered for free or at extremely cheap costs eg. Java servlet. However, the majority of commercial-grade Web servers are rather expensive, with the notable exception of Apache, which is free.
The Servlet Container
Servlet container, also known as Servlet engine, is an integrated set of objects that provide a run time environment for Java Servlet components. In simple words, it is a system that manages Java Servlet components on top of the Web server to handle the Web client requests.
Services provided by the Servlet container:
Network Services: Loads a Servlet class. The loading may be from a local file system, a remote file system or other network services. The Servlet container provides the network services over which the request and response are sent.
CNIT 129S: Ch 3: Web Application TechnologiesSam Bowne
Slides for a college course based on "The Web Application Hacker's Handbook", 2nd Ed.
Teacher: Sam Bowne
Website: https://samsclass.info/129S/129S_F16.shtml
CNIT 129S - Ch 3: Web Application TechnologiesSam Bowne
For a college course at CCSF taught by Sam Bowne.
https://samsclass.info/129S/129S_S18.shtml
Based on "The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws 2nd Edition", by Dafydd Stuttard , Marcus Pinto; ISBN-10: 1118026470
Servlet API life cycle methods
init(): called when servlet is instantiated; must return before any other methods will be called
service(): method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later)
destroy(): called when server shuts down
J2EE : Java servlet and its types, environmentjoearunraja2
The server-side extensions are nothing but the technologies that are used to create dynamic Web pages. Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web server. To meet this requirement, independent Web server providers offer some proprietary solutions in the form of APIs (Application Programming Interface).
These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is also one of the component APIs of Java Platform Enterprise Edition (nowadays known as – ‘Jakarta EE’) which sets standards for creating dynamic Web applications in Java.
Today we all are aware of the need to create dynamic web pages i.e. the ones that can change the site contents according to the time or can generate the content according to the request received by the client. If you like coding in Java, then you will be happy to know that using Java there also exists a way to generate dynamic web pages and that way is Java Servlet. But before we move forward with our topic let’s first understand the need for server-side extensions.
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, and then send a response back to the web server. Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new request received.
Servlets, as written in Java, are platform independent.
Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate process. There is only a single instance that handles all requests concurrently. This also saves the memory and allows a Servlet to easily manage the client state.
It is a server-side component, so Servlet inherits the security provided by the Web server.
The API designed for Java Servlet automatically acquires the advantages of the Java platforms such as platform-independent and portability. In addition, it obviously can use the wide range of APIs created on Java platforms such as JDBC to access the database.
Many Web servers that are suitable for personal use or low-traffic websites are offered for free or at extremely cheap costs eg. Java servlet. However, the majority of commercial-grade Web servers are rather expensive, with the notable exception of Apache, which is free.
The Servlet Container
Servlet container, also known as Servlet engine, is an integrated set of objects that provide a run time environment for Java Servlet components. In simple words, it is a system that manages Java Servlet components on top of the Web server to handle the Web client requests.
Services provided by the Servlet container:
Network Services: Loads a Servlet class. The loading may be from a local file system, a remote file system or other network services. The Servlet container provides the network services over which the request and response are sent.
CNIT 129S: Ch 3: Web Application TechnologiesSam Bowne
Slides for a college course based on "The Web Application Hacker's Handbook", 2nd Ed.
Teacher: Sam Bowne
Website: https://samsclass.info/129S/129S_F16.shtml
CNIT 129S - Ch 3: Web Application TechnologiesSam Bowne
For a college course at CCSF taught by Sam Bowne.
https://samsclass.info/129S/129S_S18.shtml
Based on "The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws 2nd Edition", by Dafydd Stuttard , Marcus Pinto; ISBN-10: 1118026470
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
2. What is a Servlet?
• Servlet is a technology i.e. used to create web application.
• Servlet is an API that provides many interfaces and
classes including documentations.
• Servlet is an interface that must be implemented for
creating any servlet.
• Servlet is a class that extends the capabilities of the
servers and responds to the incoming requests. It can
respond to any type of requests.
• Servlet is a web component that is deployed on the server
to create dynamic web page.
3.
4. CGI(Commmon 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.
6. Disadvantages of CGI
There are many problems in CGI technology:
• If number of clients increases, it takes more time
for sending response.
• For each request, it starts a process and Web
server is limited to start processes.
• It uses platform dependent language e.g. C,
C++, perl.
7. Advantage of Servlet
• The web container creates threads for handling
the multiple requests to the servlet.
• Threads have a lot of benefits over the
Processes such as they share a common
memory area, lightweight, cost of
communication between the threads are low.
8.
9. The basic benefits of servlet are as follows:
• Better performance: because it creates a thread for
each request not process.
• Portability: because it uses java language.
• Robust: Servlets are managed by JVM so we don't need
to worry about memory leak, garbage collection etc.
• Secure: because it uses java language
11. Java Servlet
• Javax.servlet package can be extended for use with
any application layer protocol
– http is the most popularly used protocol
– Javax.servlet.http package is extension of the javax.servlet
package for http protocol
• The Servlet spec allows you to implement separate Java methods
implementing each HTTP method in your subclass of HttpServlet.
– Override the doGet() and/or doPost() method to provide normal
servlet functionality.
– Override doPut() or doDelete() if you want to implement these
methods.
– There's no need to override doOptions() or doTrace().
– The superclass handles the HEAD method all on its own.
12. Anatomy of a Servlet
• init()
• destroy()
• service()
• doGet()
• doPost()
13. • Servlet API life cycle methods
– init(): called when servlet is instantiated; must
return before any other methods will be called
– service(): method called directly by server when
an HTTP request is received; default service()
method calls doGet() (or related methods covered
later)
– destroy(): called when server shuts down
14. Servlet
Container
Thread Thread
Servlet
Create Thread Pool
Instantiate servlet
Call init ( ) method
Allocate request to thread
Allocate request to thread
Block all further requests Wait
for active threads to end
Terminate thread pool
call destroy ( ) method
terminate servlet
Container shutdown
Call service ( ) method
Call service ( ) method
Perform
Initialization
Perform Service
Perform
cleanup
Servlet destroyed
& garbage collected
Perform Service
Shutdown
Initiated
HTTP
Request 1
HTTP
Request 2
HTTP
Response 1
HTTP
Response 2
15. Anatomy of a Servlet
• HTTPServletRequest object
• Information about an HTTP request
• Headers
• Query String
• Session
• Cookies
• HTTPServletResponse object
• Used for formatting an HTTP response
• Headers
• Status codes
• Cookies
16. Server-side Programming
• The combination of
– HTML
– JavaScript
– DOM
is sometimes referred to as Dynamic HTML (DHTML)
• Web pages that include scripting are often called
dynamic pages (vs. static)
17. Server-side Programming
• Similarly, web server response can be static or
dynamic
– Static: HTML document is retrieved from the file
system and returned to the client
– Dynamic: HTML document is generated by a program
in response to an HTTP request
• Java servlets are one technology for producing
dynamic server responses
– Servlet is a class instantiated by the server to
produce a dynamic response
19. Servlet Overview
Reading Data from a Client
1. When server starts it instantiates servlets
2. Server receives HTTP request, determines
need for dynamic response
3. Server selects the appropriate servlet to
generate the response, creates
request/response objects, and passes them to
a method on the servlet instance
4. Servlet adds information to response object via
method calls
5. Server generates HTTP response based on
information stored in response object
20. • The browser uses two methods to pass this information
to web server. These methods are GET Method and
POST Method.
• GET Method (doGet())
• The GET method sends the encoded user information
appended to the page request. The page and the
encoded information are separated by the ?(question
mark) symbol as follows −
http://www.test.com/hello?key1 = value1&key2 = value2
21. • POST Method
• A generally more reliable method of passing information
to a backend program is the POST method.
• This packages the information in exactly the same way
as GET method, but instead of sending it as a text string
after a ? (question mark) in the URL it sends it as a
separate message.
• This message comes to the backend program in the
form of the standard input which you can parse and use
for your processing.
• Servlet handles this type of requests
using doPost() method.
22. • Servlets handles form data parsing automatically using
the following methods depending on the situation −
• getParameter() − You call request.getParameter()
method to get the value of a form parameter.
• getParameterValues() − Call this method if the
parameter appears more than once and returns multiple
values, for example checkbox.
• getParameterNames() − Call this method if you want a
complete list of all parameters in the current request.
38. Servlets vs. Java Applications
• Servlets do not have a main()
– The main() is in the server
– Entry point to servlet code is via call to a
method (doGet() in the example)
• Servlet interaction with end user is indirect
via request/response object APIs
– Actual HTTP request/response processing is
handled by the server
• Primary servlet output is typically HTML
39. Servlet Life Cycle
• Servlet API life cycle methods
– init(): called when servlet is instantiated;
must return before any other methods will be
called
– service(): method called directly by server
when an HTTP request is received; default
service() method calls doGet() (or
related methods covered later)
– destroy(): called when server shuts down
40.
41.
42.
43. Reading HTTP Request Headers
https://www.tutorialspoint.com/servlets/servlets-client-request.htm
• When a browser requests for a web page, it sends lot of
information to the web server which cannot be read
directly because this information travel as a part of
header of HTTP request. You can check HTTP Protocol
for more information on this.
• Following is the important header information which
comes from browser side and you would use very
frequently in web programming −
44. Accept
• This header specifies the MIME types that the browser or other
clients can handle. Values of image/png or image/jpeg are the two
most common possibilities.
Accept-Charset
• This header specifies the character sets the browser can use to
display the information. For example ISO-8859-1.
Accept-Encoding
• This header specifies the types of encodings that the browser knows
how to handle. Values of gzip or compress are the two most
common possibilities.
45. Accept-Language
• This header specifies the client's preferred languages in
case the servlet can produce results in more than one
language. For example en, en-us, ru, etc
Authorization
• This header is used by clients to identify themselves
when accessing password-protected Web pages.
46. Connection
• This header indicates whether the client can handle persistent HTTP
connections. Persistent connections permit the client or other
browser to retrieve multiple files with a single request. A value of
Keep-Alive means that persistent connections should be used.
Content-Length
• This header is applicable only to POST requests and gives the size
of the POST data in bytes.
•
Cookie
• This header returns cookies to servers that previously sent them to
the browser.
47. Host
• This header specifies the host and port as given in the
original URL.
If-Modified-Since
• This header indicates that the client wants the page only
if it has been changed after the specified date. The
server sends a code, 304 which means Not Modified
header if no newer result is available.
48. If-Unmodified-Since
• This header is the reverse of If-Modified-Since; it specifies that the
operation should succeed only if the document is older than the specified
date.
Referer
• This header indicates the URL of the referring Web page. For example, if
you are at Web page 1 and click on a link to Web page 2, the URL of Web
page 1 is included in the Referrer header when the browser requests Web
page 2.
User-Agent
• This header identifies the browser or other client making the request and
can be used to return different content to different types of browsers.
50. Writing HTTP Response Header
• when a Web server responds to an HTTP
request, the response typically consists of a
status line, some response headers, a blank
line, and the document. A typical response looks
like this −
51. 1
Allow
This header specifies the request methods (GET, POST, etc.) that the
server supports.
2
Cache-Control
This header specifies the circumstances in which the response document
can safely be cached. It can have values public, privateor no-cache etc.
Public means document is cacheable, Private means document is for a
single user and can only be stored in private (non-shared) caches and no
cache means document should never be cached.
3
Connection
This header instructs the browser whether to use persistent in HTTP
connections or not. A value of close instructs the browser not to use
persistent HTTP connections and keepalive means using persistent
connections.
52. 4
Content-Disposition
This header lets you request that the browser ask the user to save the
response to disk in a file of the given name.
5
Content-Encoding
This header specifies the way in which the page was encoded during
transmission.
6
Content-Language
This header signifies the language in which the document is written.
For example en, en-us, ru, etc
53. 7
Content-Length
This header indicates the number of bytes in the response. This information is
needed only if the browser is using a persistent (keep-alive) HTTP connection.
8
Content-Type
This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.
9
Expires
This header specifies the time at which the content should be considered out-of-
date and thus no longer be cached.
10
Last-Modified
This header indicates when the document was last changed. The client can then
cache the document and supply a date by an If-Modified-Since request header
in later requests.
54. 11
Location
This header should be included with all responses that have a status
code in the 300s. This notifies the browser of the document address. The
browser automatically reconnects to this location and retrieves the new
document.
12
Refresh
This header specifies how soon the browser should ask for an updated
page. You can specify time in number of seconds after which a page
would be refreshed.
13
Retry-After
This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.
14
Set-Cookie
This header specifies a cookie associated with the page.
55. Methods to Set HTTP Response Header
• There are following methods which can be used to set
HTTP response header in your servlet program. These
methods are available with HttpServletResponse object.
56. Sr.No.
Method & Description
1
String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.
2
String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
3
boolean containsHeader(String name)
Returns a Boolean indicating whether the named response header has already been set.
4
boolean isCommitted()
Returns a Boolean indicating if the response has been committed.
5
void addCookie(Cookie cookie)
Adds the specified cookie to the response.
6
void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.
7
void addHeader(String name, String value)
Adds a response header with the given name and value.
8
void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
9
void flushBuffer()
Forces any content in the buffer to be written to the client.
10
void reset()
Clears any data that exists in the buffer as well as the status code and headers.
11
void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code.
12
void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.
57. Sessions
• Many interactive Web sites spread user
data entry out over several pages:
– Ex: add items to cart, enter shipping
information, enter billing information
• Problem: how does the server know which
users generated which HTTP requests?
– Cannot rely on standard HTTP headers to
identify a user
63. Sessions
Returns HttpSession object associated
with this HTTP request.
• Creates new HttpSession object if no
session ID in request or no object with
this ID exists
• Otherwise, returns previously created
object
85. Sessions
• Session attribute methods:
– setAttribute(String name, Object
value): creates a session attribute with the
given name and value
– Object getAttribute(String name):
returns the value of the session attribute
named name, or returns null if this session
does not have an attribute with this name
87. Sessions
• By default, each session expires if a
server-determined length of time elapses
between a session’s HTTP requests
– Server destroys the corresponding session
object
• Servlet code can:
– Terminate a session by calling
invalidate() method on session object
– Set the expiration time-out duration (secs) by
calling setMaxInactiveInterval(int)
88. Cookies
• A cookie is a name/value pair in the Set-
Cookie header field of an HTTP response
• Most (not all) clients will:
– Store each cookie received in its file system
– Send each cookie back to the server that sent
it as part of the Cookie header field of
subsequent HTTP requests
91. Cookies
• Servlets can set cookies explicitly
– Cookie class used to represent cookies
– request.getCookies() returns an array of
Cookie instances representing cookie data in
HTTP request
– response.addCookie(Cookie) adds a
cookie to the HTTP response
100. Web site
providing
requested
content
Cookies
Privacy issues
Client
Second
Web site
providing
requested
content
HTTP request to 2nd
intended site
HTTP response:
HTML document
including ad <img>
Web site
providing
banner
ads
HTTP request for
ad image plus Cookie (identifies user)
Image Based on
Referer, I know two
Web sites that
this user has
visited
101. Cookies
Privacy issues
• Due to privacy concerns, many users
block cookies
– Blocking may be fine-tuned. Ex: Mozilla
allows
• Blocking of third-party cookies
• Blocking based on on-line privacy policy
• Alternative to cookies for maintaining
session: URL rewriting
105. More Servlet Methods
• Response buffer
– All data sent to the PrintWriter object is
stored in a buffer
– When the buffer is full, it is automatically
flushed:
• Contents are sent to the client (preceded by
header fields, if this is the first flush)
• Buffer becomes empty
– Note that all header fields must be defined
before the first buffer flush
107. More Servlet Methods
• In addition to doGet() and doPost(),
servlets have methods corresponding to
other HTTP request methods
– doHead(): automatically defined if doGet()
is overridden
– doOptions(), doTrace(): useful default
methods provided
– doDelete(), doPut(): override to support
these methods
108. Common Gateway Interface
• CGI was the earliest standard technology
used for dynamic server-side content
• CGI basics:
– HTTP request information is stored in
environment variables (e.g.,
QUERY_STRING, REQUEST_METHOD,
HTTP_USER_AGENT)
– Program is executed, output is returned in
HTTP response
109. Common Gateway Interface
• Advantage:
– Program can be written in any programming
language (Perl frequently used)
• Disadvantages:
– No standard for concepts such as session
– May be slower (programs normally run in
separate processes, not server process)
111. Java Server Pages
• Servlets are pure Java programs. They introduce
dynamism into web pages by using programmatic
content.
• JSP technology is an extension/wrapper over the
Java servlet technology.
• JSP are text based documents.
• We will focus only on JSP since it subsumes the
servlet technology.
• Two major components of JSP:
– Static content: provided by HTML or XML
– Dynamic content: generated by JSP tags and
scriplets written in Java language to encapsulate
the application logic.
112. JSP compilation into Servlets
Web
Browser
Web
Server
J2EE Web
Container
Java
Servlets
JSP
translation
Initial
request
Subseq
request
113. More on JSP syntax and
contents
• HTML code for user interface lay out
• JSP tags: declarations, actions, directives,
expressions, scriplets
• JSP implicit objects: a request object, response
object, session object, config object
• Javabeans: for logic that can be taken care of at
the JSP level.
• We will examine only JSP tags here.
114. JSP Tags
• Declaration: variable declaration
<%! int age = 56 %>
• Directive: ex: import classes
<%@ page import = “java.util.*” %>
• Scriplet: Java code
<% if password(“xyz”) {
%>
<H1> Welcome <H1>
• Expression: regular expression using variables
and constants
– <%= param[3]+4 %>
• Action: <jsp:usebean name =“cart”
class=“com.sun.java.Scart”
115. Methods
S.No. Method & Description
1
out.print(dataType dt)
Print a data type value
2
out.println(dataType dt)
Print a data type value then terminate the line with new
line character.
3
out.flush()
Flush the stream.
116. The session Object
• The session object is an instance
of javax.servlet.http.HttpSession and behaves
exactly the same way that session objects
behave under Java Servlets.
• The session object is used to track client session
between client requests.