SlideShare a Scribd company logo
1 of 82
1 December 2021 1
Servlet
Name :: Mallikarjuna G D
Reach me @ Training ::
Email :: gdmallikarjuna@gmail.com
1 December 2021 2
Agenda
• Introduction to Web Application Technologies
• CGI Programs on the Web Server
• What is servlet?
• Jobs of servlet
• Advantages over CGI
• Why pages are build dynamically?
• Servlet container
• Installation & configuration
- Type 1: Integration of Tomcat server and eclipse
- Type 2: Java Servlet
• Servlet Sample Example
• Servlet Overview And Architecture
- Servlet Life cycle/Single Thread Model
- Interface Servlet
- HttpServlet Class
- HttpServletRequest, HttpServletResponse
1 December 2021 3
Agenda
• Handling client request :Http request
• Generating Server Response : Http status code
• Handling Session
- Cookies
- Session Tracking
- URL-re writing
- Hidden Form fields
1 December 2021 4
Introduction to Web Application Technologies
• World Wide Web:
HTTP (Hypertext Transfer Protocol) is similar to FTP because it is a protocol to
transfer files from the server to client. HTTP was created in conjunction with
related HTML standard.
HTML (Hypertext Markup Language) is a document display language that lets
users link from one document to another.
HTML permits images and other media objects to be embedded in an HTML
document. The media objects are stored in files on a server.
HTTP also retrieves these files. Therefore HTTP can be used to transmit any
file that confirms to multipurpose Internet Mail Extensions (MIME) specification.
1 December 2021 5
• Web Browsers and and Web Servers:
To view an HTML document with rich media content, a graphical user interface
was built on the top of the client-side HTTP.
This GUI is called as web browser. The server-side HTTP component is called
a web server.
• Web Applications:
Early in the development of HTML, the designers created a mechanism to
permit a user to invoke a program on the web server. This mechanism was
called as Common Gateway Interface (CGI). When a website includes CGI
processing, this is called a web application.
(Contd..)
1 December 2021 6
CGI Programs on the Web Server
• The browser needs to send data to the CGI program on the server. The CGI
specification defines how the data is packaged and sent in the HTTP request to
the server. This data is usually typed into the web browser in an HTML form.
• The URL determines which CGI program to execute.
This might be a script or an executable file.
• The CGI program parses the CGI data in the request, processes the data, and
generates a response.
• The CGI response is sent back to the web server, which wraps the response
in an HTTP response.
• The HTTP response is sent back to the web browser.
1 December 2021 7
Web Server Architecture with CGI Programs
(Contd..)
1 December 2021 8
Advantages and Disadvantages of CGI Programs
• Programs can be written in a variety of languages, although they are primarily
written in Perl.
• A CGI program with bugs does not crash the web server.
• Programs are easy for a web designer to reference. When the script is written, the
designer can reference it in one line in a web page.
• Because CGI programs execute in their own OS Shell, these programs do not have
concurrency conflicts with other HTTP requests executing the same CGI program.
• All service provides support CGI programs.
1 December 2021 9
• The response time of CGI programs is high because CGI programs execute in their
own OS shell. The creation of an OS shell is a heavyweight activity for the OS.
• CGI is not scalable.
• The languages for CGI are not always secure or object-oriented.
• The CGI script has to generate an HTML response, so the CGI code is mingled with
HTML. This is not good separation of presentation and business logic.
• Scripting languages are often platform-dependent.
Disadvantages
• Servlet is a program that runs on server acts as a middle layer between a request
coming from web-browser or other HTTP Clients and database or applications on
the Server.
• Improved substitute for CGI Scripts.
• Are executed in context of web server.
• Part of JEE (Servlet API 2.4)
• Helps client server communication.
1 December 2021 10
What is Servlet?
1 December 2021 11
Jobs of servlet?
• Read explicit data sent by client (form data)
• Read implicit data sent by client (request header)
• Generate the result
• Send the explicit data back to client (e.g. HTML format)
• Send the implicit data to client (status code and response
header)
Servlet:
HTTP
Web
Server
File system
Servlet
Server
Static
Tomcat = Web Server + Servlet Server
Other..
Dynamic
1 December 2021 12
Advantages of Servlet over CGI
• Efficient/Scalable-handled by separate thread within web-server
process.
• Convenient - lot of high level utilities.
• Powerful – Sharing data, pooling, persistence.
• Portable – Run virtually on all operating systems and servers.
• Security – No shell escapes, no bufferflow.
• Inexpensive.
1 December 2021 13
Disadvantages:
• Servlets often contain both business logic and presentation logic. Presentation
logic is anything that controls how the application presents information to the
user. Generating the HTML response within the servlet code is presentation
logic.
Business logic is anything that manipulates data to accomplish something such
as storing data.
• Servlets must handle concurrency issues.
• Mixing presentation and business logic means that whenever a web page
changes the servlets must be rewritten, recompiled and redeployed.
• This disadvantage led to the development of template pages, including Java
Server Pages technology.
1 December 2021 14
Why build pages dynamically?
• The web page is based on data submitted by the user.
e.g.:- result in search engines , online shopping so on.
• The web pages are derived from the data changes frequently.
e.g.:-weather report, stock exchange, news headline.
• The web pages are derived from data from databases or other server side
resources.
e.g.:- e-commerce page shows availability of product with price
information.
1 December 2021 15
Servlet Container/Servlet Engine
• The servlet container is compiled, executable program. The container acts as
intermediator between webserver and servlet in the container.
• The container loads, initializes and executes servlet. When request arrives
container maps to servlet.
• The container is designed to perform well by serving large number of requests.
A container can hold any number of servlets, filters and listener.
• Both the container and object contained in it are multithreaded. The container
handles multiple requests concurrently, and more than one thread may enter an
object at a time. Therefore, each object within a container must be thread safe.
1 December 2021 16
(Contd..)
There are three kinds of servlet engine
- standalone
- add on
- embedded
• Standalone Servlet Engines
- Built in support for servlets.
- Hard to keep latest version of servlet.
• Add on servlet Servlet-engines
- Plug-in to an existing servlets.
• Embeddable servlet engines
- lightweight servlet-deployment platform that can be
embedded in another application.
1 December 2021 17
List of servlet containers
Non commercial:
• Apache Tomcat (formerly Jakarta Tomcat) is an open source web
container available under the Apache Software License.
• Apache Geronimo -is a full Java EE implementation by Apache.
• Jetty
• Jaminid - contains a higher abstraction than servlets.
• Enhydra
• Winstone - supports specification v2.4, has a focus on minimal configuration
and the ability to strip the container down to only what you need.
• tjws - spec 2.4, small footprint, modular design
1 December 2021 18
Commercial:
• BEA WebLogic Server or Weblogic Express, from BEA Systems
• Borland Enterprise Server
• GlassFish (open source)
• Java System Application Server, from Sun Microsystems
• Java System Web Server, from Sun Microsystems
• JBoss (open source)
• JRun, from Adobe Systems (formerly developed by Allaire Corporation)
(Contd..)
1 December 2021 19
• LiteWebServer (open source)
• Oracle Application Server, from Oracle Corporation
• Orion Application Server, from IronFlare
• Caucho's Resin Server
• ServletExec, from New Atlanta Communications
• WebObjects, from Apple Inc.
• WebSphere, from IBM
(Contd..)
1 December 2021 20
• The Servlet API, contained in the Java package hierarchy javax.servlet,
defines the expected interactions of a Web container and a servlet.
• A Web container is essentially the component of a Web server that interacts
with the servlets. The Web container is responsible for managing the lifecycle of
servlets, mapping a URL to a particular servlet and ensuring that the URL
requester has the correct access rights.
• A Servlet is an object that receives a request and generates a response based
on that request.
The basic servlet package defines Java objects to represent servlet requests
and responses, as well as objects to reflect the servlet's configuration
parameters and execution environment
Java Servlet API
1 December 2021 21
Servlet API History
The complete servlet specification was created by Sun Microsystems, with
version 1.0 finalized in June 1997.
Starting with version 2.3, the servlet specification was developed under the
Java Community Process.
1 December 2021 22
Installation and Configuration
• Step 1: jdk 11.0
• Download the JDK 11.0 offline installation file (Windows Offline Installation,
Multi-language) from Oracle'
https://www.oracle.com/java/technologies/downloads/#java11-windows. The
online installation will download the installation files through the internet and
you will have to re-download them each time you format your HD.
• Double click on the .exe file (throughout I assume XP or VISTA or Windows
10, or some other crappy Micro$oft OS).
The following screen should pop up:
1 December 2021 23
(Contd..)
1 December 2021 24
(Contd..)
We still have to go that extra bit and set up some environment variables -
primarily create JAVA_HOME and edit the PATH system variable. In the
computers Control Panel double click on the System icon and select the
Advanced tab. The result should be something not foreign to the screenshot
below:
1 December 2021 25
(Contd..)
Set path to the java_home/bin:, finally restart.. And open command prompt to
check java installed by giving java –version in prompt.
1 December 2021 26
• Step 2: Install Eclipse
download eclipse IDE from http://www.eclipse.org/downloads/
and extract to the required folder.
• Step 3: Install Jakarta Tomcat
download tomcat 9.x from this site in zip format
http://tomcat.apache.org/, then extract to required folder.
(Contd..)
1 December 2021 27
(Contd..)
• Step 5: Configure Eclipse
- start eclipse, and do configuration as per below screen shots.
1 December 2021 28
(Contd..)
1 December 2021 29
Simple Servlet configuration & development
1. Select File > New > Dynamic Web Project..
1 December 2021 30
(Contd..)
Input the following code in to the file SimpleServlet.java and click Save button in
toolbar.
import java.io.PrintWriter;
public class SimpleServlet extends javax.servlet.http.HttpServlet {
public void doGet(javax.servlet.http.HttpServletRequest
request, javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
performTask(request, response);
}
public void doPost(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws javax.servlet.ServletException, java.io.IOException {
performTask(request, response);
}
1 December 2021 31
(Contd..)
public void performTask(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
{
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println( "This is a Simple Servlet Demo");
} catch(Throwable theException) {
//theException.printStackTrace();
}
}
}
1 December 2021 32
(Contd..)
Web.xml content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<servlet>
<servlet-name>SimpleServlet</servlet-name>
<servlet-class>SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/SimpleServlet</url-pattern>
</servlet-mapping>
</web-app>
1 December 2021 33
(Contd..)
Press the Start Tomcat button in tool bar, after tomcat starts, open
a browser and input the URL:
http://localhost:8080/ServletDemo/SimpleServlet
The result will show as below:
1 December 2021 34
(Contd..)
Finally, run the server to see output.
1 December 2021 35
Directory Structure
1 December 2021 36
Servlet Life cycle and Architecture
Servlets are first standard to extension to java including two packages:
-javax.servlet
-javax.servlet.http
In general, servlet
1. Generic Servlet
- must extend javax.servlet.Servlet
- protocol independent
2. Http Servlet
- must extend javax.servlet.http.HttpServlet
- Handling Http request/reply
1 December 2021 37
(Contd..)
Http Servlet:
Generic Servlet:
1 December 2021 38
Servlet Life Cycle
• The life cycle of a servlet is controlled by the container in which the servlet
has been deployed.
When a request is mapped to a servlet, the container performs the following
steps:
- If an instance of the servlet does not exist, the Web container
loads the servlet class. Creates an instance of the servlet class.
Initializes the servlet instance by calling the init method.
- Invokes the service method, passing a request and response
object.
• If the container needs to remove the servlet, it finalizes the servlet by calling
the servlet's destroy method.
1 December 2021 39
Servlet Life Cycle
1 December 2021 40
(Contd..)
Java class that implements the Servlet interface
• Servlet Interface
– Defines the Servlet’s life cycle methods.
– init(ServletConfig config)
– service(ServletRequest req, ServletResponse res)
- doGet handles GET request.
- doPost handles POST request.
– destroy()
Called by the servlet container before servlet is taken out of service.
1 December 2021 41
Allowing concurrency: Single thread Model
• Container may send multiple request to single instance , using java threads. So
service methods (doGet, doPost..) are all thread safe. It means two or more threads
operating without interfere each other.
• If service methods not thread safe. We have to use single thread model.
• The single thread model ensures that only one service method runs at time
1 December 2021 42
Servlet Interface
Servlet interface {
void init(ServletConfig sc) throws ServletException;
void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException;
void destroy();
}
1 December 2021 43
Methods of Servlet
Method Description
void init(
ServletConfig
config )
The servlet container calls this method once during a servlet’s execution cycle to
initialize the servlet. The ServletConfig argument is supplied by the servlet
container that executes the servlet.
ServletConfig
getServletConfig(
)
This method returns a reference to an object that implements interface
ServletConfig. This object provides access to the servlet’s configuration
information such as servlet initialization parameters and the servlet’s
ServletContext, which provides the servlet with access to its environment
(i.e., the servlet container in which the servlet executes).
String
getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet
information such as the servlet’s author and version.
void service(
ServletRequest
request,
ServletResponse
response )
The servlet container calls this method to respond to a client request to the servlet.
void destroy() This “cleanup” method is called when a servlet is terminated by its servlet
container. Resources used by the servlet, such as an open file or an open database
connection, should be deallocated here.
1 December 2021 44
Http Servlet
• Override the servlet class
• There are two types of request- Get and Post
- doGet responds to Get request
-doPost responds to Post request
• It has HttpServletRequest and HttpServletResponse Objects
1 December 2021 45
(Contd..)
Method Description
doDelete Called in response to an HTTP delete request. Such a request is normally used to
delete a file from a server. This may not be available on some servers, because of
its inherent security risks (e.g., the client could delete a file that is critical to the
execution of the server or an application).
doHead Called in response to an HTTP head request. Such a request is normally used
when the client only wants the headers of a response, such as the content type and
content length of the response.
doOptions Called in response to an HTTP options request. This returns information to the
client indicating the HTTP options supported by the server, such as the version of
HTTP (1.0 or 1.1) and the request methods the server supports.
doPut Called in response to an HTTP put request. Such a request is normally used to
store a file on the server. This may not be available on some servers, because of
its inherent security risks (e.g., the client could place an executable application on
the server, which, if executed, could damage the server—perhaps by deleting
critical files or occupying resources).
doTrace Called in response to an HTTP trace request. Such a request is normally used for
debugging. The implementation of this method automatically returns an HTML
document to the client containing the request header information (data sent by the
browser as part of the request).
1 December 2021 46
HttpServletRequest Interface
• Web server
- creates an HttpServletRequest object.
- passes it to the servlet’s service method.
• HttpServletRequest object contains the request from the client.
1 December 2021 47
(Contd..)
Method Description
String getParameter(
String name )
Obtains the value ofa parameter sent to the servlet as part ofa get or post
request. The name argument represents the parameter name.
Enumeration
getParameterNames()
Returns the names ofallthe parameters sent to the servlet as part ofa post
request.
String[]
getParameterValues(
String name )
For a parameter with multiple values, this method returns anarrayofstrings
containing the values for a specified servlet parameter.
Cookie[] getCookies() Returns anarrayof Cookie objects stored onthe client bythe server. Cookie
objects canbe used to uniquely identifyclients to the servlet.
HttpSession getSession(
booleancreate )
Returns an HttpSession object associated withthe client’s current browsing
session. This method cancreate an HttpSession object (true argument) ifone
does not alreadyexist for the client. HttpSession objects are used insimilar
ways to Cookies for uniquely identifying clients.
1 December 2021 48
HttpServletResponse Interface
Method Description
void addCookie(
Cookie cookie )
Used to add a Cookie to the header of the response to the client. The
Cookie’s maximum age and whether Cookies are enabled on the client
determine if Cookies are stored on the client.
ServletOutputStream
getOutputStream()
Obtains a byte-based output stream for sending binary data to the client.
PrintWriter
getWriter()
Obtains a character-based output stream for sending text data to the client.
void
setContentType(
String type )
Specifies the MIME type of the response to the browser. The MIME type
helps the browser determine how to display the data (or possibly what
other application to execute to process the data). For example, MIME type
"text/html" indicates that the response is an HTML document, so the
browser displays the HTML page.
• Web server
- creates an HttpServletResponse object.
- passes it to the servlet’s service method.
1 December 2021 49
Handling client request : Http request header
General:
getHeader, getHeaders, getHeaderNames.
Specialized:
getCookies, getAuthType, getRemoteUser, getContentLength,
getContentType, getDateHeader, getIntHeader
Related Info:
getMethod, getRequestURI, getProtocol
1 December 2021 50
(Contd..)
1 December 2021 51
Common HTTP Request Header 1.1
• Accept
- MIME Types of browser can handle.
- Can send different content to different clients.
• Accept-Encoding
- Indicate encoding (e.g gzip) browser can handle.
• Authorization
- User identification for password protected pages.
• Connection
- In Http 1.1, keep alive means browser can handle persistent
connection. Persistent connection is default. Persistent means same
socket is reused for same type of client request.
1 December 2021 52
(Contd..)
• Cookie
- Give cookies previously sent to client.
• Host
- It gives host given in original URL.
• If-Modified-Since
- Client wants pages, only after changed on some specified
dates.
• Referrer
- URL of referring web page.
- Useful for tracking traffic; logged by many servers.
• User Agent
- String identifying the browser making request.
1 December 2021 53
Generating server response: http status code
Purpose: The variety of status code that are essentially indicate failure.
e.g.:- HTTP/1.1 200 OK
• Changing a status code perform a lot of tasks.
- Forward client to another page.
- Indicate a missing resource.
- Instruct a browser to use cached copy.
• Set status before sending document.
public void setStatus (int statusCode)
- use constant for the code. Not an explicit int.
constants are HttpServletResponse.
- Names derived from standard message.
e.g SC_OK, SC_NOT_FOUND so on.
• public sendError(int code, String msg)
- Wraps the message inside HTML document.
1 December 2021 54
(Contd..)
• Public void sendRedirect(String url)
- Relative url is permitted in 2.2/2.3
- Also sets location header.
Common HTTP 1.1 Status codes:
• 200(OK)
- Everything is fine, document follows, default for servlets.
• 204(No content)
- Browser should keep displaying previous document.
• 301(Moved document)
- Requested document moved elsewhere.
- Browsers go to new location automatically.
1 December 2021 55
(Contd..)
• 401(unauthorized)
Browser tried to access protected page without proper authorization
header.
• 404(Not found)
No such page.
In general
100-199 -> codes in the 100s are informational, indicating that the
client should respond with some other action.
200-299 -> values in the 200’s signify that the request was
successful.
300-399 -> values in the 300’s are used for files that have moved
and usually include location header indicating the new address.
1 December 2021 56
(Contd..)
400-499 -> values in the 400’s indicate an error by the client.
500-599 ->codes in the 500’s signify an error by the server.
Common MIME Type:
1 December 2021 57
Session Handling
• A server site typically needs to maintain two types of persistent(remembered)
information:
- Information about the Session.
- Information about the User.
• Servlet capabilities:
Servlets, like Applets, can be trusted or untrusted.
- A servlet can use a unique ID to store and retrieve information
about a given session.
- User information usually requires a login ID and a password.
- Since servlets don’t quit between requests, any servlet can maintain
information in its internal data structures, as long as the server keeps
running.
1 December 2021 58
(Contd..)
- A trusted servlet can read and write files on the server,
hence can maintain information about sessions and users
even when the server is stopped and restarted.
- An untrusted servlet will lose all information when the
servlet or server stops for any reason.
This is sometimes good enough for session
information.
This is almost never good enough for user
information.
- HTTP is stateless: When it gets a page request, it has no
memory of any previous requests from the same client.
1 December 2021 59
(Contd..)
• Session tracking is keeping track of what has gone before in this particular
conversation.
- Since HTTP is stateless, it does not do this for you.
- You have to do it yourself, in your servlets.
- This makes it difficult to hold a “conversation”.
Typical example: Putting things one at a time into a shopping cart, then
checking out--each page request must somehow be associated with
previous requests.
- The server must be able to keep track of multiple conversations with
multiple users.
1 December 2021 60
• Cookies are small files that the servlet can store on the client computer, and
retrieve later.
• URL rewriting: You can append a unique ID after the URL to identify the user.
• Hidden <form> fields can be used to store a unique ID.
• Java’s Session Tracking API can be used to do most of the work for you.
Session tracking solution
1 December 2021 61
Cookies
• Cookies are small bits of textual information that a web server sends to the
browser and that the browser returns unchanged when later visiting the same
website or domain.
• Cookies are not a security threat.
• Cookies can be a privacy threat.
- Cookies can be used to customize advertisements.
- Outlook Express allows cookies to be embedded in email.
- A servlet can read your cookies.
Incompetent companies might keep your credit card info in
a cookie.
Netscape lets you refuse cookies to sites other than that to
which you connected.
1 December 2021 62
Why do we need cookies?
• Cookies are a very useful tool in maintaining state (persistence) on the Web.
Unless something special is done, web servers are only aware of users when a
transaction -- sending or receiving information -- is in process. The moment the
transaction is complete the server forgets about the user and makes no attempt
to correlate subsequent transactions with previous exchanges.
• Since the web protocol, HTTP, is a "stateless" (non-persistent) protocol, it is
impossible to differentiate between visits to a given web site, unless the server
can somehow "mark" a visitor.
• This is done by storing a piece of information in the visitor's browser, called a
"cookie". Cookies can contain database information, custom page settings, or
just about anything that would make a site customizable.
1 December 2021 63
Using cookies
• import javax.servlet.http.*;
• Constructor: Cookie(String name, String value)
• Assuming request is an HttpServletRequest and response is an
HttpServletResponse,
response.addCookie(cookie);
Cookie[ ] cookies = request.getCookies();
String name = cookies[i].getName();
String value = cookies[i].getValue();
• There are, of course, many more methods in the HttpServletRequest,
HttpServletResponse, and Cookie classes in the javax.servlet.http package.
1 December 2021 64
(Contd..)
• public void setComment(String purpose)
- public String getComment()
• public void setMaxAge(int expiry)
- public int getMaxAge()
- Max age in seconds after which cookie will expire.
- If expiry is negative, delete when browser exits.
- If expiry is zero, delete cookie immediately.
• setSecure(boolean flag)
- public boolean get Secure()
- Indicates to the browser whether the cookie should only be
sent using a secure protocol, such as HTTPS or SSL.
1 December 2021 65
(Contd..)
Here is the code snippet for initializing a cookie and adding the same to the
response object.
.....
Cookie cookie = new Cookie ("otncookiename",userName);
cookie.setMaxAge(86400);
response.addCookie(cookie);
Cookie onemorecookie = new Cookie("otncookiepassword",password);
onemorecookie.setMaxAge(86400);
response.addCookie (onemorecookie);
.....
Setting cookies:
1 December 2021 66
(Contd..)
Retrieving a cookie value:
Here is the code snippet for selecting cookie values from the request object.
......
Cookie[] cookieArray = request.getCookies();
if( cookieArray != null) {
for( int i = cookieArray.length-1; i >= 0; i-- ) {
Cookie cookie = cookieArray[i];
System.out.println ("Cookie name is " + cookie.getName());
System.out.println ("Cookie value is " + cookie.getValue());
}
}
......
1 December 2021 67
(Contd..)
Code snippet:
Login.html
<form name="login" method="post" action="./LoginCookieServlet">
<p>please enter login credentials</p>
User Name : <input type="text" name="txtUserName"> <br>
password : <input type="password" name="txtPassword"> <input
type="submit" value='submit'>
</form>
LoginCookieServlet
String name= request.getParameter("txtUserName");
String pwd = request.getParameter("txtPassword");
Cookie userNameCookie = new Cookie("USERNAME", name);
response.addCookie(userNameCookie);
Cookie passwordCookie = new Cookie("PASSWORD",pwd);
response.addCookie(passwordCookie);
request.getRequestDispatcher("/LoginNextCookie").forward(request, response);
1 December 2021 68
(Contd..)
Code snippet:
LoginNextCookie
Cookie[] cookies = request.getCookies();
pw.println("cookies[0].getValue()"+cookies[0].getValue());
pw.println("cookies[1].getValue()"+cookies[1].getValue());
for(Cookie cookie: cookies) {
pw.println(cookie.getValue());
}
1 December 2021 69
Limitation
• The browser should be enabled to accept cookies.
• Cookie values must never have spaces, commas or semicolons.
• Cookies can store upto 4KB of value.
1 December 2021 70
URL-Rewritting
• URL rewriting is another way to support anonymous session tracking.
• With URL rewriting, every local URL the user might click on is dynamically
modified, or rewritten, to include extra information.
• The extra information can be in the form of extra path information, added
parameters, or some custom, server-specific URL change.
• Due to the limited space available in rewriting a URL, the extra information is
usually limited to a unique session ID.
1 December 2021 71
URL-Rewritting
• For example, the following URLs have been rewritten to pass the session ID
123:
http://server: port/servlet/Rewritten original
http://server:port/servlet/Rewritten/123 extra path information
http://server:port/servlet/Rewritten?sessionid=123 added
parameter
http://server:port/servlet/Rewritten;$sessionid$123
custom change
1 December 2021 72
URL-Rewritting
• code snippet
Loginurlrewriting.html
<form name="login" method="post" action="./URLRewriting">
<p>please enter login credentials</p>
User Name : <input type="text" name="txtUserName"> <br>
password : <input type="password" name="txtPassword"> <input
type="submit" value='submit'>
</form>
URLRewriting.java
response.getWriter().append("Served at: ").append(request.getContextPath());
String name= request.getParameter("txtUserName");
String pwd = request.getParameter("txtPassword");
request.getRequestDispatcher("/LoginUrlReceive?uname="+name+"&&pwd="+pwd).forward(request
, response);
1 December 2021 73
URL-Rewritting
• code snippet
LoginUrlReceive.java
String username = request.getParameter("uname");
String password = request.getParameter("pwd");
pw.println("LoginUrlReceive username::"+username+"password::"+password);
1 December 2021 74
Hidden form fields
• One way to support anonymous session tracking is to use hidden form fields.
As the name implies, these are fields added to an HTML form that are not
displayed in the client's browser. They are sent back to the server when the
form that contains them is submitted. You include hidden form fields with HTML
like this:
• <FORM ACTION="/servlet/MovieFinder" METHOD="POST">
...
<INPUT TYPE=hidden NAME="zip" VALUE="94040">
<INPUT TYPE=hidden NAME="level" VALUE="expert">
..
</FORM>
In a sense, hidden form fields define constant variables for a form. To a servlet
receiving a submitted form, there is no difference between a hidden field and a
visible field.
1 December 2021 75
Hidden form fields
• code snippet
Loginhidform.html
<form name="login" method="post" action="./HiddenServlet">
<p>please enter login credentials</p>
User Name : <input type="text" name="txtUserName"> <br>
password : <input type="password" name="txtPassword"> <input
type="submit" value='submit'>
</form>
HiddenServlet.java
String name = request.getParameter("txtUserName");
String pwd = request.getParameter("txtPassword");
out.print("<form action='./LoginUrlReceive'>");
out.print("<input type='hidden' name='uname' value='" + name + "'>");
out.print("<input type='hidden' name='pwd' value='" + pwd + "'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
1 December 2021 76
Hidden form fields
• code snippet
LoginUrlReceive.java
String username = request.getParameter("uname");
String password = request.getParameter("pwd");
pw.println("LoginUrlReceive username::"+username+"password::"+password);
1 December 2021 77
Session tracking API
• The session tracking API is in javax.servlet.http.HttpSession and is built on
top of cookies.
• To use the session tracking API:
- Create a session:
HttpSession session = request.getSession();
Returns the session associated with this request
If there was no associated session, one is created.
- Store information in the session and retrieve it as needed:
session.setAttribute (name, value);
Object obj = getAttribute(name);
• Session information is automatically maintained across requests.
1 December 2021 78
Looking up information associated with session
• getId - This method returns the unique identifier generated for each session.
It is sometimes used as the key name when there is only a single value
associated with a session, or when logging information about previous
sessions.
• isNew - This returns true if the client (browser) has never seen the session,
usually because it was just created rather than being referenced by an
incoming client request. It returns false for preexisting sessions.
1 December 2021 79
• getCreationTime - This returns the time, in milliseconds since the epoch, at
which the session was made. To get a value useful for printing out, pass the
value to the Date constructor or the setTimeInMillis method of
GregorianCalendar.
• getLastAccessedTime - This returns the time, in milliseconds since the
epoch, at which the session was last sent from the client.
• getMaxInactiveInterval - This returns the amount of time, in seconds, that a
session should go without access before being automatically invalidated. A
negative value indicates that the session should never timeout.
(Contd..)
1 December 2021 80
• Public Object getValue(String name)
• Public Object getAttribute (String name)
• Public Object setValue(String name, Object value)
• Public Object setAttribute (String name, Object value)
• Public Object removeValue(String name)
• Public Object removeAttribute(String name)
(Contd..)
1 December 2021 81
Code snippet
Loginsession.html
<form name="login" method="post" action="./AdminServletSession">
<p>please enter login credentials</p>
User Name : <input type="text" name="txtUserName"> <br>
password : <input type="password" name="txtPassword"> <input
type="submit" value='submit'>
</form>
AdminServletSession.java
HttpSession session = request.getSession(true);
String reqUsername = request.getParameter("txtUserName");
String reqPassword = request.getParameter("txtPassword");
out.println("AdminServletSession::"+"username::"+reqUsername+ "password ::"+reqPassword);
session.setAttribute("USERNAME", reqUsername);
session.setAttribute("PASSWORD", reqPassword);
request.getRequestDispatcher("./HRServletSession").forward(request, response);
(Contd..)
1 December 2021 82
Code snippet
Loginsession.html
< HttpSession session = request.getSession(true);
String sessionUsername =(String) session.getAttribute("USERNAME");
String sessionPassword = (String) session.getAttribute("PASSWORD");
out.println("HRServletSession::"+"username::"+sessionUsername+ "password
::"+sessionPassword);
(Contd..)

More Related Content

What's hot

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepRajiv Gupta
 
Big data: current technology scope.
Big data: current technology scope.Big data: current technology scope.
Big data: current technology scope.Roman Nikitchenko
 
Java EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJava EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJosh Juneau
 
Architecting virtualized infrastructure for big data presentation
Architecting virtualized infrastructure for big data presentationArchitecting virtualized infrastructure for big data presentation
Architecting virtualized infrastructure for big data presentationVlad Ponomarev
 
Utilizing JSF Front Ends with Microservices
Utilizing JSF Front Ends with MicroservicesUtilizing JSF Front Ends with Microservices
Utilizing JSF Front Ends with MicroservicesJosh Juneau
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutesArun Gupta
 
Contributors Guide to the Jakarta EE 10 Galaxy
Contributors Guide to the Jakarta EE 10 GalaxyContributors Guide to the Jakarta EE 10 Galaxy
Contributors Guide to the Jakarta EE 10 GalaxyJakarta_EE
 
Intro to React
Intro to ReactIntro to React
Intro to ReactJustin Reock
 
Java EE 8 Recipes
Java EE 8 RecipesJava EE 8 Recipes
Java EE 8 RecipesJosh Juneau
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js SimplifiedSunil Yadav
 
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)Kevin Sutter
 
NLOUG 2017- Oracle WebCenter Portal 12c Performance
NLOUG 2017- Oracle WebCenter Portal 12c PerformanceNLOUG 2017- Oracle WebCenter Portal 12c Performance
NLOUG 2017- Oracle WebCenter Portal 12c PerformanceDaniel Merchán García
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introductionejlp12
 
Java EE 8 Update
Java EE 8 UpdateJava EE 8 Update
Java EE 8 UpdateRyan Cuprak
 

What's hot (20)

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by step
 
Type script
Type scriptType script
Type script
 
Next stop: Spring 4
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4
 
Big data: current technology scope.
Big data: current technology scope.Big data: current technology scope.
Big data: current technology scope.
 
Java EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVCJava EE 8 Web Frameworks: A Look at JSF vs MVC
Java EE 8 Web Frameworks: A Look at JSF vs MVC
 
Architecting virtualized infrastructure for big data presentation
Architecting virtualized infrastructure for big data presentationArchitecting virtualized infrastructure for big data presentation
Architecting virtualized infrastructure for big data presentation
 
Utilizing JSF Front Ends with Microservices
Utilizing JSF Front Ends with MicroservicesUtilizing JSF Front Ends with Microservices
Utilizing JSF Front Ends with Microservices
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes
 
Contributors Guide to the Jakarta EE 10 Galaxy
Contributors Guide to the Jakarta EE 10 GalaxyContributors Guide to the Jakarta EE 10 Galaxy
Contributors Guide to the Jakarta EE 10 Galaxy
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Javascript
JavascriptJavascript
Javascript
 
Java EE 8 Recipes
Java EE 8 RecipesJava EE 8 Recipes
Java EE 8 Recipes
 
React Js Simplified
React Js SimplifiedReact Js Simplified
React Js Simplified
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
 
NLOUG 2017- Oracle WebCenter Portal 12c Performance
NLOUG 2017- Oracle WebCenter Portal 12c PerformanceNLOUG 2017- Oracle WebCenter Portal 12c Performance
NLOUG 2017- Oracle WebCenter Portal 12c Performance
 
Ecom 1
Ecom 1Ecom 1
Ecom 1
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
 
Java EE 8 Update
Java EE 8 UpdateJava EE 8 Update
Java EE 8 Update
 
NLOUG 2018 - Future of JSF and ADF
NLOUG 2018 - Future of JSF and ADFNLOUG 2018 - Future of JSF and ADF
NLOUG 2018 - Future of JSF and ADF
 

Similar to Servlet programming

WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxkarthiksmart21
 
Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Gera Paulos
 
Intorduction to struts
Intorduction to strutsIntorduction to struts
Intorduction to strutsAnup72
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...WebStackAcademy
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music storeADEEBANADEEM
 
Edge 2016 Session 1886 Building your own docker container cloud on ibm power...
Edge 2016 Session 1886  Building your own docker container cloud on ibm power...Edge 2016 Session 1886  Building your own docker container cloud on ibm power...
Edge 2016 Session 1886 Building your own docker container cloud on ibm power...Yong Feng
 
Webapplication ppt prepared by krishna ballabh gupta
Webapplication ppt prepared by krishna ballabh guptaWebapplication ppt prepared by krishna ballabh gupta
Webapplication ppt prepared by krishna ballabh guptaShivalik college of engineering
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overviewramya marichamy
 
Transforming the web into a real application platform
Transforming the web into a real application platformTransforming the web into a real application platform
Transforming the web into a real application platformMohanadarshan Vivekanandalingam
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...Edward Burns
 
Meteor South Bay Meetup - Kubernetes & Google Container Engine
Meteor South Bay Meetup - Kubernetes & Google Container EngineMeteor South Bay Meetup - Kubernetes & Google Container Engine
Meteor South Bay Meetup - Kubernetes & Google Container EngineKit Merker
 
Open shift and docker - october,2014
Open shift and docker - october,2014Open shift and docker - october,2014
Open shift and docker - october,2014Hojoong Kim
 
Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC  Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC vipin kumar
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technologyMinal Maniar
 
Server side programming
Server side programming Server side programming
Server side programming javed ahmed
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivitypkaviya
 

Similar to Servlet programming (20)

WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)Servlets as introduction (Advanced programming)
Servlets as introduction (Advanced programming)
 
Intorduction to struts
Intorduction to strutsIntorduction to struts
Intorduction to struts
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 
Ppt for Online music store
Ppt for Online music storePpt for Online music store
Ppt for Online music store
 
JAVA
JAVAJAVA
JAVA
 
Edge 2016 Session 1886 Building your own docker container cloud on ibm power...
Edge 2016 Session 1886  Building your own docker container cloud on ibm power...Edge 2016 Session 1886  Building your own docker container cloud on ibm power...
Edge 2016 Session 1886 Building your own docker container cloud on ibm power...
 
Webapplication ppt prepared by krishna ballabh gupta
Webapplication ppt prepared by krishna ballabh guptaWebapplication ppt prepared by krishna ballabh gupta
Webapplication ppt prepared by krishna ballabh gupta
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Transforming the web into a real application platform
Transforming the web into a real application platformTransforming the web into a real application platform
Transforming the web into a real application platform
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
HTTP/2 Comes to Java: Servlet 4.0 and what it means for the Java/Jakarta EE e...
 
Meteor South Bay Meetup - Kubernetes & Google Container Engine
Meteor South Bay Meetup - Kubernetes & Google Container EngineMeteor South Bay Meetup - Kubernetes & Google Container Engine
Meteor South Bay Meetup - Kubernetes & Google Container Engine
 
Open shift and docker - october,2014
Open shift and docker - october,2014Open shift and docker - october,2014
Open shift and docker - october,2014
 
Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC  Cloud compiler - Minor Project by students of CBPGEC
Cloud compiler - Minor Project by students of CBPGEC
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Server side programming
Server side programming Server side programming
Server side programming
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 

More from Mallikarjuna G D

More from Mallikarjuna G D (20)

Reactjs
ReactjsReactjs
Reactjs
 
Bootstrap 5 ppt
Bootstrap 5 pptBootstrap 5 ppt
Bootstrap 5 ppt
 
CSS
CSSCSS
CSS
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Mmg logistics edu-final
Mmg  logistics edu-finalMmg  logistics edu-final
Mmg logistics edu-final
 
Interview preparation devops
Interview preparation devopsInterview preparation devops
Interview preparation devops
 
Interview preparation testing
Interview preparation testingInterview preparation testing
Interview preparation testing
 
Interview preparation data_science
Interview preparation data_scienceInterview preparation data_science
Interview preparation data_science
 
Interview preparation full_stack_java
Interview preparation full_stack_javaInterview preparation full_stack_java
Interview preparation full_stack_java
 
Enterprunership
EnterprunershipEnterprunership
Enterprunership
 
Core java
Core javaCore java
Core java
 
Git Overview
Git OverviewGit Overview
Git Overview
 
Jenkins
JenkinsJenkins
Jenkins
 
Hadoop
HadoopHadoop
Hadoop
 
Digital marketing
Digital marketingDigital marketing
Digital marketing
 
Training
TrainingTraining
Training
 
Project excursion career_orientation
Project excursion career_orientationProject excursion career_orientation
Project excursion career_orientation
 
Installer benchmarking
Installer benchmarkingInstaller benchmarking
Installer benchmarking
 
Sql implementations
Sql implementationsSql implementations
Sql implementations
 
Dao benchmark
Dao benchmarkDao benchmark
Dao benchmark
 

Recently uploaded

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 

Recently uploaded (20)

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 

Servlet programming

  • 1. 1 December 2021 1 Servlet Name :: Mallikarjuna G D Reach me @ Training :: Email :: gdmallikarjuna@gmail.com
  • 2. 1 December 2021 2 Agenda • Introduction to Web Application Technologies • CGI Programs on the Web Server • What is servlet? • Jobs of servlet • Advantages over CGI • Why pages are build dynamically? • Servlet container • Installation & configuration - Type 1: Integration of Tomcat server and eclipse - Type 2: Java Servlet • Servlet Sample Example • Servlet Overview And Architecture - Servlet Life cycle/Single Thread Model - Interface Servlet - HttpServlet Class - HttpServletRequest, HttpServletResponse
  • 3. 1 December 2021 3 Agenda • Handling client request :Http request • Generating Server Response : Http status code • Handling Session - Cookies - Session Tracking - URL-re writing - Hidden Form fields
  • 4. 1 December 2021 4 Introduction to Web Application Technologies • World Wide Web: HTTP (Hypertext Transfer Protocol) is similar to FTP because it is a protocol to transfer files from the server to client. HTTP was created in conjunction with related HTML standard. HTML (Hypertext Markup Language) is a document display language that lets users link from one document to another. HTML permits images and other media objects to be embedded in an HTML document. The media objects are stored in files on a server. HTTP also retrieves these files. Therefore HTTP can be used to transmit any file that confirms to multipurpose Internet Mail Extensions (MIME) specification.
  • 5. 1 December 2021 5 • Web Browsers and and Web Servers: To view an HTML document with rich media content, a graphical user interface was built on the top of the client-side HTTP. This GUI is called as web browser. The server-side HTTP component is called a web server. • Web Applications: Early in the development of HTML, the designers created a mechanism to permit a user to invoke a program on the web server. This mechanism was called as Common Gateway Interface (CGI). When a website includes CGI processing, this is called a web application. (Contd..)
  • 6. 1 December 2021 6 CGI Programs on the Web Server • The browser needs to send data to the CGI program on the server. The CGI specification defines how the data is packaged and sent in the HTTP request to the server. This data is usually typed into the web browser in an HTML form. • The URL determines which CGI program to execute. This might be a script or an executable file. • The CGI program parses the CGI data in the request, processes the data, and generates a response. • The CGI response is sent back to the web server, which wraps the response in an HTTP response. • The HTTP response is sent back to the web browser.
  • 7. 1 December 2021 7 Web Server Architecture with CGI Programs (Contd..)
  • 8. 1 December 2021 8 Advantages and Disadvantages of CGI Programs • Programs can be written in a variety of languages, although they are primarily written in Perl. • A CGI program with bugs does not crash the web server. • Programs are easy for a web designer to reference. When the script is written, the designer can reference it in one line in a web page. • Because CGI programs execute in their own OS Shell, these programs do not have concurrency conflicts with other HTTP requests executing the same CGI program. • All service provides support CGI programs.
  • 9. 1 December 2021 9 • The response time of CGI programs is high because CGI programs execute in their own OS shell. The creation of an OS shell is a heavyweight activity for the OS. • CGI is not scalable. • The languages for CGI are not always secure or object-oriented. • The CGI script has to generate an HTML response, so the CGI code is mingled with HTML. This is not good separation of presentation and business logic. • Scripting languages are often platform-dependent. Disadvantages
  • 10. • Servlet is a program that runs on server acts as a middle layer between a request coming from web-browser or other HTTP Clients and database or applications on the Server. • Improved substitute for CGI Scripts. • Are executed in context of web server. • Part of JEE (Servlet API 2.4) • Helps client server communication. 1 December 2021 10 What is Servlet?
  • 11. 1 December 2021 11 Jobs of servlet? • Read explicit data sent by client (form data) • Read implicit data sent by client (request header) • Generate the result • Send the explicit data back to client (e.g. HTML format) • Send the implicit data to client (status code and response header) Servlet: HTTP Web Server File system Servlet Server Static Tomcat = Web Server + Servlet Server Other.. Dynamic
  • 12. 1 December 2021 12 Advantages of Servlet over CGI • Efficient/Scalable-handled by separate thread within web-server process. • Convenient - lot of high level utilities. • Powerful – Sharing data, pooling, persistence. • Portable – Run virtually on all operating systems and servers. • Security – No shell escapes, no bufferflow. • Inexpensive.
  • 13. 1 December 2021 13 Disadvantages: • Servlets often contain both business logic and presentation logic. Presentation logic is anything that controls how the application presents information to the user. Generating the HTML response within the servlet code is presentation logic. Business logic is anything that manipulates data to accomplish something such as storing data. • Servlets must handle concurrency issues. • Mixing presentation and business logic means that whenever a web page changes the servlets must be rewritten, recompiled and redeployed. • This disadvantage led to the development of template pages, including Java Server Pages technology.
  • 14. 1 December 2021 14 Why build pages dynamically? • The web page is based on data submitted by the user. e.g.:- result in search engines , online shopping so on. • The web pages are derived from the data changes frequently. e.g.:-weather report, stock exchange, news headline. • The web pages are derived from data from databases or other server side resources. e.g.:- e-commerce page shows availability of product with price information.
  • 15. 1 December 2021 15 Servlet Container/Servlet Engine • The servlet container is compiled, executable program. The container acts as intermediator between webserver and servlet in the container. • The container loads, initializes and executes servlet. When request arrives container maps to servlet. • The container is designed to perform well by serving large number of requests. A container can hold any number of servlets, filters and listener. • Both the container and object contained in it are multithreaded. The container handles multiple requests concurrently, and more than one thread may enter an object at a time. Therefore, each object within a container must be thread safe.
  • 16. 1 December 2021 16 (Contd..) There are three kinds of servlet engine - standalone - add on - embedded • Standalone Servlet Engines - Built in support for servlets. - Hard to keep latest version of servlet. • Add on servlet Servlet-engines - Plug-in to an existing servlets. • Embeddable servlet engines - lightweight servlet-deployment platform that can be embedded in another application.
  • 17. 1 December 2021 17 List of servlet containers Non commercial: • Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under the Apache Software License. • Apache Geronimo -is a full Java EE implementation by Apache. • Jetty • Jaminid - contains a higher abstraction than servlets. • Enhydra • Winstone - supports specification v2.4, has a focus on minimal configuration and the ability to strip the container down to only what you need. • tjws - spec 2.4, small footprint, modular design
  • 18. 1 December 2021 18 Commercial: • BEA WebLogic Server or Weblogic Express, from BEA Systems • Borland Enterprise Server • GlassFish (open source) • Java System Application Server, from Sun Microsystems • Java System Web Server, from Sun Microsystems • JBoss (open source) • JRun, from Adobe Systems (formerly developed by Allaire Corporation) (Contd..)
  • 19. 1 December 2021 19 • LiteWebServer (open source) • Oracle Application Server, from Oracle Corporation • Orion Application Server, from IronFlare • Caucho's Resin Server • ServletExec, from New Atlanta Communications • WebObjects, from Apple Inc. • WebSphere, from IBM (Contd..)
  • 20. 1 December 2021 20 • The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of a Web container and a servlet. • A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. • A Servlet is an object that receives a request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment Java Servlet API
  • 21. 1 December 2021 21 Servlet API History The complete servlet specification was created by Sun Microsystems, with version 1.0 finalized in June 1997. Starting with version 2.3, the servlet specification was developed under the Java Community Process.
  • 22. 1 December 2021 22 Installation and Configuration • Step 1: jdk 11.0 • Download the JDK 11.0 offline installation file (Windows Offline Installation, Multi-language) from Oracle' https://www.oracle.com/java/technologies/downloads/#java11-windows. The online installation will download the installation files through the internet and you will have to re-download them each time you format your HD. • Double click on the .exe file (throughout I assume XP or VISTA or Windows 10, or some other crappy Micro$oft OS). The following screen should pop up:
  • 23. 1 December 2021 23 (Contd..)
  • 24. 1 December 2021 24 (Contd..) We still have to go that extra bit and set up some environment variables - primarily create JAVA_HOME and edit the PATH system variable. In the computers Control Panel double click on the System icon and select the Advanced tab. The result should be something not foreign to the screenshot below:
  • 25. 1 December 2021 25 (Contd..) Set path to the java_home/bin:, finally restart.. And open command prompt to check java installed by giving java –version in prompt.
  • 26. 1 December 2021 26 • Step 2: Install Eclipse download eclipse IDE from http://www.eclipse.org/downloads/ and extract to the required folder. • Step 3: Install Jakarta Tomcat download tomcat 9.x from this site in zip format http://tomcat.apache.org/, then extract to required folder. (Contd..)
  • 27. 1 December 2021 27 (Contd..) • Step 5: Configure Eclipse - start eclipse, and do configuration as per below screen shots.
  • 28. 1 December 2021 28 (Contd..)
  • 29. 1 December 2021 29 Simple Servlet configuration & development 1. Select File > New > Dynamic Web Project..
  • 30. 1 December 2021 30 (Contd..) Input the following code in to the file SimpleServlet.java and click Save button in toolbar. import java.io.PrintWriter; public class SimpleServlet extends javax.servlet.http.HttpServlet { public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { performTask(request, response); } public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { performTask(request, response); }
  • 31. 1 December 2021 31 (Contd..) public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { try { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "This is a Simple Servlet Demo"); } catch(Throwable theException) { //theException.printStackTrace(); } } }
  • 32. 1 December 2021 32 (Contd..) Web.xml content: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <servlet> <servlet-name>SimpleServlet</servlet-name> <servlet-class>SimpleServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SimpleServlet</servlet-name> <url-pattern>/SimpleServlet</url-pattern> </servlet-mapping> </web-app>
  • 33. 1 December 2021 33 (Contd..) Press the Start Tomcat button in tool bar, after tomcat starts, open a browser and input the URL: http://localhost:8080/ServletDemo/SimpleServlet The result will show as below:
  • 34. 1 December 2021 34 (Contd..) Finally, run the server to see output.
  • 35. 1 December 2021 35 Directory Structure
  • 36. 1 December 2021 36 Servlet Life cycle and Architecture Servlets are first standard to extension to java including two packages: -javax.servlet -javax.servlet.http In general, servlet 1. Generic Servlet - must extend javax.servlet.Servlet - protocol independent 2. Http Servlet - must extend javax.servlet.http.HttpServlet - Handling Http request/reply
  • 37. 1 December 2021 37 (Contd..) Http Servlet: Generic Servlet:
  • 38. 1 December 2021 38 Servlet Life Cycle • The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps: - If an instance of the servlet does not exist, the Web container loads the servlet class. Creates an instance of the servlet class. Initializes the servlet instance by calling the init method. - Invokes the service method, passing a request and response object. • If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method.
  • 39. 1 December 2021 39 Servlet Life Cycle
  • 40. 1 December 2021 40 (Contd..) Java class that implements the Servlet interface • Servlet Interface – Defines the Servlet’s life cycle methods. – init(ServletConfig config) – service(ServletRequest req, ServletResponse res) - doGet handles GET request. - doPost handles POST request. – destroy() Called by the servlet container before servlet is taken out of service.
  • 41. 1 December 2021 41 Allowing concurrency: Single thread Model • Container may send multiple request to single instance , using java threads. So service methods (doGet, doPost..) are all thread safe. It means two or more threads operating without interfere each other. • If service methods not thread safe. We have to use single thread model. • The single thread model ensures that only one service method runs at time
  • 42. 1 December 2021 42 Servlet Interface Servlet interface { void init(ServletConfig sc) throws ServletException; void service(ServletRequest req,ServletResponse res) throws ServletException,IOException; void destroy(); }
  • 43. 1 December 2021 43 Methods of Servlet Method Description void init( ServletConfig config ) The servlet container calls this method once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet. ServletConfig getServletConfig( ) This method returns a reference to an object that implements interface ServletConfig. This object provides access to the servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes). String getServletInfo() This method is defined by a servlet programmer to return a string containing servlet information such as the servlet’s author and version. void service( ServletRequest request, ServletResponse response ) The servlet container calls this method to respond to a client request to the servlet. void destroy() This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection, should be deallocated here.
  • 44. 1 December 2021 44 Http Servlet • Override the servlet class • There are two types of request- Get and Post - doGet responds to Get request -doPost responds to Post request • It has HttpServletRequest and HttpServletResponse Objects
  • 45. 1 December 2021 45 (Contd..) Method Description doDelete Called in response to an HTTP delete request. Such a request is normally used to delete a file from a server. This may not be available on some servers, because of its inherent security risks (e.g., the client could delete a file that is critical to the execution of the server or an application). doHead Called in response to an HTTP head request. Such a request is normally used when the client only wants the headers of a response, such as the content type and content length of the response. doOptions Called in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such as the version of HTTP (1.0 or 1.1) and the request methods the server supports. doPut Called in response to an HTTP put request. Such a request is normally used to store a file on the server. This may not be available on some servers, because of its inherent security risks (e.g., the client could place an executable application on the server, which, if executed, could damage the server—perhaps by deleting critical files or occupying resources). doTrace Called in response to an HTTP trace request. Such a request is normally used for debugging. The implementation of this method automatically returns an HTML document to the client containing the request header information (data sent by the browser as part of the request).
  • 46. 1 December 2021 46 HttpServletRequest Interface • Web server - creates an HttpServletRequest object. - passes it to the servlet’s service method. • HttpServletRequest object contains the request from the client.
  • 47. 1 December 2021 47 (Contd..) Method Description String getParameter( String name ) Obtains the value ofa parameter sent to the servlet as part ofa get or post request. The name argument represents the parameter name. Enumeration getParameterNames() Returns the names ofallthe parameters sent to the servlet as part ofa post request. String[] getParameterValues( String name ) For a parameter with multiple values, this method returns anarrayofstrings containing the values for a specified servlet parameter. Cookie[] getCookies() Returns anarrayof Cookie objects stored onthe client bythe server. Cookie objects canbe used to uniquely identifyclients to the servlet. HttpSession getSession( booleancreate ) Returns an HttpSession object associated withthe client’s current browsing session. This method cancreate an HttpSession object (true argument) ifone does not alreadyexist for the client. HttpSession objects are used insimilar ways to Cookies for uniquely identifying clients.
  • 48. 1 December 2021 48 HttpServletResponse Interface Method Description void addCookie( Cookie cookie ) Used to add a Cookie to the header of the response to the client. The Cookie’s maximum age and whether Cookies are enabled on the client determine if Cookies are stored on the client. ServletOutputStream getOutputStream() Obtains a byte-based output stream for sending binary data to the client. PrintWriter getWriter() Obtains a character-based output stream for sending text data to the client. void setContentType( String type ) Specifies the MIME type of the response to the browser. The MIME type helps the browser determine how to display the data (or possibly what other application to execute to process the data). For example, MIME type "text/html" indicates that the response is an HTML document, so the browser displays the HTML page. • Web server - creates an HttpServletResponse object. - passes it to the servlet’s service method.
  • 49. 1 December 2021 49 Handling client request : Http request header General: getHeader, getHeaders, getHeaderNames. Specialized: getCookies, getAuthType, getRemoteUser, getContentLength, getContentType, getDateHeader, getIntHeader Related Info: getMethod, getRequestURI, getProtocol
  • 50. 1 December 2021 50 (Contd..)
  • 51. 1 December 2021 51 Common HTTP Request Header 1.1 • Accept - MIME Types of browser can handle. - Can send different content to different clients. • Accept-Encoding - Indicate encoding (e.g gzip) browser can handle. • Authorization - User identification for password protected pages. • Connection - In Http 1.1, keep alive means browser can handle persistent connection. Persistent connection is default. Persistent means same socket is reused for same type of client request.
  • 52. 1 December 2021 52 (Contd..) • Cookie - Give cookies previously sent to client. • Host - It gives host given in original URL. • If-Modified-Since - Client wants pages, only after changed on some specified dates. • Referrer - URL of referring web page. - Useful for tracking traffic; logged by many servers. • User Agent - String identifying the browser making request.
  • 53. 1 December 2021 53 Generating server response: http status code Purpose: The variety of status code that are essentially indicate failure. e.g.:- HTTP/1.1 200 OK • Changing a status code perform a lot of tasks. - Forward client to another page. - Indicate a missing resource. - Instruct a browser to use cached copy. • Set status before sending document. public void setStatus (int statusCode) - use constant for the code. Not an explicit int. constants are HttpServletResponse. - Names derived from standard message. e.g SC_OK, SC_NOT_FOUND so on. • public sendError(int code, String msg) - Wraps the message inside HTML document.
  • 54. 1 December 2021 54 (Contd..) • Public void sendRedirect(String url) - Relative url is permitted in 2.2/2.3 - Also sets location header. Common HTTP 1.1 Status codes: • 200(OK) - Everything is fine, document follows, default for servlets. • 204(No content) - Browser should keep displaying previous document. • 301(Moved document) - Requested document moved elsewhere. - Browsers go to new location automatically.
  • 55. 1 December 2021 55 (Contd..) • 401(unauthorized) Browser tried to access protected page without proper authorization header. • 404(Not found) No such page. In general 100-199 -> codes in the 100s are informational, indicating that the client should respond with some other action. 200-299 -> values in the 200’s signify that the request was successful. 300-399 -> values in the 300’s are used for files that have moved and usually include location header indicating the new address.
  • 56. 1 December 2021 56 (Contd..) 400-499 -> values in the 400’s indicate an error by the client. 500-599 ->codes in the 500’s signify an error by the server. Common MIME Type:
  • 57. 1 December 2021 57 Session Handling • A server site typically needs to maintain two types of persistent(remembered) information: - Information about the Session. - Information about the User. • Servlet capabilities: Servlets, like Applets, can be trusted or untrusted. - A servlet can use a unique ID to store and retrieve information about a given session. - User information usually requires a login ID and a password. - Since servlets don’t quit between requests, any servlet can maintain information in its internal data structures, as long as the server keeps running.
  • 58. 1 December 2021 58 (Contd..) - A trusted servlet can read and write files on the server, hence can maintain information about sessions and users even when the server is stopped and restarted. - An untrusted servlet will lose all information when the servlet or server stops for any reason. This is sometimes good enough for session information. This is almost never good enough for user information. - HTTP is stateless: When it gets a page request, it has no memory of any previous requests from the same client.
  • 59. 1 December 2021 59 (Contd..) • Session tracking is keeping track of what has gone before in this particular conversation. - Since HTTP is stateless, it does not do this for you. - You have to do it yourself, in your servlets. - This makes it difficult to hold a “conversation”. Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests. - The server must be able to keep track of multiple conversations with multiple users.
  • 60. 1 December 2021 60 • Cookies are small files that the servlet can store on the client computer, and retrieve later. • URL rewriting: You can append a unique ID after the URL to identify the user. • Hidden <form> fields can be used to store a unique ID. • Java’s Session Tracking API can be used to do most of the work for you. Session tracking solution
  • 61. 1 December 2021 61 Cookies • Cookies are small bits of textual information that a web server sends to the browser and that the browser returns unchanged when later visiting the same website or domain. • Cookies are not a security threat. • Cookies can be a privacy threat. - Cookies can be used to customize advertisements. - Outlook Express allows cookies to be embedded in email. - A servlet can read your cookies. Incompetent companies might keep your credit card info in a cookie. Netscape lets you refuse cookies to sites other than that to which you connected.
  • 62. 1 December 2021 62 Why do we need cookies? • Cookies are a very useful tool in maintaining state (persistence) on the Web. Unless something special is done, web servers are only aware of users when a transaction -- sending or receiving information -- is in process. The moment the transaction is complete the server forgets about the user and makes no attempt to correlate subsequent transactions with previous exchanges. • Since the web protocol, HTTP, is a "stateless" (non-persistent) protocol, it is impossible to differentiate between visits to a given web site, unless the server can somehow "mark" a visitor. • This is done by storing a piece of information in the visitor's browser, called a "cookie". Cookies can contain database information, custom page settings, or just about anything that would make a site customizable.
  • 63. 1 December 2021 63 Using cookies • import javax.servlet.http.*; • Constructor: Cookie(String name, String value) • Assuming request is an HttpServletRequest and response is an HttpServletResponse, response.addCookie(cookie); Cookie[ ] cookies = request.getCookies(); String name = cookies[i].getName(); String value = cookies[i].getValue(); • There are, of course, many more methods in the HttpServletRequest, HttpServletResponse, and Cookie classes in the javax.servlet.http package.
  • 64. 1 December 2021 64 (Contd..) • public void setComment(String purpose) - public String getComment() • public void setMaxAge(int expiry) - public int getMaxAge() - Max age in seconds after which cookie will expire. - If expiry is negative, delete when browser exits. - If expiry is zero, delete cookie immediately. • setSecure(boolean flag) - public boolean get Secure() - Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.
  • 65. 1 December 2021 65 (Contd..) Here is the code snippet for initializing a cookie and adding the same to the response object. ..... Cookie cookie = new Cookie ("otncookiename",userName); cookie.setMaxAge(86400); response.addCookie(cookie); Cookie onemorecookie = new Cookie("otncookiepassword",password); onemorecookie.setMaxAge(86400); response.addCookie (onemorecookie); ..... Setting cookies:
  • 66. 1 December 2021 66 (Contd..) Retrieving a cookie value: Here is the code snippet for selecting cookie values from the request object. ...... Cookie[] cookieArray = request.getCookies(); if( cookieArray != null) { for( int i = cookieArray.length-1; i >= 0; i-- ) { Cookie cookie = cookieArray[i]; System.out.println ("Cookie name is " + cookie.getName()); System.out.println ("Cookie value is " + cookie.getValue()); } } ......
  • 67. 1 December 2021 67 (Contd..) Code snippet: Login.html <form name="login" method="post" action="./LoginCookieServlet"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> LoginCookieServlet String name= request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); Cookie userNameCookie = new Cookie("USERNAME", name); response.addCookie(userNameCookie); Cookie passwordCookie = new Cookie("PASSWORD",pwd); response.addCookie(passwordCookie); request.getRequestDispatcher("/LoginNextCookie").forward(request, response);
  • 68. 1 December 2021 68 (Contd..) Code snippet: LoginNextCookie Cookie[] cookies = request.getCookies(); pw.println("cookies[0].getValue()"+cookies[0].getValue()); pw.println("cookies[1].getValue()"+cookies[1].getValue()); for(Cookie cookie: cookies) { pw.println(cookie.getValue()); }
  • 69. 1 December 2021 69 Limitation • The browser should be enabled to accept cookies. • Cookie values must never have spaces, commas or semicolons. • Cookies can store upto 4KB of value.
  • 70. 1 December 2021 70 URL-Rewritting • URL rewriting is another way to support anonymous session tracking. • With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information. • The extra information can be in the form of extra path information, added parameters, or some custom, server-specific URL change. • Due to the limited space available in rewriting a URL, the extra information is usually limited to a unique session ID.
  • 71. 1 December 2021 71 URL-Rewritting • For example, the following URLs have been rewritten to pass the session ID 123: http://server: port/servlet/Rewritten original http://server:port/servlet/Rewritten/123 extra path information http://server:port/servlet/Rewritten?sessionid=123 added parameter http://server:port/servlet/Rewritten;$sessionid$123 custom change
  • 72. 1 December 2021 72 URL-Rewritting • code snippet Loginurlrewriting.html <form name="login" method="post" action="./URLRewriting"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> URLRewriting.java response.getWriter().append("Served at: ").append(request.getContextPath()); String name= request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); request.getRequestDispatcher("/LoginUrlReceive?uname="+name+"&&pwd="+pwd).forward(request , response);
  • 73. 1 December 2021 73 URL-Rewritting • code snippet LoginUrlReceive.java String username = request.getParameter("uname"); String password = request.getParameter("pwd"); pw.println("LoginUrlReceive username::"+username+"password::"+password);
  • 74. 1 December 2021 74 Hidden form fields • One way to support anonymous session tracking is to use hidden form fields. As the name implies, these are fields added to an HTML form that are not displayed in the client's browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this: • <FORM ACTION="/servlet/MovieFinder" METHOD="POST"> ... <INPUT TYPE=hidden NAME="zip" VALUE="94040"> <INPUT TYPE=hidden NAME="level" VALUE="expert"> .. </FORM> In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.
  • 75. 1 December 2021 75 Hidden form fields • code snippet Loginhidform.html <form name="login" method="post" action="./HiddenServlet"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> HiddenServlet.java String name = request.getParameter("txtUserName"); String pwd = request.getParameter("txtPassword"); out.print("<form action='./LoginUrlReceive'>"); out.print("<input type='hidden' name='uname' value='" + name + "'>"); out.print("<input type='hidden' name='pwd' value='" + pwd + "'>"); out.print("<input type='submit' value='go'>"); out.print("</form>");
  • 76. 1 December 2021 76 Hidden form fields • code snippet LoginUrlReceive.java String username = request.getParameter("uname"); String password = request.getParameter("pwd"); pw.println("LoginUrlReceive username::"+username+"password::"+password);
  • 77. 1 December 2021 77 Session tracking API • The session tracking API is in javax.servlet.http.HttpSession and is built on top of cookies. • To use the session tracking API: - Create a session: HttpSession session = request.getSession(); Returns the session associated with this request If there was no associated session, one is created. - Store information in the session and retrieve it as needed: session.setAttribute (name, value); Object obj = getAttribute(name); • Session information is automatically maintained across requests.
  • 78. 1 December 2021 78 Looking up information associated with session • getId - This method returns the unique identifier generated for each session. It is sometimes used as the key name when there is only a single value associated with a session, or when logging information about previous sessions. • isNew - This returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions.
  • 79. 1 December 2021 79 • getCreationTime - This returns the time, in milliseconds since the epoch, at which the session was made. To get a value useful for printing out, pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar. • getLastAccessedTime - This returns the time, in milliseconds since the epoch, at which the session was last sent from the client. • getMaxInactiveInterval - This returns the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never timeout. (Contd..)
  • 80. 1 December 2021 80 • Public Object getValue(String name) • Public Object getAttribute (String name) • Public Object setValue(String name, Object value) • Public Object setAttribute (String name, Object value) • Public Object removeValue(String name) • Public Object removeAttribute(String name) (Contd..)
  • 81. 1 December 2021 81 Code snippet Loginsession.html <form name="login" method="post" action="./AdminServletSession"> <p>please enter login credentials</p> User Name : <input type="text" name="txtUserName"> <br> password : <input type="password" name="txtPassword"> <input type="submit" value='submit'> </form> AdminServletSession.java HttpSession session = request.getSession(true); String reqUsername = request.getParameter("txtUserName"); String reqPassword = request.getParameter("txtPassword"); out.println("AdminServletSession::"+"username::"+reqUsername+ "password ::"+reqPassword); session.setAttribute("USERNAME", reqUsername); session.setAttribute("PASSWORD", reqPassword); request.getRequestDispatcher("./HRServletSession").forward(request, response); (Contd..)
  • 82. 1 December 2021 82 Code snippet Loginsession.html < HttpSession session = request.getSession(true); String sessionUsername =(String) session.getAttribute("USERNAME"); String sessionPassword = (String) session.getAttribute("PASSWORD"); out.println("HRServletSession::"+"username::"+sessionUsername+ "password ::"+sessionPassword); (Contd..)