MBA 2009-11 Notes Servlets

  • Upload
    arsam

  • View
    219

  • Download
    0

Embed Size (px)

Citation preview

  • 8/8/2019 MBA 2009-11 Notes Servlets

    1/19

    Web Application :

    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.

    o A web application relieves the developer of the responsibility of building a client

    for a specific type of computer or a specific operating system. Since the client

    runs in a web browser, the user could be using an IBM-compatible or a Mac.They can be running Windows XP or Windows Vista. They can even be using

    Internet Explorer or Firefox, though some applications require a specific web

    browser.

    o Web applications commonly use a combination of server-side script (ASP, PHP,

    etc) and client-side script (HTML, Javascript, etc.) to develop the application. The

    client-side script deals with the presentation of the information while the server-side script deals with all the hard stuff like storing and retrieving the information.

    o In the Java 2 platform, web components provide the dynamic extension

    capabilities for a web server. Web components are either Java servlets, JSP pages,or web service endpoints. The interaction between a web client and a web

    application is illustrated in Figure 3-1. The client sends an HTTP request to the

    web server. A web server that implements Java Servlet and JavaServer Pages

    technology converts the request into an HTTPServletRequest object. This objectis delivered to a web component, which can interact with JavaBeans components

    or a database to generate dynamic content. The web component can then generate

    anHTTPServletResponse or it can pass the request to another web component.Eventually a web component generates a HTTPServletResponse object. The web

    server converts this object to an HTTP response and returns it to the client.

    1

    http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebApp.html#wp227454http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebApp.html#wp227454
  • 8/8/2019 MBA 2009-11 Notes Servlets

    2/19

    Enterprise Applications :

    o An Enterprise application runs in a Special container called enterprise container

    which have special features like JMS,Transaction etc. These containers can also

    handles web application. Eg : Bea Weblogic, IBM WebSphere, Oracle IAS,

    JBOSS etc.

    o Web application runs in web container. This containers won't have specialfetaures 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 adesktop application if more than a browser is used.

    HTTP request and response :

    o HTTP : a protocol to transfer hypertext requests and information between

    servers and browsers.

    2

  • 8/8/2019 MBA 2009-11 Notes Servlets

    3/19

    o Request and response both have two parts header and body.

    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 The http methods are different from the java methods.

    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.

    o GET : used for resource retrieval from the server.

    Body is empty

    Header contains only the url of resource and may contain some

    supplementary data using attributes.

    Get is used when :

    Client is requesting resource to be returned.

    Client does not wish to upload or provide additional parameters.

    o POST : is used to pass info to the server.

    It is used over get when :

    Large amounts of data to transmit

    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 users chosen language may decide to abort the download.

    o PUT: used to place resources on the server, upload a file.

    3

  • 8/8/2019 MBA 2009-11 Notes Servlets

    4/19

    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.

    o DELETE: used to remove a resource from the server.

    Like PUT poses serious security considerations.

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

    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 tofacilitate SSL-encrypted communication (HTTPS) through an unencrypted

    HTTPproxy.[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 sent in an Http response, and is used by client to

    determine what to do next.

    Each status code is 3 digit number, out of which first digit indicates code

    class and last two the exact status type.

    Informational 1XX: reported during connection with the client, indicates

    server is continuing to process request.

    Successful 2XX : successful completion of request

    Redirection 3XX : indicates requested resource has been moved to

    somewhere else

    Client error 4XX : when an error on clients part occurs, such as spelling

    mistake in typing url, or user is unauthorized for this resource etc

    4

    http://en.wikipedia.org/wiki/URLhttp://en.wikipedia.org/wiki/URLhttp://en.wikipedia.org/wiki/Tunneling_protocolhttp://en.wikipedia.org/wiki/Tunneling_protocolhttp://en.wikipedia.org/wiki/Transport_Layer_Securityhttp://en.wikipedia.org/wiki/Proxy_serverhttp://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#cite_note-0http://en.wikipedia.org/wiki/URLhttp://en.wikipedia.org/wiki/Tunneling_protocolhttp://en.wikipedia.org/wiki/Transport_Layer_Securityhttp://en.wikipedia.org/wiki/Proxy_serverhttp://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#cite_note-0
  • 8/8/2019 MBA 2009-11 Notes Servlets

    5/19

  • 8/8/2019 MBA 2009-11 Notes Servlets

    6/19

    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.

    o Difference between application server and web server:

    (1) Webserver serves pages for viewing in web browser, application server

    provides exposes businness logic for client applications through various

    protocols

    (2) Webserver exclusively handles http requests.application server serves

    bussiness logic to application programs through any number of protocols.

    (3) Webserver delegation model is fairly simple,when the request comes

    into the webserver,it simply passes the request to the program best able to

    handle it(Server side program). It may not support transactions and

    database connection pooling. To process a request, a Web server mayrespond with a static HTML page or image, send a redirect, or delegate the

    dynamic response generation to some other program such as CGI scripts, JSPs

    (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side

    JavaScripts, or some other server-side technology.

    (4) Application server is more capable of dynamic behaviour than

    webserver. We can also configure application server to work as awebserver.Simply applic! ation server is a superset of webserver.

    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.

    An Application Server is used to run business logic or dynamically

    generated presentation code. It can either be .NET based or J2EE based

    (BEA WebLogic Server, IBM WebSphere, JBoss).

    A J2EE application server runs servlets and JSPs (infact a part of the appserver 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.

    o Apache Tomcat Installation and applcn deployment :

    6

  • 8/8/2019 MBA 2009-11 Notes Servlets

    7/19

    Run the Apache Tomcat windows installer.

    Set the JAVA_HOME AND CATALINA_HOME variables to the base

    path of jdk and tomcat

    Deploy the web-applcn in the webapps folder. Within it place a WEB-INFfolder containing classes & lib folder along with web.xml deployment

    descriptor.

    Make sure the classpath has entries for servlet-api.jar,applcn-name/web-

    inf/classes/ dir where your class files will be located.

    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 :

    All public directories in a WAR map to a URL path accessible to clients.

    The /WEB-INF directory is private in nature, accessible only to the web

    container in which applcn is deployed, other applcns cannot access it.

    Outside the applcn archive, the directory appears to not exist.

    Other sub directories that must be present in WEB-INF are

    /WEB-INF/classes

    /WEB-INF/lib : contains JAR files which are used to bundle

    multiple java classes into one. Jar files used for distribution of java

    classes along with its metadata.

    7

  • 8/8/2019 MBA 2009-11 Notes Servlets

    8/19

    /WEB-INF/tags

    Deployment Descriptor :

    URL to servlet mappings are made in the DD.

    Web.xml is the file required to be present in every application

    archive.

    DD provides metadata information about the application and WAR

    to the container.

    o Servlets :

    Is the heart of every java web application.

    They are normally responsible for all the processing in the applcn, ex .updating d/b, mediating a complete request and servicing appropriate

    response etc .

    It is just a special type of class implementing the javax.servlet.Servlet

    interface.

    It is converted into a bytecode before being put into the WEB-INF/classes.

    Small applcn may have only one servlet doing everything but generally u

    have one servlet for one purpose.

    There are five stages in servlet life cycle

    Servlet loading :

    instantiation : container does not know what the servlet does, so it

    use the default no-arg constructor to create the servlet instance.

    Therefore if you override the servlet const make sure there is one

    const with no-args and public. Otherwise error 4XX/fail to load.

    Initialization: to communicate the config info to the servlet, every

    servlet must provide implementation to the void

    init(ServletConfig) method. Initialization info is present in the

    servletconfig object. Init is a method of the servlet interface.

    o The genericServlet defines this method and in addition

    provides a no-arg init method. This init() method is called

    8

  • 8/8/2019 MBA 2009-11 Notes Servlets

    9/19

    after the genericservlets implmn of the init(ServletConfig)

    completes.

    Request servicing : void service(ServletRequest,ServletResponse)

    is called when a request(of any type and any protocol) is made to

    the servlet.

    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.

    o also the Httpservlet class defines concrete protected

    methods for each of the HTTP methods.

    o The service method scans the header of the HTTP request

    and delegates the processing to the appropriate method.

    doGet for GET method, doHead for HEAD method etc.

    o A ServletException(or UnavailableException) may be

    thrown if the servlet is unavailable to service a given

    request.

    o If the failure is temporary, 503 error is reported else if

    failure is permanent 404 status code showing the

    component does not exist.

    Destroy : we can never really be sure when a servlet instance has

    been destroyed and garbage collected but we can be sure when a

    destroy method is called.

    o

    Called after the container removes the servlet from service.

    o Destroy indicates that the servlet will be removed from the

    service method but does not indicate that it will be garbage

    collected immediately.

    o it takes no args and throws no exception

    9

  • 8/8/2019 MBA 2009-11 Notes Servlets

    10/19

    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 neverbe called.

    If u do not override any of the doXxx methods, will cause HTTP

    error (for HTTP/1.0 400 Bad Request and HTTP/1.1 405

    Method not allowed status code)

    o ServletContext :

    Is an interface to whom the implementation is given by the container.

    When you instantiate a Servletcontext object, it is actually the object of

    the subclass that implements the ServletContext interface.

    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.

    The ServletContext instance is first created by the container when the

    applcn is first started and the container configures it using the data in the

    DD.

    It has methods :

    RequestDispatcher getRequestDispatcher(String path)

    RequestDispatcher getNamedDispatcher(String name)

    The most imp contextual information vital to ServletContext are :

    Initialization parameters

    Context Attributes

    Resources : static content files that are a part of the web

    application Ex: gif, jpeg, html etc. can be accessed using

    getResource(), getResourceAsStream() etc.

    10

  • 8/8/2019 MBA 2009-11 Notes Servlets

    11/19

    Context attributes :

    When you want variables to accessible throughout the applcn, you

    must use these. These are static variables.

    These attributes/variables can be accessed by any component in theapplcn but is NOT accessible by other applcns.

    They are stored in the applications context.

    Methods of the javax.servlet.ServletContext interface

    o Object getAttribute(String identifier_name)

    o Enumeration getAttributeNames()

    o

    void removeAttribute(String name)

    o void setAttribute(String name, Object value)

    Context initialization parameters :

    Declared in WEB.xml in a element under the

    root

    o String getInitParameter(String name) : gives the value of

    the init parameter identified by the name.

    The context initialization parameters and the context attributes differ in the

    way :

    They are declared. Cip : and ca through

    setAttribute() and getAttribute() fns

    The cip are read only once they are intialized.

    o ServletConfig :

    Is per Servlet and deals with the initialization of each servlet.

    Every Servlet has its config object.

    Again, this is also an interface like the servlet context.

    The context for a servlet is stored as an instance variable in the this config

    object.

    11

  • 8/8/2019 MBA 2009-11 Notes Servlets

    12/19

    Servlet initialization parameters:

    Declared in the WEB.xml in the element in the

    But the method name are same as the context initializationparameters:

    o String getInitParameter(String name)

    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.

    o ServletRequest : interface has flg methods

    Request scoped methods :

    Same as context attributes setAttribute(String name, Object

    value), getAttribute(String name) etc.Attributes exist only within

    the web container, most suitable form of storage is an object. But

    parameters received from client are always read only and strings.

    Request parameters:

    String[] getParameterValues(String name) : used for list etc

    String getParameter(String name)

    Enumeration getParameterNames()

    Map getParameterMap()

    12

  • 8/8/2019 MBA 2009-11 Notes Servlets

    13/19

    s

    Difference between request.getParameter() and request.getAttribute() :

    request.getParameter() :

    o It retrieves the value of the parameter passed by the client

    through a html component or the url.

    o Its value is read only and is of string type.

    request.getAttribute() :

    o It retrieves the value of the attribute set in the request on

    the server side, client is unaware of this.

    o Its value is modifiable and of object type.

    o HttpServletRequest : an interface extending the SevletRequest interface provides

    additional methods for getting the request headers, protocol data and resource

    paths,url etc and also security related methods.

    o ServletResponse :

    Provides o/p streams to components such as servlets to write data back to

    the client.

    Response methods :

    getOutputStream() : used to return binary data to the client.

    Returns ServletOutputStream object.

    getWriter() : returns writer to send character data to the client.

    Returns PrintWriter object.

    resetBuffer(), flushBuffer(), setBufferSize() etc.

    Response protocol and transmission data

    void setCharacterEncoding(String enc)

    String getCharacterEncoding()

    void setContentType(String typ)

    13

  • 8/8/2019 MBA 2009-11 Notes Servlets

    14/19

    And so on

    o HttpServletResponse :

    Adds support for Http headers and status codes and ability to support

    cookies

    Status code : can be set using

    void setStatus(int code)

    void sendRedirect(String path) : an indirect way of setting status

    codes.

    o RequestDispatcher:

    It is a way for communicating between two components / resources withinthe same application using the container. components can be html/jsp or

    servlet

    The rd object is obtained from the container. It is interface to whom a

    concrete implementation is provide by the container when the

    getRD/getNamedDispatcher method is invoked

    Three ways to achieve an RD object :

    1.

    Using context object : can be relative to the context root(starting with

    the forward slash), passing a String containing the path of the other

    resources, path is relative to the root of the ServletContext.

    RequestDispatcher

    rd=request.getRequestDispatcher(/secondServlet);

    rd.forward(request, response);

    2.

    Using request object : the path can be relative to the current

    servlet(omitting the / forward slash) or the context root(starting with

    the forward slash)

    14

  • 8/8/2019 MBA 2009-11 Notes Servlets

    15/19

    RequestDispatcher

    rd=getServletContext( ).getRequestDispatcher(servlet/secondServlet);

    rd.forward(request, response);

    3.

    By using the getNameDispatcher( ) of the javax.Servlet.ServletContext

    interface.

    RequestDispatcher

    rd=getServletContext( ).getNameDispatcher(secondServlet);

    Rd.forward(request, response);

    RD mechanism can be used to delegate execution to both static and

    dynamic resources.

    The rd mechanism :

    Calling resource A invokes applcns ServletContext instance to

    obtain a suitable RD

    The ServletContext uses the containers interface to create new

    appropriate RD

    The ServletContext returns the newly created RD

    The calling resource A calls the required method on the RD

    returned in the above step

    The RD uses the containers interface to invoke the target resource

    B

    The target resource B returns control to the RD

    In case of include, the control returns to A. For forward, the

    method returns but A is not permitted to make any further changes

    to the response

    RD methods:

    15

  • 8/8/2019 MBA 2009-11 Notes Servlets

    16/19

    void forward(ServletRequest request, ServletResponse response)

    o Once this method is called, control is completely delegated

    to the second resource and the first resource completely

    gives up its right to change any data in the response.

    o This method should be called before any response is

    committed or before any calls to getWriter()/

    getOutputstream() are made else IllegalStateException is

    thrown.

    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.

    o You may need it for for redirecting from outdated/old url to

    newly updated urlss,

    void include(ServletRequest request, ServletResponse response)

    o causes runtime evaluation of the second resource to be

    included in the response created by the first

    o once second resource returns from its evaluation, the

    execution begins from the from the same position in thefirst resource and execution of the rest of the first resource

    continues.

    o Included servlet may not make any changes to the response.

    o Can be invoked unconditionally, even after the response

    has been committed

    o If the included resource, closes the output stream, the

    first resource cannot write further to the response object.

    When a request is forwarded to 2nd resource, the response must be sent,

    committed and the stream closed before the fwd method returns. Response

    should not be committed before fwd is called. So generally, its the last

    line of the service method.

    16

  • 8/8/2019 MBA 2009-11 Notes Servlets

    17/19

    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.

    Sendredirect( ) : javax.Servlet.Http.HttpServletResponse interface

    -response.sendRedirect( ) works on the browser.

    - Sends a temporary redirect response to the client using the

    specified redirect location URL.

    - The SendRedirect( ) allows you to redirect trip to the Client.

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

    - If the specified location is relative , this method converts it into an

    absolute URL before redirecting.

    -The sendRedirect( ) will come to the Client and go back to the server,..i.e. URL appending will happen.

    response. sendRedirect( absolute path);

    Absolutepath other than application , relative path - same application.

    Difference between RequestDispatcher forward and Response

    sendRedirect

    When you invoke a forward request, the request is sent to another

    resource on the server, without the client being informed that a

    different resource is going to process the request. This process

    occurs completely within the web container.

    17

  • 8/8/2019 MBA 2009-11 Notes Servlets

    18/19

    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.

    This extra round trip makes redirect slower than forward.

    o Session Management :

    Http is an stateless protocol as opposed to FTP which is a stateful

    protocol, which means it doesnt maintain a persistent connection with the

    client. Connections are formed only for the duration of the

    request/response

    So to associate multiple requests of a single user with each other, A thirdscope is required which is session scope. It uses a session id which is

    unique serial number associated with every client

    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

    Cookies : store small amount of temporary data on the client

    machine.

    o Cookie required for storage is automatically created by the

    container during the first request made by the client.

    o Disadvantage is that cookies may be disabled.

    URL Rewriting :

    o Puts the jsessionid in the request uri.

    18

  • 8/8/2019 MBA 2009-11 Notes Servlets

    19/19

    o The container inserts the jsessionid in every encoded url.

    o When the container returns a resource as a response to the

    first request, the container encodes all the urls in that page

    to contain the jsession id.

    o Then when the client clicks on any hyperlink in that page a

    new request is sent to the client and the jsessionid is

    appended to the url.

    o The container can automatically encode urlss to contain

    jsessionid but in order for this process to work, all urls

    must be passed through the

    HttpServletResponse.encodeURL(String)

    o Disadavantages :

    is that if link in the chain breaks the next request

    will be a new session.

    And if the client types the url manually.

    SSL session : ssl provides inherent session tracking.

    o Session lifecycle : has 3 stages

    Session is new when client does not know anything about it

    Client joins a new session when it returns tracking data to server

    indicating it has been correctly established.

    Session is explicitly invalidated or the session time out period expires

    causing session to be destroyed.

    Since http is a stateless protocol, it has a time out period rather than a

    close command or so.

    Session has methods like getAttribute(String name),setAttribute(Stringname, Object value) etc

    The 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