Unit 6
Unit 6
Unit IV
By Ghazala Khan
Web and Web Application
Web consists of billions of clients and servers connected through wires
and wireless networks.
The web clients make requests to web servers. The web servers receive the
requests, find the resources and return the responses to the clients.
- Before, dynamic pages were constructed using the Common Gateway Interface (CGI).
- A separate process (CGI) was created for each client request, and this process
communicated with databases to get the required data, in languages like C, C++, Perl.
- CGI programs read data from the HTTP request and wrote data to the HTTP response.
- CGI had significant performance issues because a separate process had to be created
for each client request, which was resource-intensive ( processor and memory usage).
- Opening and closing Db connections for each request was costly.
- Platform Dependent
Alternative methods, such as Servlets, were introduced to solve these problems.
1. To request a page “abc.html” that will be built (at that time), send a request to the server.
2. Server doesn’t have it and has to build that page, it goes to a helper application (web container).
3. Web/Servlet container contains servlets. We’re using Apache Tomcat web container.
4. Servlets are Java files on the internet, take a request, process it, give an HTML page as response.
5. Request goes to Tomcat, Tomcat doesn’t have a page called abc.html, so execute a servlet..
6. You can have multiple servlets and many requests for one servlet.
7. Servlet name for this page is AddServlet, so when abc.html is being requested, this means
AddServlet is to be executed. This is taken care of by Deployment Descriptor.
8. Deployment Descriptor (web.xml) specifies for which request which servlet will be called.
9. In xml file, Servlet tag- class name, servlet-mapping tag - url (abc.html).
10. Extends HTTPServlet, so it meets all requirements, take request, process, give response. Response
goes to client in response object format.
11. Can use annotations to avoid xml files.
Serve
r ■ It is a running program or software that provides services.
■ Two types:
1. Better performance: Servlets run within the web server's address space
(memory area allocated for the web server to run its processes and handle
requests), so there's no need to create a new process for each client request,
making them faster.
2. Platform-independent: Since servlets are written in Java, they can run on any
platform that supports Java.
3. Security: The Java security manager ensures that servlets follow specific rules
to protect the server's resources.
4. Full Java functionality: Servlets can use all the Java libraries, allowing them to
interact with applets, databases, and other programs through mechanisms like
sockets and RMI.
5. Servlet technology is robust and scalable because of Java language.
Servlet life cycle
Assume that user enters a (URL) to a web browser. Browser generates an HTTP request for. This
request is then sent to the appropriate server.
Second, this HTTP request is received by the web server. The server gives this request to a
particular servlet. The servlet is dynamically retrieved and loaded into the address space of the
server.
Third, the server invokes the init( ) method of the servlet. This method is invoked only when the
servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet to
configure.
Fourth, the server invokes the service( ) method of the servlet. The service( ) method is called for
each HTTP request to process it.
● It is possible for the servlet to read data that has been provided in the HTTP request.
● It may also create an HTTP response for the client.
● The servlet remains in the server’s address space and is available to process any other HTTP
requests received from clients.
Finally, the server may decide to unload the servlet from its memory. The algorithms for this is
specific to each server. The server calls the destroy( ) method to release any resources such as
file handles that are allocated for the servlet. Important data may be saved to a persistent store.
The memory allocated for the servlet and its objects can then be garbage collected.
■ Each servlet instance is loaded once.
■ Each execution happens in a separate thread
■ Three methods:
■ init() : call only once to initialize servlet.
■ service() : Call for every request.
■ destroy() : call only once
STEPS:-
1. Load Servlet Class.
2. Create Instance of Servlet.
3. Call the servlets init() method.
4. Call the servlets service() method.
5. Call the servlets destroy() method.
Note: Step 1,2,3 executed only once when servlet is
initially loaded.
Step 4 executed "N"-times whenever http request
comes
Step 5 executed to destroy servlet means unload servlet
class
1) javax.servlet
2) javax.servlet.http
1)javax.servlet package
The java.servlet Package
The javax.servlet package contains a number of
interfaces and classes that establish the framework in
which servlets operate.
The most significant of these is Servlet. All servlets must
implement this interface or extend a class that implements
the interface.
The ServletRequest and ServletResponse interfaces are
also very important.
javax.servlet package:
interfaces
Interfaces Description
Servlet Declare life cycle methods for servlet. To
implement this interface we have to extend
GenericServlet or HttpServlet classes.
METHODS
● public String getInitParameter(String name):
Returns the value for the parameter “name”.
● Enumeration<String> getInitParameterNames():
Returns an enumeration of all the initialized
parameter names.
● public String getServletName():
Returns the name of the invoking servlet.
● public ServletContext getServletContext():
Returns the context (details) for this servlet.
ServletContext interface
■ Object of ServletContext is created by the web container
at time of deploying web application, only one
ServletContext object per web application.
- `getInputStream()`: Gets input stream to read binary data from the request.
- Eg: `getInputStream().read()` reads bytes from request body through inputstream
- `getServerPort()`: Returns the port number the request was sent to.
- Eg: returns `80` for HTTP.
ServletResponse
Interface
- enables a servlet
- `getCharacterEncoding()`: to create
Returns a response
the character for
encoding for the a
response.
client"UTF-8".
- Eg: returns
Classes Description
- `long getDateHeader(String field)`: Returns the date value for the header named *field*.
- Example: For a "Date" header, it might return "Tue, 20 Jun 2023 15:30:00 GMT."
- `String getHeader(String field)`: Returns the value of the specified header *field* as a string.
- Example: For a "Content-Type" header, it could return "text/html."
- `int getIntHeader(String field)`: Returns the integer value for the specified header *field*.
- Eg: For "Expires" header, it might return 120 for the number of seconds until expiry.
- String getPathInfo(): Returns any path info after the servlet path, before a query string.
- Eg: If the URL is https://example.com/app/user/profile/picture?size=large, it would return
"/user/profile/picture".
- String getPathTranslated()
The getPathTranslated() method converts any extra path information in a request
URL into a real path on the server’s file system.
URL: http://example.com/images/user/profile.jpg
Servlet Path: /images Path Info: /user/profile.jpg
server stores resources in directory: "/var/www/images” in its file system.
This would convert path into: "/var/www/images/user/profile.jpg"
- String getRemoteUser(): Returns the name of the user issuing this request.
- E.g., "johndoe"
- String getRequestURI(): Returns the URI, which is the part after the server address.
- Eg., for http://example.com/shop/products/item, returns "/shop/products/item".
- HttpSession getSession(boolean new): manage user sessions in a servlet by either creating a new
session or returning an existing one
E.g., If the new parameter is true, the server will:
● Return the existing session if already exists.
● Create and return a new session if no current session exists.
If the new parameter is false, the server will:
● Return the existing session if there is one.
● Return null if there is no current session
- boolean isRequestedSessionIdFromURL()
- Returns *true* if session ID is in the URL, else *false*. *E.g., false, indicating session ID was not
passed in the URL.*
- boolean isRequestedSessionIdValid()
- Returns *true* if the requested session ID is valid.
A session ID is a unique identifier assigned to each user session, allowing the server to
track and manage the user's activity across multiple requests.
HttpServletResponse
Interface-
void addCookie(Cookie cookie)
enables
● Addsaa servlet
cookie totothe
create
HTTPan HTTP response
response. E.g., Addsto a client. cookie with value
a "session"
"abc123".
boolean containsHeader(String field)
● Returns true if the HTTP response header contains a field named field. E.g.,
Returns true for "Content-Type" if Content-Type is present in header.
String encodeURL(String url)
● Determines if the session ID must be encoded in the URL and returns the modified
or original URL. E.g., Encodes "https://example.com" to include session ID.
String encodeRedirectURL(String url)
● Encodes the session ID in the URL for redirects if needed. E.g., Encodes "
https://example.com/redirect" to include session id if session tracking is needed.
void sendError(int code)
● Sends the error code to the client. E.g., Sends a 404 error code for a missing
page.
void sendError(int code, String msg)
● Sends the error code and message to the client. E.g., Sends 500 with "Internal
Server Error" message.
HttpServletResponse
Interface
void sendRedirect(String url)
● Redirects the client to the specified url. E.g., Redirects to
"https://example.com/homepage".
void setDateHeader(String field, long ms)
● Adds field to the header with date value equal to ms (milliseconds since Jan 1,
1970). E.g., Set "Expires" header to a future date.
void setHeader(String field, String value)
● Adds field to the header with value value. E.g., Sets "Content-Type" header to
"text/html".
void setIntHeader(String field, int value)
● Adds field to the header with integer value value. E.g., Sets "Content-Length"
header to 1024.
void setStatus(int code)
● Sets the status code for the response. E.g., Sets 200 for a successful response.
SESSION
In an e-commerce website, when a user logs in, an HTTP
session is created with a unique session ID. This session
stores user-specific data, such as their user ID, login status,
and items in their shopping cart. As the user browses and
adds products to their cart, the server retrieves and
updates this session data. If the user is inactive for a certain
period, the session expires, requiring them to log in again
to continue shopping. This mechanism allows for a
personalized and seamless shopping experience.
HttpSession interface (manages session-related data )
Enumeration<String> getAttributeNames()
Returns an enumeration of attribute names in the session. E.g., ["username", "cart", "preferences"].
long getCreationTime()
Returns the session creation time in milliseconds since January 1, 1970. E.g., 1625244000000 for a
session created on July 2, 2021.
String getId()
Returns the session ID. E.g., "SESSION123456789".
long getLastAccessedTime()
Returns the last accessed time in milliseconds since January 1, 1970. E.g., 1625247600000 when
user last accessed session.
void invalidate()
Invalidates and removes the session from context. E.g., Destroys session after user logout.
boolean isNew()
Returns true if the server created the session and it hasn’t been accessed. E.g., true for a newly
created session.
● Handles an HTTP DELETE request. E.g., Deletes a specific resource like "/user/123" (user with id 123).
● Handles an HTTP HEAD request. E.g.,When a client sends a HEAD request to "/status", the server responds with
headers, like status code and content type, but no body data.
● Handles an HTTP OPTIONS request. E.g., When a client sends an OPTIONS request to "/api", the server responds
with a list of HTTP methods supported at that endpoint (e.g., GET, POST, PUT).
● Handles an HTTP PUT request. E.g., Updating a user's details at "/user/123"(user with id 123).
● When a client sends a TRACE request to "/api/debug", the server responds with a diagnostic trace- showing the
path and any modifications made to the request by any servers on its way to the destination server.
● Returns the last modified time of the requested resource in milliseconds. E.g., 1625259000000 for a recent modification.
● Processes an HTTP request and response. E.g., Manages incoming requests to "/service-endpoint".
Cookie Class
■HTTP Cookies are little pieces of data that a web
application can store on the client machine of users
visiting the web application.
■Typically up to 4 kilo bytes (KB) of data can be stored.
■We can write cookies using HttpServletResponse object:
■Example:
Cookie cookie = new Cookie("myCookie", "myCookieValue");
response.addCookie(cookie);
Cooki
e
■ By default, each request from client to server is a new request.
■ Servlet sends response and cookies.
■ Cookies are stored in the cache of the browser on client machine
■ After that, if new request is sent by the user, cookie is sent along with
the request by default. Now, server recognizes the user as the old user.
Cookie:
Types
■Non-persistent cookie:
■It is valid for single session only. It is removed each time
when user closes the browser.
■Persistent cookie:
■It is valid for multiple sessions . It is not removed each time
when user closes the browser. It is removed only if user
logout or sign-out or clear cookies/cache memory of
browsers.
Object clone()
● Returns a copy of this object. E.g., Clones a cookie for re-use in another request.
String getComment()
● Returns the comment. E.g., "This cookie stores user session info."
String getDomain()
int getMaxAge()
● Returns the maximum age (in seconds) of the cookie. E.g., 3600 for one-hour expiry.
String getName()
String getPath()
● Returns the path. E.g., "/user" for a cookie accessible under "/user".
boolean getSecure()
● Returns true if the cookie is secure. Otherwise, returns false. E.g., true for cookies sent over
HTTPS.
String getValue()
boolean isHttpOnly()
● Returns true if the cookie has the HttpOnly attribute. Eg, if isHttpOnly() returns
true for a cookie, it means that cookie is protected from being accessed by
client-side scripts like JavaScript.
void setComment(String c)
void setDomain(String d)
● Sets the maximum age to sec. E.g., Sets expiry to 600 seconds.
void setPath(String p)
● Sets the path to p. E.g., Sets path to "/account".
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified
name and value.
■ Creating cookie object
Cookie ck=new Cookie("user",”Sandip");
Example:
import java.io.*; import javax.servlet.*;
public class Hello Servlet extends GenericServlet{