Unit 3
Unit 3
• Many applications are running concurrently over the Web, such as web browsing/surfing, e-mail, file transfer,
audio & video streaming, and so on.
• In order for proper communication to take place between the client and the server, these applications must agree
on a specific application-level protocol such as HTTP, FTP, SMTP, POP, and etc.
3
Hyper Text Transfer Protocol (HTTP)
• HTTP, the most used application protocol used on Web is a TCP/IP based communication protocol.
• A web browser may be the client, and an application on a computer that hosts a web site may be the server.
4
Hyper Text Transfer Protocol (HTTP) (…)
http://www.mysite.com:80/myfolder/myapp/mypage.html
6
HTTP Features
• There are three basic features that make HTTP a simple but powerful protocol:
o HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request and after a request is
made, the client disconnects from the server and waits for a response. The server processes the request and re-
establishes the connection with the client to send a response back.
o HTTP is media independent: It means, any type of data can be sent by HTTP as long as both the client and
the server know how to handle the data content. It is required for the client as well as the server to specify the
content type using appropriate MIME-type.
o HTTP is stateless: As mentioned above, HTTP is connectionless and it is a direct result of HTTP being a
stateless protocol. The server and client are aware of each other only during a current request. Afterwards,
both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can
retain information between different requests across the web pages.
7
HTTP Methods
• HTTP works as a Request – Response protocol:
• HTTP Request Methods: The HTTP Request is a class of HTTP style requests with HTTP methods,
request URL, headers and body contents. Following are the HTTPRequest methods defined in HTTP:
o The GET method appends user given information with the page request as encoded data.
Page name and values are separated by ‘?’.
o This URL will appear in the address bar and is used to retrieve requested resource from
the server.
GET /RegisterDao.jsp?name1=value1&name2=value2
9
HTTP Methods (…)
2. HEAD method:
o HEAD method will allow client to retrieve only the header information i.e. content-type
or content-length etc.
o It is similar to GET method, except the web server will only return status line and header
section only.
o It’s received response is cacheable i.e. it can be used to update previously cached
information of the same response.
3. POST method:
o Unlike GET method, user information will not be appended with the requested URL
instead it will be send as a separate message through socket.
POST/RegisterDao.jsp HTTP/1.1
Host: www. javatpoint.com
name1=value1&name2=value2
11
4. PUT method:
HTTP Methods (…)
o This method allows to store an entity / enclosed info in the body in the specific request-
URI (Uniform Resource Identifier)
o If the request-URI in the URL, does not refer to an existing resource then the web server
will create a new resource with the specified name.
5. DELETE method:
o Used to delete all expired or unused resources by specifying the resource name to the
request URI.
5. OPTIONS method:
o Performs a message loop-back test along the path to the target resource
• HTTP Response Method: After receiving and interpreting a request message, a server responds with
an HTTP response message which provides following meta information about HTTPresponse:
o General-header: Informs the server about further access to the resources requested by the request
URL.
o Response-header: Allow the web server to pass additional information of the response to the
client.
13
Sample HTTP Request and Response
200 OK
Date: Wed, 07 Jan 2018 19:55:50 GMT
GET /FirstServletProject/jsps/hello.jsp HTTP/1.1 Server: Apache-Coyote/1.1
Host: localhost:8080 Content-Length: 309
Cache-Control: no-cache Content-Type: text/html;charset=US-ASCII
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head> <meta http-equiv="Content-Type"
content="text/html; charset=US-ASCII">
<title>Hello</title>
</head>
<body>
<h2>Hi There!</h2> <br>
<h3>Date=Wed Aug 07 12:57:55 PDT 2013 </h3>
</body>
</html> 14
HTTP Get Vs Post Method
GET POST
1) In case of Get request, only limited amount of In case of post request, large amount of data can
data can be sent because data is sent in header. be sent because data is sent in body.
2) Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.
15
Common Gateway Interface (CGI)
• Web sites were comprised of only static HTML documents stored in server’s file system.
• There were no way for the client to transmit information to the server in order to customize the
information returned or store data in a database.
• In combination with HTML forms, CGI (Common Gateway Interface) provided a mechanism for true
two-way interaction between the client and the server. CGI programs are written using Perl, C,
Python, PHP etc.
• CGI is the first technique for creating dynamic content. With CGI, server passes the request to the
CGI program and output is sent back to client.
16
CGI Scripts
• Common Gateway Interface (CGI) is a standard environment for web servers to interface with
executable programs installed on a server that generate web pages dynamically.
Limitations:
o It creates a new process to run CGI program
o It requires time and significant server resources
• Number of request cannot be handled
• When multiple users make a request to the same servlet then all requests will be processed by the container by
creating multiple threads for the same servlet. In order to deal with these servlet programming, we must import
javax.servlet.* and javax.servlet.http.* into our java program.
22
Why Servlet?
• What can servlets do?
o Dynamically build and return HTML file based on the nature of the client request
o Process user input passed by an HTML form and return an appropriate response
o Facilitate communication between groups of people by publishing information submitted by many clients
o Provide user authentication and other security mechanisms
o Interact with server resources such as databases, other applications, and network files to return useful
information to the client.
o Process input from many clients for interaction among peers for applications such as multiplayer games.
o Allow the server to communicate with a client applet via a custom protocol and keep the connection open
throughout the conversation
o Automatically attach Web page design elements, such as headers or footers, to all pages returned by the
server.
o Forward requests from one server to another for load balancing purposes
o Partition a single logical service across servers or between servlets in order to most efficiently process the
task
o Virtually any other way you can imagine to enhance or extend a server 21
Advantages of using Servlet
• Servlets have many advantages over computing technologies:
o Capable of running in-process :
– Run in the same process space as server
– Unlike other server side programming methods like CGI that requires program to run as separate processes when
servicing client requests. Using servlets, all client requests can be serviced by separate threads within the server’s
process space.
o Compiled: Servlets are compiled into Java byte-codes and byte-code compilation improves performance through
compile-time code optimization.
o Crash resistant:
– Servlets are written in Java and executed by a Java Virtual Machine (JVM).
– JVM does not allow servlets direct access to memory locations, thereby eliminating crashes that result from invalid
memory accesses.
– JVM also verifies that compiled Java class files are valid and do not perform illegal operations.
– Thus, a poorly written or malicious servlet cannot crash the server.
o Cross-platform: Write once, run anywhere.
o Cross-server: Servlets can run on virtually every popular Web server in use today. Major software vendors currently
provide native support for servlets within their products. For those servers that do not currently offer native servlet
support, third party add-ons allow these servers to load and run servlets. 22
Advantages of using Servlet (…)
• Servlets have many advantages over computing technologies: (…)
o Durable: Servlets are durable objects that remain in memory until specifically instructed to be destroyed.
o Dynamically loadable across the network:
– Similar to applets, servlets can be dynamically loaded either locally or from across the network.
– Dynamic loading ensures that unused servlets do not consume precious server resources. i.e. load when needed
– Fortunately, for performance reasons it is also possible to instruct the server to load a servlet at start-up rather than
when it is first invoked.
o Extensible:
– Since servlets are written in Java, there is a wealth of third-party support for writing and extending them.
o Multithreaded: Allow client requests to be handled by separate threads within a single process.
o Protocol independent: Allows a servlet to be specially constructed to support HTTP, FTP, SMTP etc.
o Secure:
– Invalid memory access calls and strong typing violations are avoided.
– Use server’s Security Manager for the optimization and enforcement of specific security policies
– It can access to all information contained in each client request
o Written in Java (all advantages of Java and Java Virtual Machine)
25
Why Servlets better than CGI?
• Though less choice of language for Servlet development where as CGI can be built using any language,
Servlets is better than CGI for following reasons:
o Servlets improved performance as they run in the same process space as the server and are loaded
only once, where as CGI must create a new process to service each request.
o Servlets can be run on different servers and platforms without modification. They are portable.
26
Life cycle of a Servlet
• A servlet life cycle can be defined as the entire process from its creation till the destruction.
1. Initialization phase:
o Represents creation and initialization of the resources that the server may need in response to
service requests.
o Represents all the interactions carried out along with the requests that are handled by the servlet
until it is destroyed
o Service() method of Servlet interface is invoked once for every request and has the responsibility to
generate response for the received request.
o Based on the received HTML request method, it will call other methods i.e. doGet(), doPost() etc to
process request.
3. Destruction Phase:
o Method destroy() of Servlet interface is called to terminate servlet execution and its removal from
the container.
4. Finally, servlet is garbage collected by the garbage collector of the JVM. 26
Life cycle of a Servlet (…)
• Servlet Methods:
27
Life Cycle of Servlet (…)
• The init() method:
❑ The servlet is normally created when a user first invokes a URL corresponding to the servlet, for
the first time.
❑However, the servlet is loaded on the server when a Servlet container maps the user request to the
servlet.
❑ When a user invokes a servlet, a single instance of each servlet gets created.
❑ With each subsequentuser request, a new thread is handed off to doGet or doPost as appropriate.
❑The init() method simply creates or loads some data that will be used throughout the life of the
servlet.
❑ So, it is used for one-time initializations, just as with the init method of applets. 28
Life Cycle of Servlet (…)
• The init() method: (…)
public void init(ServletConfig config) throws ServletException {
//Initialization code
}
❑ The init() method is called only once by the servlet container throughout the life of a servlet.
o The init() method does not return within a fix time set by the web server.
o It throws a ServletException
❑ Parameters:
o The init() method takes a ServletConfig object that contains the initialization parameters and servlet's configuration
and throws a ServletException if an exception has occurred.
31
Life Cycle of Servlet (…)
• The service() method:
❑ The service() method is the main method to perform the actual task.
❑ The servlet container (i.e. web server) calls the service() method:
❑ Each time the server receives a request for a servlet, the server spawns a new thread and calls
service.
❑The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods as appropriate.
e.g. If the incoming HTTP request is of type GET then service() method will call doGet() method.
32
Life Cycle of Servlet (…)
• The service() method: (…)
public void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {…
}
❑ The servlet services the client's request with the help of two objects :
javax.servlet.ServletRequest and javax.servlet.ServletResponse
o The status code of the response always should be set for a servlet that throws or sends an error.
❑Parameters - The service() method takes the ServletRequest object that contains the client's
request and the object ServletResponse contains the servlet's response.
❑ A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
….
}
34
Life Cycle of Servlet (…)
• The doPost() method:
❑ A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
…
}
35
Life Cycle of Servlet (…)
• The destroy() method:
❑ The destroy() method is called only once at the end of the life cycle of aservlet.
❑ This method gives your servlet a chance to close database connections, halt background threads,
write cookie lists or hit counts to disk, and perform other such clean-up activities.
❑ After the destroy() method is called, the servlet object is marked for garbage collection.
36
Methods Details
Life Cycle of Servlet (…)
38
How does the JVM execute a Servlet compared with a
regular Java class?
39
Web Container / Servlet Container / Servlet Engine
• Web Container is a part of Web Server that interacts with Servlets and manages Servlet’s lifecycle.
• Request from web client i.e. browser are not directly transferred to the servlet which is requested.
• Web server (e.g.Apache) on receiving request, will transfer the request to the web container (e.g.
Tomcat) in which the requested servlet is deployed.
• Container then gives the HTTP request and response object to the Servlet and it is the container that
calls Servlet’s methods (doGet() or doPost()).
40
Working of Web Containers
1. User clicks a link that has a URL to a servlet instead of a static page.
2. The container “sees” that the request is for a servlet, so the container creates two objects:
o HttpServletResponse
o HttpServletRequest
3. The container finds the correct servlet based on the URL in the request, creates or allocates a thread for that
request, and passes the request and response objects to the servlet thread.
4. The container calls the servlet’s service() method. Depending on the type of request, the service() method
calls either the doGet() or doPost() method. For the previous flow, we assume the request was an HTTP GET.
5. doGet() method generates the dynamic page and stuffs the page into the response object. Container still have
reference to the response object.
6. The thread completes, the container converts the response into HTTP response and send it back to the client.
It then deletes the request and response object. 41
42
Web Containers (…)
• If no Servlet or Containers are available, then to have server-side support for web application
using java we have to do :
43
Web Containers (…)
• If no Servlet or Containers are available, then to have server-side support for web application
using java we have to do :
o Socket Programming: Create a socket connection with the server and create a listener for the
socket.
NOTE: Servlets are helpful because they manage the socket handling for us but the drawback is we
need a container (such as Tomcat) to run our servlets on.
44
Web Containers (…)
• Advantages of using Container:
❑ Communications Support:
❑ No need to worry about writing code for threading, security and networking.
❑No need to worry about the APIs used between as the container knows the protocol used
between the web server and itself.
❑ Multithreading Support : Creates a new Java thread for every servlet request it receives
❑Declarative Security : Allows to use XML deployment descriptor to configure security without
having to hard code it into servlet class code.
45
Steps to create Servlet
▪ There are given 6 steps to create a servlet example. These steps are required for all the servers.
51
Steps to create Servlet (…)
▪ Step 2: Create a Servlet
The HttpServlet class is widely used to create the servlet because it provides methods to handle http
requests such as doGet(), doPost, doHead() etc.
In our example we have created a servlet that extends the HttpServlet class. In that example, we are
inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that
get request is the default request.
52
53
54
55
56
57
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html"); //Setting the content type
PrintWriter out = response.getWriter(); //Get the stream to write the data
// Writing html in the stream
out.println("<html><head><title>Welcome Page</title></head><body><h1>Welcome to my
Servlet</h1></body><html>");
out.close(); // Closing the stream
}
} 55
Steps to create Servlet (…)
▪ Step 3: Compile the Servlet
To compile the Servlet, jar files needs to be loaded. Different servers provide different jar files:
Jar File Server
servlet-api.jar Apache Tomcat
weblogic.jar Weblogic
javaee.jar Glassfish
javaee.jar JBoss
56
61
62
63
64
Steps to create Servlet (…)
▪ Step 4: Create the deployment descriptor (web.xml file) What is Deployment Descriptor?
o The deployment descriptor is an XML file that provides configuration and deployment
information for the Web components that comprise a Web application.
o The web.xml file must reside in the WEB-INF directory under the context of the hierarchy of
directories that exist for a Web application.
o This file is updated by the Application Server Toolkit. Application Server’s functions use
information in this file during the configuration and deployment phases of Web application
development.
o Web Container gets the information about the servlet to be invoked from this xml file.
o The web container uses the Parser to get the information from the web.xml file. There are many
xml parsers such as SAX, DOM and Pull. 61
Steps to create Servlet (…)
• A Servlet has three names: What is Deployment Descriptor? (…)
❑ File path name:
o Full path name contains a path to an actual class file i.e. Location of the class on the server + class
name ( and the package name that defines part of directory structure)
e.g. classes/NewUser/Register.class
❑ Deployment name:
o Anyone who deploys Servlet may give it a special name called deployment name.
o It is a simple secret internal name that doesn’t have to be same as the class or file name.
e.g. It can be the same as the servlet class name (NewUser.Register) or the relative path to the class
file(classes/NewUser/Register.class) or can be completely different name like EnrollServlet.
66
Steps to create Servlet (…)
• A Servlet has three names: (…) What is Deployment Descriptor? (…)
o This name is coded into HTML that is when the user clicks a link that’s supposed to go to that servlet,
this public URL name is sent to the server in the HTTP request.
❑ Improves security: Hiding real name and path to the servlet from the client.
67
Steps to create Servlet (…)
What is Deployment Descriptor? (…)
• Deployment Descriptor (DD) is an XML document that is created when Servlets are deployed in the
web Container.
o It is also used to customize other aspects of web application like security roles, error pages, tag
libraries, initial configuration information.
o If it is full J2EE server, then we can also declare about the specific enterprise javabeans that will
be used.
• Thus, DD provides a “declarative” mechanism for customizing web applications without touching
source code. 64
Steps to create Servlet (…)
• Mapping URL to the Servlet in DD (web.xml file):
What is Deployment Descriptor? (…)
• Two XML elements are used to map URLs to the servlet
71
72
73
74
75
76
Write a simple servlet program for Login Page
LoginPage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form method="post" action = "./MyLoginServlet">
<table>
<tr><td colspan=2><center>Log In</center></td></tr>
<tr><td>User Name </td><td><input type = "text" name="txtUserName"/></td></tr>
<tr><td>Password </td><td><input type = "password" name="txtPwd"/></td></tr>
<tr><td colspan = 2><center><input type = "submit" id="btSubmit" value = "SUBMIT"/></center></td></tr>
</table>
</form>
</body>
</html> 73
import java.io.IOException; MyLoginServlet.java
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/MyLoginServlet")
public class MyLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyLoginServlet() {}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("txtUserName");
String pwd = request.getParameter("txtPwd");
if(name.equals("admin") && pwd.equals("admin") )
{
out.println("<html><head><title>Welcome Page</title></head><body><h1>Welcome
"+name+"</h1></body></html>");
}
else
{
out.println("Invalid Login");
}}} 74
Output Program
79
Model View Controller
▪ Model View Controller (MVC): MVC takes the business logic out of the servlet, and puts it in a
“Model” – a reusable plain old Java class. (Model = business data + logic → operate on data)
80
ServletRequest interface
▪ ServletRequest object is used to provide following information about client request:
o Content type
o Content length
o Parameter names and values
o Header information
o Attributes etc.
public String[] getParameterValues(String name) Returns an array of String containing all values of
given parameter name. It is mainly used to obtain
values of a Multi select list box
java.util.Enumeration getParameterNames() Returns an enumeration of all of the request
parameter names
81
ServletRequest interface (…)
▪ ServletRequest Methods are: (…)
public int getContentLength() Returns the size of the request entity data, or -1 if
not known.
public String getCharacterEncoding() Returns the character set encoding for the input of
this request.
public String getContentType() Returns the Internet Media Type of the request entity
data, or null if not known.
public ServletInputStream getInputStream() Returns an input stream for reading binary data in
throws IOException the request body.
public abstract String getServerName() Returns the host name of the server that received the
request.
public int getServerPort() Returns the port number on which this request was
received.
82
ServletRequest interface (…)
▪ ServletRequest Methods are: (…)
1. The client’s platform and browser info
String client = request.getHeader(“User-Agent”);
2. The cookies associated with this request
Cookie[] cookie = request.getCookies();
3. The session associated with this client
HttpSession session = request.getSession();
4. The HTTP Method of the request
String usedMethod = request.getMethod();
5. An input stream from the request
InputStream input = request.getInputStream();
6. Port associated with the request
getServerPort(): Returns server port number to which the request was actually sent.
getLocalPort(): Returns port no. where the incoming request actually ended up. (i.e. Though the requests are sent to
single server listening port , server finds a different local port for each thread so that multiple requests can he handled.
getRemotePort(): Returns the client’s port number. 83
ServletResponse interface
▪ Servlet provides two important interfaces ServletResponse and HttpServletResponse to assist in
sending response to client.
void setBufferSize(int size) Sets the preferred buffer size for the body of the response
void setContentLength(int len) Sets the length of the content body in the response. In HTTP
servlets, this method sets the HTTP Content-Length header
void setContentType(String type) Sets the content type of the response being sent to the client before
sending the respond.
84
ServletResponse interface (…)
▪ Few methods of HttpServletResponse are:
void sendRedirect(String location) Sends a temporary redirect response to the client using the specified
redirect location URL and clears the buffer
String getHeader(String name) Gets the value of the response header with the given name.
void setStatus(int sc) Sets the status code for this response
void sendError(int sc, String msg) Sends an error response to the client using the specified status and
clears the buffer
85
ServletResponse interface (…)
▪ Two choices for output:
❑ Bytes : ServletOutputStream
2. OutputStream: Used for writing anything else i.e. pdf, jar etc.
<display-name>ContentTypeExample</display-name>
<welcome-file-list>
<welcome-file>FirstPage.html</welcome-file>
</welcome-file-list>
</web-app>
89
Write a program to read a pdf file (…)
90
ServletResponse interface (…)
▪ Methods to deal with response headers:
1. addHeader(headerName,headerValue):
o Adds a new header and value to the Response.
o Adds an additional value to an existing header.
response.addHeader(“Logged-in-page”, “firstPage”);
response.setHeader(“Logged-in-page”, “loginPage”);
response.setHeader(“content-type”, “text/html”); //response.setContentType(“text/html”);
response.addIntHeader(“Loged-in-page”, 1); 91
Self Exercise
1. Write a Servlet displaying the current date and time.
2. Write a web application using servlet to find the sum of all digits of the given number.
4. Write a servlet which accept two numbers using POST methods and display the maximum
of them.
5. Display an HTML page that list different hobbies. Display the user selected hobbies using
servlet.
6. Write servlet which displayed following information of client: a) Client Browser b) Client
IP address c) Client Port No. d) Server Port No. e) Local Port No. f) Method used by client
for form submission g) Query String names and values 88
Self Exercise (…)
Write servlet which displayed following information of client: a) Client Browser b) Client IP
address c) Client Port No. d) Server Port No. e) Local Port No. f) Method used by client for form
submission g) Query String names and values
<html>
<head><meta charset="ISO-8859-1">
<title>Client Server Info</title>
</head>
<body>
<form method="get" action="./SixthProg">
Enter No1: <input type="text" name="txtInputNo1"/></br>
Enter No2: <input type="text" name="txtInputNo2"/></br>
<input type="Submit" value="SUBMIT"/>
</form>
</body></html> 89
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("</br>Client Browser : "+request.getHeader("User-Agent"));
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if(ipAddress == null){
ipAddress = request.getRemoteAddr(); }
out.println("</br>Client IP Address : "+ipAddress);
out.println("</br>Client Port No : "+request.getRemotePort());
out.println("</br>Server Port No : "+request.getServerPort());
out.println("</br>Local Port No : "+request.getLocalPort());
out.println("</br>Request Method : "+request.getMethod());
out.println("</br>Query String : "+request.getQueryString());
90
}
OUTPUT:
95
Browser Header Details
Servlet inherit lifecycle methods
97
Servlet inherit lifecycle methods (…)
93 98
ServletConfig interface
▪ Each servlet has an object associated with it, called ServletConfig.
▪ Use to pass deploy-time information or initial configuration information to the servlet that we don’t
want to hardcode into the servlet.
▪ To specify initialization parameters, the web-app element must contain a <servlet> element with three
sub-elements:
o <servlet-name>
o <servlet-class>
94
o <init-param>
ServletConfig interface (…)
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>MyDemo</display-name>
<servlet>
<servlet-name>ServletN</servlet-name>
<servlet-class>ServletN</servlet-class>
<init-param> ServletConfig parameters
<param-name>Param1</param-name>
<param-value>ParamValue1</param-value>
</init-param>
</servlet>
<servlet-mapping> @WebInitParam(name = <name>, value = <value>,description = <value>)
<servlet-name>ServletN</servlet-name>
<url-pattern>/ServletN</url-pattern>
</servlet-mapping>
</web-app> 95
ServletConfig interface (…)
The servlet init parameters are read only ONCE—when the Container initializes the servlet
1. Container reads the Deployment Descriptor for this servlet, including the servlet init parameters
(<init-param>).
10
ServletConfig interface (…)
The servlet init parameters are read only ONCE—when the Container initializes the servlet
1
2
3
6
5
10
ServletConfig interface (…)
▪ public ServletConfig getServletConfig(): This method of Servlet interface creates ServletConfig
object.
String getInitParameter(String name) Returns the parameter value for the specified
parameter name.
10
ServletContext interface
▪ An object of ServletContext is created by the web container at the time of deploying the project.
▪ Use it to access web app parameters, get server info, including the name and version of the Container, and the
version of the API that’s supported.
▪ This object is used to provide context information from the web.xml file.
▪ If any information need to be provided to all servlets, then such parameters need to be mentioned in web.xml
file using <context-param> element.
o A ServletConfig object contains a ServletContext object, which specifies the parameters for a particular
servlet while the ServletContext object specifies the parameters for an entire Web application. 99
ServletContext interface (…)
▪ Uses of ServletContext:.
o The object of ServletContext provides an interface between the container and servlet.
o The ServletContext object can be used to get configuration information from the web.xml file.
o The ServletContext object can be used to set, get or remove attribute from the web.xmlfile.
100
ServletContext interface (…)
→ One per web app
→ Declared in <context-param> tag
→ Retrieved:
getServletContext().getInitParameter(“Par
ameterName”)
void setAttribute(String name,Object object) Sets the given object in the application scope.
Object getAttribute(String name) Returns the attribute for the specified name.
void removeAttribute(String name) Removes the attribute with the given name from the servlet
context.
String getMimeType(String file) Returns the MIME type of the specified file or null if the MIME
type is not known
RequestDispatcher getRequestDispatcher(String path) Returns a RequestDispatcher object that acts as a wrapper for
the resource located at the given path
String getServerInfo() Returns the name and version of the servlet container on which
the servlet is running.
107
Web.xml
@WebServlet("/MyFirstPage")
public class MyFirstPage extends HttpServlet {
Output
114
Attributes in Servlet
▪ Attribute: It is the entity/parameter that can be transferred or sent from one resource to another. (Resource can
be Servlet or JSP)
▪ An attribute is an object set into one of the three servlet API objects – ServletContext, HttpServletRequest (or
ServletRequest) , or HttpSession.
▪ It is an object that can be set, get or removed from one of the following scopes: Request scope, Session scope,
and Application scope (Context)
▪ The three attribute scopes are handled by the ServletContext, ServletRequest and HttpSession interfaces.
116
Attributes vs Parameters
⚫
Redirecting request
sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it
may be servlet, jsp or html file.
o Absolute: sendRedirect(http://www.mysite.com/mypages/pages/page1.html);
⚫ It works at client side because it uses the URL bar of the browser to make another request. So, it can work
111
inside and outside the server.
Redirecting request (…)
119
Redirecting request (…)
120
Example for redirecting request
SearchPage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="./Search">
<input type="text" name="txtSearch"/>
<input type="submit" value="Google
Search"/>
</form>
</body>
</html> 114
Example for redirecting request (…)
Search.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Search")
public class Search extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse
rep) throws ServletException,IOException{
String str= req.getParameter("txtSearch");
rep.sendRedirect("https://www.google.co.in/#q="+str);
}} 115
Dispatching request
123
Dispatching request (…)
⚫ RequestDispatcher interface provides the facility of dispatching the request to another resource like html, servlet
or jsp.
⚫ This interface can also be used to include the content of another resource also. (Servlet collaboration)
o From ServletRequest:
RequestDispatcher rd= request.getRequestDispatcher(“result.jsp”); //Relative path with or without slash
o From ServletContext:
RequestDispatcher rd = getServletContext().getRequestDispatcher(“/result.jsp”); //Path must have forward slash
124
Dispatching request (…)
⚫ There are two methods defined in the RequestDispatcher interface.
1. public void forward(ServletRequest request,ServletResponse response)throws
ServletException, java.io.IOException: Forwards a request from a servlet to another resource
(servlet, JSP file, or HTML file) on theserver.
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
2. public void include(ServletRequest request,ServletResponse response)throws
ServletException, java.io.IOException: Includes the content of a resource (servlet, JSPpage,
or HTML file) in the response.
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.include(request, response);
125
Dispatching request (…)
126
Dispatching request (…)
Response of the second servlet is not sent to client directly, it is instead merged with
the response of the first servlet and then this merged message is sent to client
127
Example for dispatching request
HomePage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form method="post" action = "./Servlet1">
<table>
<tr><td colspan=2><center>Log In</center></td></tr>
<tr><td>User Name </td><td><input type = "text" name="txtUserName"/></td></tr>
<tr><td>Password </td><td><input type = "password" name="txtPwd"/></td></tr>
<tr><td colspan = 2><center><input type = "submit" id="btSubmit" value =
"SUBMIT"/></center></td></tr>
</table>
</form>
</body>
</html>
128
Example for dispatching request (…)
ValidateInput.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
ValidateInput.java (…)
if(name.equals("Admin") && pwd.equals("Admin") )
{
RequestDispatcher rd = request.getRequestDispatcher("Servlet2");
rd.forward(request, response);
}
else
{
out.println("<h3><font color='red'>Invalid username or password</font></h3>");
RequestDispatcher rd = request.getRequestDispatcher("/HomePage.html");
rd.include(request, response);
}
}
}
123
Example for dispatching request (…)
WelcomePage.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
} 124
Example for dispatching request (…) web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>MyApp</display-name>
<welcome-file-list><welcome-file>HomePage.html</welcome-file></welcome-file-list>
<servlet>
<servlet-name>ValidateInput</servlet-name>
<servlet-class>ValidateInput</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomePage</servlet-name>
<servlet-class>WelcomePage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidateInput</servlet-name>
<url-pattern>/Servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomePage</servlet-name>
<url-pattern>/Servlet2</url-pattern>
</servlet-mapping>
125
</web-app>
Example for dispatching request (…)
ValidateInput
(Servlet1)
Yes Is No
valid?
Forward to
Include Error
HomePage.html WelcomePage
in the html file
(Servlet2)
133
Web App Structure
• A Web app is structured as a directory consistingof:
❑ Myapp/
❑ Myapp/WEB-INF
❑ Myapp/WEB-INF/classes
❑ Myapp/WEB-INF/lib
134
Issues with Multithreading
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{ Output on first run
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(“Test Context Attribute </br>”);
getServletContext().setAttribute(“foo”, “22”);
getServletContext().setAttribute(“bar”, “42”);
out.println(getServletContext().getAttribute(“foo”));
Output on second run
out.print(getServletContext().getAttribute(“bar”));
142
Issues with Multithreading (…)
143
Issues with Multithreading (…)
How do we make context attributes thread safe?
• Idea 2: SingleThreadModel
» What to Use????
{
getServletContext().setAttribute(“foo”, “22”);
getServletContext().setAttribute(“bar”, “42”);
out.println(getServletContext().getAttribute(“foo”));
out.print(getServletContext().getAttribute(“bar”));
}
} 145
Issues with Multithreading (…)
Are session attributes thread safe?
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(“Test Session Attribute </br>”);
HttpSession session = request.getSession();
synchronized(session)
{
session.setAttribute(“foo”, “22”);
session.setAttribute(“bar”, “42”);
out.println(session.getAttribute(“foo”));
out.print(session.getAttribute(“bar”));
}
} 146
Questions
Questions
Questions
Questions
Questions
Questions
Answer Key
1->BC
2->ADF
3->ABD
4->B
5->DF
6->BCD
7->D
8->C
9->D
10->D
11->C
12->AE
13->D
14->
15->AC