0% found this document useful (0 votes)
10 views

Unit 3

Adavance java - be - unit 3

Uploaded by

istra0802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit 3

Adavance java - be - unit 3

Uploaded by

istra0802
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 146

ADVANCEDJAVA

B.E. – III, Sem. VI


Unit- 3
Web Programming
Introduction
• Internet (or The Web) is a massive distributed client/server information system as depicted below.

• 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.

• HTTP works as a request-response protocol between a client and server.

• 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

Protocol: Server: Port No.: (Optional) Path: Resource:


Tells the server Unique name of the 16 bit TCPport number is The path to the location The name of the
which physical server. used to identify server on the server, of the content being
communication This name maps to the application (80 –default) resource being requested. requested.
protocol will be unique IP address of e.g.
used numeric form: 80 – HTTP
xxxx.yyyy.zzzz.aaaa 23 – Telnet
21 – FTP
25 - SMTP

Parts of URL (Uniform Resource Locator)


5
Hyper Text Transfer Protocol (HTTP) (…)

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:

❑ Client Request is send using HTTPRequest

❑ Server Response is send using HTTP Response

• 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:

1. GET method: (default)

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.

o Max size of GET Request URL is 1024 characters.


8
HTTP Methods (…)
Sample HTTP GET Request Method: The query string (name/value pairs) is sent inside the URL of a GET
request:

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.

o More reliable way of passing web browser’s data to web server.


10
HTTP Methods (…)
• HTTP Request POST method: The query string (name/value pairs) is sent in HTTP message body for a POST
request:

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.

o Responses to this method is not cacheable.

5. OPTIONS method:

o To obtain information related to different communication protocols available on request


12
and response.
HTTP Methods (…)
7. TRACE method:

o Used to invoke a remote application layer associated with a request object.

o Performs a message loop-back test along the path to the target resource

8. CONNECT method: Establishes a tunnel to the server identified by a given URI.

• 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 Status-Line: Provides information related to protocol version and status code

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.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent.


Post request is non-idempotent.

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.

1. Client sends a request to server


2. Server starts a CGI script
3. Script computes a result for server and quits
4. Server returns response to client
5. Another client sends a request
6. Server starts the CGI script again etc. 17
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

1. Client sends a request to server concurrently.

2. Server starts a CGI script


3. Script computes a result for server and quits
4. Server returns response to client
5. Another client sends a request
6. Server starts the CGI script again etc. 18
Traditional vs JAMstack Workflow
Servlet
• A servlet is a server side platform independent, dynamic and multithread java program, which runs in the context
of server for extending the functionality of server.

• 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.

❑ javax.servlet.Servlet → is one of pre-defined top most interface, which contains


servlet’s life cycle methods.
❑javax.servlet.GenericServlet → It is one of the predefined abstract class which
implements javax.servlet.Servlet interface. This GenericServlet class is used for
developing protocol independent applications.
❑javax.servlet.http.HttpServlet → is sub class of GenericServlet used for
developing protocol dependent application [ HTTP protocol ]
21
Servlet (…)

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 CGI cannot share a single database connection across multiple requests.

o Servlets can be run on different servers and platforms without modification. They are portable.

o Servlets are more secure than CGI.

26
Life cycle of a Servlet
• A servlet life cycle can be defined as the entire process from its creation till the destruction.

• It follow a three-phase life cycle : Initialization, Service and Destruction.

1. Initialization phase:

o Represents creation and initialization of the resources that the server may need in response to
service requests.

o To perform this phase, init() method of javax.servlet.Servlet interface is implemented.


27
Life cycle of a Servlet (…)
2. Service Phase:

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 It takes two object parameters, javax.servlet.ServletRequest and javax.servlet.ServletResponse.

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 init method is called only once.

❑ 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.

❑ The servlet cannot be put into the service if

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:

– To handle requests coming from the client(browsers) and

– To write the formatted response back to the client.

❑ 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 They are passed by the servlet container.

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.

❑ The service() method throws ServletException and IOExceptions exception.


33
Life Cycle of Servlet (…)
• The doGet() method:

❑ 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.

public void destroy(){


//Finalization code
}

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.

❑ Lifecycle Management : Controls the life and death of servlets

❑ 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.

❑JSP Support : Translates JSP code into real Java Code

45
Steps to create Servlet
▪ There are given 6 steps to create a servlet example. These steps are required for all the servers.

▪ The servlet example can be created by three ways:

o By implementing Servlet interface, The mostly used approach is by extending


HttpServlet because it provides http request specific
o By inheriting GenericServlet class,
method such as doGet(), doPost(), doHead() etc.
o By inheriting HttpServlet class

▪ The steps are as follows:


1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet 43
Deployment Environment
48
49
50
Steps to create Servlet (…)
▪ Step 1: Create a directory structure
The directory structure defines that where to put the different types of files so that web container may get the
information and respond to the client.

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;

public class MyServlet extends HttpServlet {


public MyServlet() {
// Constructor code
}
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
}
} 54
import java.io.IOException; Content Type: It is a HTTP header that provides the
import java.io.PrintWriter; description about what are you sending to the browser.
import javax.servlet.ServletException; • text/html

import javax.servlet.annotation.WebServlet; • text/plain


• application/msword
import javax.servlet.http.HttpServlet;
• application/vnd.ms-excel
import javax.servlet.http.HttpServletRequest;
• application/jar
import javax.servlet.http.HttpServletResponse; • application/pdf
• application/octet-stream
public class MyServlet extends HttpServlet { • application/x-zip
public MyServlet() { • images/jpeg
// Constructor code • video/quicktime etc.

}
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 Name given by the original developer of the Servlet.

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? (…)

❑ Public URL name:

o This is the name known to the client.

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.

• Benefits from mapping Servlet names:


❑Improves app’s flexibility : Tracking down and changing client code that refers to old location of servlet
files reduced.

❑ 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 DD tells the Container how to run Servlets and JSP.

o It is used to map URLs to the servlet.

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

o <servlet> : maps internal name to the fully qualified class name

o <servlet-mapping> : maps internal name to the public URL name


<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<servlet>
<servlet-name>InternalName1</servlet-name>
<servlet-class>mysite.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InternalName1</servlet-name>
<url-pattern>/PublicURL</url-pattern>
</servlet-mapping>
</web-app> 65
web.xml file

<?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>MyServletProgram</display-name>
<welcome-file-list>
<welcome-file>MyServlet.java</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
70
Steps to create Servlet (…)
▪ Step 5: Start the server and deploy the project

▪ Step 6: Access 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

Positive Case Negative Case

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.

▪ ServletRequest Methods are:


public String getParameter(String name) Used to obtain the value of a parameter by name.

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.

▪ Few methods of ServletResponse are:


PrintWriter getWriter() Returns a PrintWriter object that can send character text to the
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 addCookie(Cookie cookie) Adds the specified cookie to the response.

void sendRedirect(String location) Sends a temporary redirect response to the client using the specified
redirect location URL and clears the buffer

int getStatus() Gets the current status code of this response

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:

❑ Character data : PrintWriter

❑ Bytes : ServletOutputStream

1. PrintWriter: Designed to handle character data.


To write text data to characterstream

PrintWriter writer = response.getWriter();


writer.println(“This is the example of PrintWriter stream</br>”);

2. OutputStream: Used for writing anything else i.e. pdf, jar etc.

ServletOutputStream out = response.getOutputStream();


out.writeln(aByteArray);
86
Write a program to read a pdf file FirstPage.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Content Type Example</title>
</head>
<body>
<form action = "./ContentType">Select content type: <br/>
<input type="radio" name="resource" value="pdf“ checked>PDF</input>
</br>
<input type="radio" name="resource" value="other">Other</input></br>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html> 83
Write a program to read a pdf file (…) doGet() from ContentType.java file
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String selected = request.getParameter("resource");
if(selected.equals("pdf")){
response.setContentType("application/pdf");
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/Sarvajanik College of
Engineering.pdf");
int read = 0;
byte[] bytes = new byte[1024];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
else
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("</br><h2>Requested resource not available currently...</h2>");
84
}}
Write a program to read a pdf file (…) web.xml file

<?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>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”);

2. setHeader(headerName,headerValue): Overwrites the existing given headerName with the latest


given headerValue.

response.setHeader(“Logged-in-page”, “loginPage”);
response.setHeader(“content-type”, “text/html”); //response.setContentType(“text/html”);

3. setIntHeader(headerName,headerIntValue): Replaces the headerValue for the given headerName


with the new integer value headerIntValue.

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.

3. Write a web application to compute area and perimeter of rectangle.

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.

▪ This object is created by the container and implements the javax.servlet.ServletConfiginterface.

▪ Use to pass deploy-time information or initial configuration information to the servlet that we don’t
want to hardcode into the servlet.

▪ Use it to access ServletContext

▪ Parameters are configured in the Deployment Descriptor (web.xml) file.

▪ 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>).

2. Container creates a new ServletConfig instance for this servlet


3. Container creates a name/value pair of Strings for each servlet init parameter. Assume we have
only one.

4. Container gives the ServletConfig references to the name/value init parameters.


5. Container creates a new instance of the servlet class.
6. Container calls the servlet’s init() method, passing in the reference to theServletConfig.

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.

▪ Methods of ServletConfig interface:

String getInitParameter(String name) Returns the parameter value for the specified
parameter name.

Enumeration getInitParameterNames() Returns an enumeration of all the initialization


parameter names.

String getServletName() Returns the name of the servlet.

ServletContext getServletContext() Returns an object of ServletContext.

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.

▪ There is one ServletContext object per web application.

▪ 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.

▪ ServletContext vs. ServletConfig:


o A ServletContext object is used to communicate with the Servlet container while ServletConfig, is passed to
the servlet by the container when the servlet is initialized.

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.

o The ServletContext object can be used to provide inter-application communication.

100
ServletContext interface (…)
→ One per web app
→ Declared in <context-param> tag
→ Retrieved:
getServletContext().getInitParameter(“Par
ameterName”)

→ One per servlet


→ Declared in <init-param> sub-tag of
<servlet> tag
→ Retrieved:
getServletConfig().getInitParameter(“Para
meterName”) 101
ServletContext interface (…)
▪ public ServletContext getServletContext(): Method of ServletConfig interface or Generic Servlet
class is used to return ServletContext object.

▪ Methods of ServletContext interface are:


String getInitParameter(String name) Returns the parameter value for the specified parameter name.
Enumeration getInitParameterNames() Returns the names of the context's initialization parameters.

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

<?xml version="1.0" encoding="UTF-8"?> <init-param>


<web-app <param-name>LastName</param-name>
xmlns:xsi="http://www.w3.org/2001/XMLSchema- <param-value>XYZ</param-value>
instance" xmlns="http://java.sun.com/xml/ns/javaee" </init-param>
xsi:schemaLocation="http://java.sun.com/xml/ns/javae </servlet>
e http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" <context-param>
id="WebApp_ID" version="3.0"> <param-name>ExampleName</param-name>
<display-name>MyDemo</display-name> <param-value>ServletConfigMethods</param-value>
<servlet> </context-param>
<servlet-name>MyFirstPage</servlet-name> <servlet-mapping>
<servlet-class>MyFirstPage</servlet-class> <servlet-name>MyFirstPage</servlet-name>
<init-param> <url-pattern>/MyFirstPage</url-pattern>
<param-name>Message</param-name> </servlet-mapping>
<param-value>Welcome</param-value> <session-config>
</init-param> <session-timeout>30</session-timeout>
<init-param> </session-config>
<param-name>FirstName</param-name> </web-app>
<param-value>ABC</param-value>
</init-param>
108
Web.xml

<?xml version="1.0" encoding="UTF-8"?> <init-param>


<web-app <param-name>LastName</param-name>
xmlns:xsi="http://www.w3.org/2001/XMLSchema- <param-value>XYZ</param-value>
instance" xmlns="http://java.sun.com/xml/ns/javaee" </init-param>
xsi:schemaLocation="http://java.sun.com/xml/ns/javae </servlet>
e http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" <context-param>
id="WebApp_ID" version="3.0"> <param-name>ExampleName</param-name>
<display-name>MyDemo</display-name> <param-value>ServletConfigMethods</param-value>
<servlet> </context-param>
<servlet-name>MyFirstPage</servlet-name> <servlet-mapping>
<servlet-class>MyFirstPage</servlet-class> <servlet-name>MyFirstPage</servlet-name>
<init-param> <url-pattern>/MyFirstPage</url-pattern>
<param-name>Message</param-name> </servlet-mapping>
<param-value>Welcome</param-value> <session-config>
</init-param> <session-timeout>30</session-timeout>
<init-param> </session-config>
<param-name>FirstName</param-name> </web-app>
<param-value>ABC</param-value>
</init-param>
ServletConfig parameters
109
Web.xml

<?xml version="1.0" encoding="UTF-8"?> <init-param>


<web-app <param-name>LastName</param-name>
xmlns:xsi="http://www.w3.org/2001/XMLSchema- <param-value>XYZ</param-value>
instance" xmlns="http://java.sun.com/xml/ns/javaee" </init-param>
xsi:schemaLocation="http://java.sun.com/xml/ns/javae </servlet>
e http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" <context-param>
id="WebApp_ID" version="3.0"> <param-name>ExampleName</param-name>
<display-name>MyDemo</display-name> <param-value>ServletConfigMethods</param-
<servlet> value>
<servlet-name>MyFirstPage</servlet-name> </context-param>
<servlet-class>MyFirstPage</servlet-class> <servlet-mapping>
<init-param> <servlet-name>MyFirstPage</servlet-name>
<param-name>Message</param-name> <url-pattern>/MyFirstPage</url-pattern>
<param-value>Welcome</param-value> </servlet-mapping>
</init-param> <session-config>
<init-param> <session-timeout>30</session-timeout>
<param-name>FirstName</param-name> </session-config>
<param-value>ABC</param-value> </web-app>
</init-param>
ServletContext parameters 105
MyFirstPage.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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("/MyFirstPage")
public class MyFirstPage extends HttpServlet {

private static final long serialVersionUID = 1L;


public MyFirstPage() {}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException


{
response.setContentType("text/html");
ServletConfig config = getServletConfig();
PrintWriter out = response.getWriter();
out.println("<b>ServletConfig method examples.....</b></br>"); 106
MyFirstPage.java (…)

out.println("Servlet Name : " +config.getServletName()+"</br>");


Enumeration<String> list = config.getInitParameterNames();
String str="";
while(list.hasMoreElements())
{
str=list.nextElement();
out.println(str+" : "+config.getInitParameter(str)+"</br>");
}

out.println("</br><b>ServletContext method examples....</b></br>");


ServletContext context = getServletContext();
out.println("Server Info : "+context.getServerInfo());
out.println("<br>Servlet Context : "+context.getInitParameter("ExampleName"));
context.setAttribute("Subject1","AJava");
out.println("</br>Attribute 1 added : "+context.getAttribute("Subject1"));
context.setAttribute("Subject2", ".Net");
out.println("</br>Attribute 2 added : "+context.getAttribute("Subject2"));
context.removeAttribute("Subject2"); 107
Context init parameter vs Config/servlet init parameter
MyFirstPage.java (…)

out.println("</br><font color = 'red'><b>After removal of attribute</b></font></br> Attribute 2 added :


"+context.getAttribute("Subject2"));
Enumeration<String> contextList = context.getInitParameterNames();
while(contextList.hasMoreElements())
{
str = contextList.nextElement();
out.println("</br>"+str+" : "+context.getInitParameter(str)+"</br>");
}
}
}

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.

▪ Attribute specific methods of ServletRequest, HttpSession and ServletContext interface


Enumeration getInitParameterNames() Returns the names of the context's initialization parameters.
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.
115
Attributes in Servlet (…)

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.

⚫ It accepts relative as well as absolute URL.

o Absolute: sendRedirect(http://www.mysite.com/mypages/pages/page1.html);

o Relative: Comes with or without slash

o e.g. i) sendRedirect(“pageDetails/page2.html”) : Container builds the following URL →


http://www.mysite.com/mypage/pages/pageDetails/page2.html

o ii) sendRedirect(“/pageDetails/page2.html”): Container builds the following URL →


http://www.mysite.com/mypage/pageDetails/page2.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)

⚫ getRequestDispatcher() method of ServletRequest interface is used to return RequestDispatcher object.

⚫ Syntax: public RequestDispatcher getRequestDispatcher(String resource);

⚫ Example: RequestDispatcher rd = request.getRequestDispatcher("servlet2");

⚫ Two ways to get RequestDispatcher:

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 (…)

Response of the second servlet is sent to client.

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;

public class ValidateInput extends HttpServlet {


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"); 122
Example for dispatching request (…)

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;

public class WelcomePage extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {
response.setContentType("text/html");
String name = request.getParameter("txtUserName");
PrintWriter out = response.getWriter();
out.println("<h2> Welcome "+name);
}

} 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/

o Contains HTML,CSS,GIF etc types of files

❑ Myapp/WEB-INF

o Contains the deployment descriptor web.xml file

❑ Myapp/WEB-INF/classes

o Contains servlet class files (in subdirectories corresponding to packagenames)

❑ Myapp/WEB-INF/lib

o Contains extra jar files.

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 1: Synchronizing the service method is a spectacularly BAD idea

• Idea 2: SingleThreadModel

• Idea 3: Synchronized Block

» What to Use????

public synchronized void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException
{
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”));
out.print(getServletContext().getAttribute(“bar”));
} 144
Issues with Multithreading (…)
How do we make context attributes thread safe?
Solution: You don’t need a lock on the servlet... you need the lock on thecontext!
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(“Test Context Attribute </br>”);
synchronized(getServletContext())

{
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

You might also like