MBA 2009-11 Notes Servlets
MBA 2009-11 Notes Servlets
o A web application is any application that uses a web browser as a client. The
application can be as simple as a message board or a guest sign-in book on a
website, or as complex as a word processor or a spreadsheet.
1
•
• Enterprise Applications :
o Web application runs in web container. This containers won't have special
fetaures like transaction, JMS etc. Eg : Tomcat,JavaWebserver
o There are broadly three tiers : the client tier (this tier runs a browser or some
other client Java code), the web tier(this tier runs your web server or Servlet
container that sends pages of html or other data to the first tier ) , the business
logic tier ( this tier runs your enterprise Java beans, your database connectivity
code etc. This tier communicates with the second tier)
o All together these tiers make up an 'enterprise application'; when you leave out the
third tier you have a 'web based' application. The first tier by itself is just a
desktop application if more than a browser is used.
o Header contains the http version, metadata about resource requested , size of
resource(in case of response which helps to determine time left to complete
download and % download completed)
o Body of a request is generally empty although some types of requests like POST
the body is not empty.
o Every user request may be for a different reason (request resource, upload file
etc ). This may be considered a distinct action and is called a method of data
transfer.
Body is empty
Header contains only the url of resource and may contain some
supplementary data using attributes.
• Hiding data (but hiding does not guarantee security. Use https for
security)
o HEAD: used when client may want all headers before the resource.
So that client browser could check if the length is too much and decide to
abandon download, or client might look at the language of the content and
if not in user’s chosen language may decide to abort the download.
3
Body of the put request would contain the data of resource being uploaded
and an extra header, the Request-URI header field, used to identify the
location on the server to which the resource is to be uploaded to.
PUT request differs from the POST in that it contains an extra header
Request-URI.
The uri path to the resource is given through the Request-URI header
field.
o TRACE
Echoes back the received request, so that a client can see what
intermediate servers are adding or changing in the request.
o OPTIONS
Returns the HTTP methods that the server supports for specified URL.
This can be used to check the functionality of a web server by requesting
'*' instead of a specific resource.
o CONNECT
Converts the request connection to a transparent TCP/IP tunnel, usually to
facilitate SSL-encrypted communication (HTTPS) through an unencrypted
HTTP proxy.[1]
o Status Codes: Http also gives some feedback as to how the request has been
processed. This feedback comes in the form of a status code.
Each status code is 3 digit number, out of which first digit indicates code
class and last two the exact status type.
Client error 4XX : when an error on client’s part occurs, such as spelling
mistake in typing url, or user is unauthorized for this resource etc
4
Server error 5XX : server fails to respond correctly coz of malfunction or
lack of resources or a permanent “service unavailable” problem.
Static resources such as text files, images, pdfs, supporting classes, private
config file and Jar libraries are not web components.
o Web container: is where all the Web applications are managed and executed.
All applications run in the same container, since it is not feasible in terms
of memory and resource usage to have separate container for very
application, what about components in one application which have the
same name as components in other application? Which to use ?
So when one class talks to other class in other application, the container
helps here.
5
Since container intervenes every call between components, the container
knows when a component from one application is calling other
application.
It can then act to execute the resource being called separately, process data
returned from it and send this back to calling component.
(1) Webserver serves pages for viewing in web browser, application server
provides exposes businness logic for client applications through various
protocols
Web Server serves static HTML pages or gifs, jpegs, etc., and can also
run code written in CGI, JSP etc. A Web server handles the HTTP
protocol. Eg of some web server are IIS or apache.
A J2EE application server runs servlets and JSPs (infact a part of the app
server called web container is responsible for running servlets and JSPs)
that are used to create HTML pages dynamically. In addition, J2EE
application server can run EJBs - which are used to execute business logic.
6
Run the Apache Tomcat windows installer.
When you create a new servlet, make its entry in the web.xml, compile it
like a normal java program, make sure class file resides in web-inf/classes
of your applcn and then execute it from the browser after starting the
tomcat server.
o WAR files :
is used to contain all the files for a single application, as well as the
metadata which describes the application to the container.
When deployed the WAR file is given a context root and at this point we
consider it to be the Web application.
In a complete J2EE applcn, many War files with other supporting Jar files
may be combined into a single enterprise application archive(EAR).
o WEB-INF directory :
• /WEB-INF/classes
7
• /WEB-INF/tags
Deployment Descriptor :
o Servlets :
They are normally responsible for all the processing in the applcn, ex .
updating d/b, mediating a complete request and servicing appropriate
response etc .
Small applcn may have only one servlet doing everything but generally u
have one servlet for one purpose.
• Servlet loading :
8
after the genericservlet’s implmn of the init(ServletConfig)
completes.
o But for HTTP based requests, the req can be any one of the
seven HTTP methods, therefore the HttpServlet class
implements the service method of the GenericServlet and
adds protected access to it.
o protected void
service(HttpServletRequest,HttpServletResponse) .
delegation of processing responsibility is passed from the
standard service method to this method.
9
• When you create your own HTTP servlet by extending from the
HttpServlet class, you must override atleast one of the doXxx
methods and not override any of the service methods. These are
guidelines laid down in the api & specs.
• If you override the service method, the doXxx methods will never
be called.
o ServletContext :
The implementation class will be specific to the vendor and its container.
Every web applcn will have only one of this. It is per application and
represents the whole application.
It has methods :
• Initialization parameters
• Context Attributes
10
Context attributes :
o Enumeration getAttributeNames()
The context initialization parameters and the context attributes differ in the
way :
o ServletConfig :
The context for a servlet is stored as an instance variable in the this config
object.
11
Servlet initialization parameters:
When a container receives a request, it wraps all data found in the request into an object and
provides an empty request object which we/compnonent may fill as we please. It then forwards
the request and response objects to the appropriate filter/jsp/servlet. Similarly, after we have filed
the response object and passed it back to the container, the container unwraps the encapsulated
response data, converts it back to the stream of HTTP data and sends it down the n/w.
Request parameters:
• Enumeration getParameterNames()
• Map getParameterMap()
12
s
• request.getParameter() :
• request.getAttribute() :
o ServletResponse :
the client.
Response methods :
• String getCharacterEncoding()
13
• And so on
o HttpServletResponse :
Adds support for Http headers and status codes and ability to support
cookies
o RequestDispatcher:
1.
RequestDispatcher
rd=request.getRequestDispatcher(“/secondServlet”);
rd.forward(request, response);
2.
14
RequestDispatcher
rd=getServletContext( ).getRequestDispatcher(“servlet/secondServlet”);
rd.forward(request, response);
3.
RequestDispatcher
rd=getServletContext( ).getNameDispatcher(“secondServlet”);
Rd.forward(request, response);
The rd mechanism :
RD methods:
15
• void forward(ServletRequest request, ServletResponse response)
o Req and res objects are the same in fwd. the servlet which
is going to fwd, even if makes any changes to the response
the res buffer is automatically uncommitted before fwding.
Also even though the control returns back to the first
servlet, it cannot modify the res coz it is already committed.
16
On the contrary, if include is used, the stream should be open when the
method returns so that further content can be written to the response.
-You can also redirect response to resource outside your web server like
gmail.com etc using the url http://www.gmail.com
-After executing the SendRedirect( ) the control will not return back to
same method.
-The Client receives a temporary response with the Http response code
302 indicating that temporarily the client is being redirected to the
specified location.
-The sendRedirect( ) will come to the Client and go back to the server,..
i.e. URL appending will happen.
17
• When a sendRedirect method is invoked, it causes the web
container to return to the browser indicating that a new URL
should be requested. Because the browser issues a completely new
request any objects/data that are stored as request attributes before
the redirect occurs will be lost.
o Session Management :
When a client contacts the server for the first time, it is said to join a new
session.
At this time the server/web container will establish a new session, with a
unique session id for communication with the client.
The server will send the jsessionid back to the client, which the client will
store for all future requests.
The next time client makes the request, client includes value of jsessionid
in the request data.
There are three ways the client can store the sessionid
• URL Rewriting :
18
o The container inserts the jsessionid in every encoded url.
o Disadavantages :
Since http is a stateless protocol, it has a time out period rather than a
close command or so.
The <session-config> element of the DD can be used to set the time out
period in minutes. The setMaxInactiveInterval method of HttpSession sets
the time out in secs. This method can be used to override the time out set
in DD. If the time out is –ve or 0, the time out is infinite I .e the session
will never time out.
19