MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

Embed Size (px)

Citation preview

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    1/80

    Basic Servlets

    Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    2/80

    Servlet

    2Web Programming

    Java programming language class used to extend thecapabilities of servers that host applications accessed via arequest-response programming model

    Java class that implements the Servlet interface andaccepts requests that can come from Java classes, Webclients, or other Servlets and generates responses

    Also called "HTTP Servlet"

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    3/80

    Servlet

    3Web Programming

    To start making servlets, you'll need to have knowledgeabout:

    Java programming

    Client-server concepts Basic HTML and HTTP

    To create a Servlet, you'll need to import in your javaprogram the standard extension classes in the packagesjavax.servlet and javax.servlet.http.

    javax.servlet contains the basic servlet framework

    javax.servlet.http is used as an extension of the Servlet frameworkfor Servlets that answer HTTP requests

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    4/80

    Servlet Architecture

    Overview

    4Web Programming

    Common Gateway Interface (CGI)

    One of the most common ways of adding functionality for a web

    server, prior to Servlets Provides the server an interface to an external program, allowing it

    to be called by the server to handle client requests

    Designed in such a way that each call for a CGI resource creates anew process on the server

    This approach imposed a heavy requirement on system resources, limiting thenumber of users that the application can handle at the same time.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    5/80

    Servlet Architecture

    Overview

    5Web Programming

    Servlets are designed to be able to bypass the CGI problemand provide developers a robust Java solution to creating

    applications for the Web. With servlets, there is only one process that handles ALL

    requests: the process required by the servlet container torun.

    Servlets are also loaded into memory only once: either the

    container loads them into memory on server startup, or thefirst time the servlet is required to service a client.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    6/80

    6Web Programming

    import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

    public class HelloServlet extends HttpServlet {public void doGet(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, IOException {

    //"request" is used for reading incoming HTTP headers// HTML form data (e.g. data the user entered and submitted)// and other data that can be inferred from the client request.

    // "response" is for specifying the HTTP response line and// headers(e.g. specifying the content type, setting cookies).// It also contains methods that allow the servlet to generate// responses for the client.

    PrintWriter out = response.getWriter();out.println(" Hello Page
    ");

    out.println("Hello World!");out.println("");

    //"out" for sending content to browser}

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    7/80

    Servlet First Look

    7Web Programming

    HelloServlet shows the structure of a basic servlet thathandles GET requests, as well as displaying the traditional'Hello World'.

    The first part is simply importing classes:import java.io.*;

    java.io (for PrintWriter, etc.)

    import javax.servlet.*;

    import javax.servlet.http.*;

    javax.servlet and javax.servlet.http are packages that provideinterfaces and classes for wrtiting servlets (for HttpServlet,HttpServletRequest and HttpServletResponse).

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    8/80

    Servlet First Look

    8Web Programming

    By extending HttpServlet, this class inherits methods thatare automatically called by the server depending on certainconditions.

    public class HelloServlet extends HttpServlet {

    doGet method is inherited and overriden

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException { HttpServletRequest object: provides access to all information regarding the

    client's request (HTTP request headers, the HTTP request method that theyused, etc.).

    HttpServletResponse object: contains all the necessary methods needed bydevelopers to produce a response that will be sent back to the client (methodsto set the HTTP response headers, to declare the MIME type of the response,to retrieve instances of Java I/O classes that we can directly use to produceoutput).

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    9/80

    Servlet First Look

    9Web Programming

    Aside from the comments, there are only several lines thatwe use to display "Hello World!"

    PrintWriter out = response.getWriter();

    out.println(" Hello Page
    ");

    out.println("Hello World!");

    out.println("");

    PrintWriter is an object that lets us output text to the client browser.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    10/80

    Servlet First Look

    10Web Programming

    Output of HelloServlet

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    11/80

    Testing HelloServlet

    11Web Programming

    At this point we need to be able to display the output ofHelloServlet.

    To initially abstract the details of servlet deployment andconfiguration, we will be making use of the automated toolsprovided by IDEs

    Sun Studio Enterprise 8

    The IDE we will use.

    Available for free for members of the Sun Developer Network.

    Has complete support for the servlet and JSP specifications, as wellas a host of additional features.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    12/80

    Testing HelloServlet

    12Web Programming

    First, we need to create a new web application project:

    To do this select New->Project in the menubar.

    In the screen that appears next, select the Web category.

    On the right, choose New Web Application. The next screen will prompt you for details about the project:

    For HelloServlet, our first test servlet, let's make use of"FirstServletProject" as our project name, and make use of defaultvalues for the other fields.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    13/80

    Testing HelloServlet

    13Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    14/80

    Testing HelloServlet

    14Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    15/80

    Testing HelloServlet

    15Web Programming

    To add our servlet to the application:

    Right click on Source Packages, select New->Servlet.

    If Servlet does not appear in the New context menu, select New->File/Folder instead. In the next screen, select the Web category,then Servlet.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    16/80

    Testing HelloServlet

    16Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    17/80

    Testing HelloServlet

    17Web Programming

    The IDE will then launch a series of screens which will askfor details about the servlet to be created.

    In the first screen, name the servlet FirstServlet. Under packagename, use jedi.servlet. (see next slide)

    In the screen that follows, leave the default values untouched. Then,click the Finish button.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    18/80

    Testing HelloServlet

    18Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    19/80

    Testing HelloServlet

    19Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    20/80

    Testing HelloServlet

    20Web Programming

    The IDE has created and partially implemented for us amethod named processRequest.

    ProcessRequest

    Simply a method that will be called by both doGet and doPost.

    Its content forms the basis of the functionality of our servlet.

    First, remove all contents of the processRequest method. Then,copy / paste the contents of the doGet method from the code listingfor the test servlet into it. (see next slide)

    To run, press Shift + F6. The IDE will then package, deploy,

    and invoke the servlet automatically for us, producing theoutput.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    21/80

    Testing HelloServlet

    21Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    22/80

    Servlet Lifecycle

    22Web Programming

    A servlet is managed through a well-defined lifecycledescribed in the servlet specification.

    The servlet lifecycle describes how a servlet is loaded,instantiated, initialized, services requests, destroyed andfinally garbage collected

    The life cycle of a servlet is controlled by the container inwhich the servlet has been deployed.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    23/80

    Servlet Lifecycle

    23Web Programming

    The servlet life cycle allows servlet engines to address boththe performance and resource problems of CGI and thesecurity concerns of low-level server API programming.

    A servlet engine may execute all its servlets in a single Java virtual

    machine (JVM): Because they are in the same JVM, servlets can efficiently share data with each

    other, yet they are prevented by the Java language from accessing one another'sprivate data.

    Servlets may also be allowed to persist between requests as object instances,taking up far less memory than full-fledged processes.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    24/80

    Servlet Lifecycle

    24Web Programming

    The major events in a servlet's life:

    Instantiation

    Initialization

    Service Destruction

    Garbage Collection

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    25/80

    Servlet Lifecycle

    25Web Programming

    Instantiation

    The servlet class is loaded into memory, and an instance is createdby the servlet container.

    By default, a servlet container practices what is called lazy loading.

    A servlet class is loaded into memory, instantiated, and initialized only after arequest has been made for it.

    Advantage: makes for a faster startup time for the application.

    Disadvantage: there is a little bit of overhead associated for the first call to eachservlet.

    A servlet goes through the instantiation phase only once per lifetime. The relevant method that the container will call at this stage will be

    the servlet's no-argument constructor.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    26/80

    Servlet Lifecycle

    26Web Programming

    Initialization

    The servlet is primed for use in the application.

    A servlet also goes through this stage only once.

    It is only after this phase that our object instance starts to be called aservlet.

    The method that is called by the container at this point is the init()method.

    public void init(ServletConfig config)

    ServletConfig object: contains the servlet's configuration information, as well asprovides a way for the servlet to access application-wide information andfacilities.

    Any configuration or initialization code should be placed in the init method.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    27/80

    Servlet Lifecycle

    27Web Programming

    (Initialization continued)

    After initialization, the servlet is ready to handle client requests.

    This method can only be called again when the server reloads theservlet . The server cannot reload a servlet until after the server has

    destroyed the servlet by calling the destroy method.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    28/80

    Servlet Lifecycle

    28Web Programming

    Service

    The phase that a servlet is in for the bulk of its lifetime.

    The servlet can be repeatedly called by the container to provide itsfunctionality.

    The method invoked by the servlet container during this phase isthe service() method.

    public void service(ServletRequest req, ServletResponse res)

    ServletRequest and ServletResponse objects: provides methods to extractinformation from the user's request and methods to generate the response.

    One important thing to note is that the servlet container makes these repeatedcalls to the service method using separate threads. That is, mostly there is onlyone active servlet instance taking up space in memory, handling multiplerequests. That is one advantage of a Java servlet. That is also one of thereasons why a servlet (and its service method) should always be designed tobe thread-safe.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    29/80

    Servlet Lifecycle

    29Web Programming

    (Service continued)

    For HTTP-specific servlets (servlets extending HttpServlet),developers should not override the service method directly. Instead,developers should override any of the following methods:

    public void doGet(HttpServletRequest req, HttpServletResponse res)

    public void doPost(HttpServletRequest req, HttpServletResponse res)

    public void doPut(HttpServletRequest req, HttpServletResponse res)

    public void doTrace(HttpServletRequest req, HttpServletResponse res)

    Each of these methods correspond to a specific HTTP method (GET, POST, ...).

    Since most HTTP calls that developers concern themselves with are either GETor POST method calls, servlets can implement only doGet, doPost, or both.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    30/80

    Servlet Lifecycle

    30Web Programming

    Destruction

    When a servlet is to be removed from a container's management, itis said to be in its destruction phase.

    There are times when a servlet container will run out of memory, or detect that

    the amount of free memory it has is within a certain threshold. When thishappens, the container will attempt to free up memory by destroying one or moreservlet instances. What servlet is removed is determined by the servlet containerand is not something a developer has direct control over.

    A container will also free up a servlet instance as part of its shutdown process.

    The method called by the container before this is accomplished isthe destroy() method.

    Servlet should be coded to explicitly free up resources that it handles, such asdatabase connections, etc.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    31/80

    Servlet Lifecycle

    31Web Programming

    Garbage Collection

    This phase in the servlet lifecycle is equivalent to that in any otherJava object.

    Occurs just before an object instance is removed from memory.

    Developers have no direct control as to when this will occur.

    The object method called in this phase is the finalize() method.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    32/80

    Review

    32Web Programming

    The main purpose of a servlet is to provide dynamic contentto the user.

    By definition, dynamic content is content that changes inresponse to various conditions. Examples of which are the

    particulars of a user request, time of day, etc.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    33/80

    Handling Requests and

    Responses

    33Web Programming

    To give the servlet access to the particulars of a user'srequest, it is provided an instance of a ServletRequestobject that encapsulates those details.

    HTTP-based servlets are given a subclass calledHTTPServletRequest, that provides additional methods forretrieving HTTP-specific info, such as cookie information,header details, etc.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    34/80

    Handling Requests and

    Responses

    34Web Programming

    Form Data and Parameters

    Retrieving Info from the Request URL

    Header Information Output Generation

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    35/80

    Form Data and Parameters

    35Web Programming

    request.getParameter

    request.getParameterValues

    request.getParameterNames

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    36/80

    request.getParameter

    36Web Programming

    One of the most often encountered scenarios requiringdynamic content is when we want our application to respondto user data as presented in a form.

    Given the form above which takes in the user's name, we want to beable to produce a response customized to that user's name.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    37/80

    37Web Programming

    Halloa!

    Enter user name:

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    38/80

    request.getParameter

    38Web Programming

    For this and other similar scenarios, Java provides thegetParameter method in the HttpServletRequest object.

    public String getParameter(String parameterName)

    This method takes in the name of the parameter we wish to retrieve

    and returns the String value of that parameter. Now, let's create the code that takes in the user's name and

    outputs a simple greeting, and the HTML used to display theform.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    39/80

    39Web Programming

    public class GetParameterServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    // retrieve the value supplied by the user

    String userName = request.getParameter("userName");

    // retrieve the PrintWriter object and use it to output the greeting

    PrintWriter out = response.getWriter();

    out.println("");

    out.println("HELLO AND WELCOME, " + userName + "!");

    out.println("");

    out.close();

    }

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    40/80

    request.getParameter

    40Web Programming

    If we were to supply "JEDI" as the value for the form wecreated, the following result would be generated:

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    41/80

    request.getParameterValues

    41Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    42/80

    42Web Programming

    Choice selection

    What sports activities do you perform?

    Biking

    Table Tennis

    Swimming

    Basketball

    Others

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    43/80

    request.getParameterValues

    43Web Programming

    There are times when we need to retrieve data from a formwith multiple elements of the same name. In this case, usingthe getParameter method will return only the value of thefirst element with the given name. To retrieve all of the

    values, we use the getParameterValues method:public String[] getParameterValues(String parameterName)

    Also takes in the name of the parameter whose values we wish toretrieve.

    Returns a String array.

    Sample code and HTML (see next slides)

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    44/80

    44

    Web Programming

    public class GetParameterValuesServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response) throws ServletExceptionm IOException{

    String paramValues[] = request.getParameterValues("sports");

    StringBuffer myResponse = new StringBuffer();

    PrintWriter out = response.getWriter();

    out.println("Your choices");

    out.println("Your choices were : ");

    for (int i = 0; i < paramValues.length; i++) {

    out.println("
    ");

    out.println(paramValues[i]);

    }

    }

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    45/80

    request.getParameterValues

    45

    Web Programming

    If the entries "Biking", "Table Tennis", and "Swimming" areto be chosen, the output would be:

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    46/80

    request.getParameterNames

    46

    Web Programming

    There are times when we want our servlet to be aware ofthe name of one or more of the parameters within the formwithout having to hardcode them into the servlet. In thiscase, we can use the getParameterNames method:

    public Enumeration getParameterNames() The Enumeration object that this method returns contains all of the

    names of the parameters embedded in the user's request.

    Retrieving Info from the

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    47/80

    Retrieving Info from theRequest URL

    47

    Web Programming

    A request URL is composed of the following parts:

    http://[host]:[port]/[requestPath]?[queryString]

    To retrieve the curent values for each part from the user'srequest, call on methods in the HttpServletRequest object:

    Host request.getServerName()

    Port request.getServerPort()

    Request Path divided into 2 logical components in Java:

    Context the context of the web application. Can be retrieved by invokingrequest.getContextPath().

    Path info the rest of the request after the context name. Can be retrieved byinvoking request.getPathInfo().

    Query String request.getQueryString()

    Retrieving Info from the

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    48/80

    Retrieving Info from theRequest URL

    48

    Web Programming

    So, with a request URL of:

    http://www.myjedi.net:8080/HelloApp/greetUser?name=Jedi

    The following table presents the results yielded if we call onthe aforementioned methods:

    request.getServerName() www.myjedi.net

    request.getServerPort() 8080

    request.getContextPath() HelloApp

    request.getPathInfo() greetUser

    request.getQueryString() name=Jedi

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    49/80

    Header Information

    49

    Web Programming

    Can be retrieved from within the servlet by calling on thefollowing methods in HttpServletRequest:

    getHeader(String name)

    Returns the value of the specified header as a String; null, if it does not exist.

    getHeaders(String name) Returns all values for the specified header as an Enumeration object.

    getHeaderNames()

    Returns as an Enumeration object the names of all headers included in the HTTPrequest.

    getIntHeader(String name) Returns the value of the specified header as an int; -1, if it does not exist.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    50/80

    Header Information

    50

    Web Programming

    (Methods in HttpServletRequest continued)

    getDateHeader(String name)

    Returns the value of the specified header as a long value that represents a Dateobject; -1, if it does not exist.

    Throws an IllegalArgumentException if the header cannot be converted to aDate.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    51/80

    Output Generation

    51

    Web Programming

    In all the previous examples, we are able to generatedynamic output for the user by using methods exposed inthe HttpServletResponse object.

    So far, we have been making use mostly of the getWriter method.

    getWriter returns a PrintWriter object associated with our response to the user.

    Can you still recall HelloServlet? (see next slide)

    import java.io.*;import javax servlet *;

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    52/80

    52Web Programming

    import javax.servlet. ;import javax.servlet.http.*;

    public class HelloServlet extends HttpServlet {public void doGet(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, IOException {

    //"request" is used for reading incoming HTTP headers// HTML form data (e.g. data the user entered and submitted)// and other data that can be inferred from the client request.

    // "response" is for specifying the HTTP response line and// headers(e.g. specifying the content type, setting cookies).// It also contains methods that allow the servlet to generate// responses for the client.

    PrintWriter out = response.getWriter();out.println(" Hello Page
    ");out.println("Hello World!");

    out.println("");

    //"out" for sending content to browser}

    }

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    53/80

    Output Generation

    53Web Programming

    Other notable methods in the HttpServletResponse objectare:

    SetContentType

    Informs the client's browser of the MIME type of the output it is about to receive.

    Limited to text outputs: JPEG, PDF, DOC, XLS, etc.

    getOutputStream

    Retrieves an instance of the OutputStream object associated with our responseto the user.

    Using this OutputStream, we can then use standard Java I/O objects andmethods to produce all kinds of output.

    public JPEGOutputServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) {

    // define a byte array to hold data

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    54/80

    54Web Programming

    // define a byte array to hold databyte bufferArray[] = new byte[1024];

    // retrieve the ServletContext which we will use to retrieve the resourceServletContext ctxt = getServletContext();

    // inform the browser that the resource we are sending is a GIF fileresponse.setContentType("image/gif");

    // retrieve the output stream we will use to produce responseServletOutputStream os = response.getOutputStream();

    // retrieve the resource as an input streamInputStream is = ctxt.getResource("/WEB-INF/images/logo.gif").openStream();

    // read the contents of the resource and write it afterwards into the outputstreamint read = is.read(bufferArray);while (read != -1) {

    os.write(bufferArray);read = is.read(bufferArray);

    }// close the streams usedis.close();os.close();

    }}

    Configuration Packaging

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    55/80

    Configuration, Packaging,and Deployment

    55Web Programming

    In all the examples we have done so far, we have used thetools inherent in the Enterprise IDE to abstract the details ofweb application configuration, packaging, and deployment.

    We will take a look at those details now.

    Web Application

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    56/80

    Web ApplicationConfiguration

    56Web Programming

    The servlet specification defines an XML file named web.xmlthat acts as a configuration file for our web applications. Thisfile is also called the deployment descriptor.

    We will use our FirstServlet example as our starting point inexploring web.xml.

    NOTE: The web.xml for Enterprise web application projects can befound by expanding the Configuration Files tab in the project view.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    57/80

    57Web Programming

    FirstServletjedi.servlet.FirstServlet

    FirstServlet/FirstServlet

    30

    index.jsp

    b l

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    58/80

    web.xml

    58Web Programming

    Serves as both the root element of the configuration file as well asdeclaring the necessary info for the servlet container to recognizethe file as a valid deployment descriptor file.

    Each instance defines a servlet to be used by the application.

    Child nodes:

    A logical name supplied by the developer which will be usedfor all future references to this servlet.

    The fully qualified class name of the servlet. (Optional) Having an entry and value for this element tells

    the container that the servlet should be instantiated and initialized oncontainer/application startup, bypassing the normal lazy loading rule. The valuefor this element is a number which dictates the order of its loading compared toother servlets.

    b l

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    59/80

    web.xml

    59Web Programming

    Each instance defines a mapping to a servlet.

    Child nodes:

    the logical name of the servlet to be mapped. Must be defined

    previously in the descriptor file. the URL pattern to which this servlet will be mapped. Having a

    value of /* will make all requests to your application redirected to your servlet.

    Take note that all servlet definitions must first be supplied beforeadding any servlet mappings.

    b l

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    60/80

    web.xml

    60Web Programming

    Defines configuration details for session management.

    Defines a web component that will be automatically loaded if the

    user enters a request for the application without specifying aparticular resource.

    More than one file can be specified but the first one visible to theweb container will be loaded.

    Packaging the Web

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    61/80

    Packaging the WebApplication

    61Web Programming

    Our application can be deployed to a server by making useof what is called a WAR file.

    WAR files are the same as JARs: they contain Java application code

    compressed using the ZIP format.

    Informally, WAR stands for Web Archive.

    Contains HTML, images, other static content, plus JSPs

    Contains meta-information about your application (optional)

    All contents of this folder cannot be seen from the web browser

    Contains class files of Java classes created for this application (optional)

    Contains JAR files of any third-party libraries used by your app (optional)

    XML file storing the configuration entries for your application

    Generating WAR Files

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    62/80

    Generating WAR Files

    62Web Programming

    To produce the WAR file containing our web applicationfrom an existing project in Sun Studio Enterprise 8:

    Right click on the project name in the Project view, and select BuildProject. The IDE will then proceed to package your application.

    Generating WAR Files

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    63/80

    Generating WAR Files

    63Web Programming

    (WAR file... continued)

    The IDE will inform you if the build operation is successful. It willinform you of the location of the created WAR file, as well.

    Packaging the Web

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    64/80

    g gApplication

    64Web Programming

    Using an Ant build file to package the application

    Aside from using an IDE to package the web application, we canalso make use of a build tool that can automate for us thecompilation and packaging process.

    Ant A build tool that has wide industry acceptance.

    An open-source project of the Apache Software Foundation, and can bedownloaded from: http://ant.apache.org

    Reads in a build file (traditionally named build.xml) made up of targets, whichessentially define logical activities that can be carried out by the build file. Thesetargets are composed of one or more tasks that define the details of how the

    targets perform their activities.

    Requirements of the Build File

    http://ant.apache.org/http://ant.apache.org/
  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    65/80

    Requirements of the Build File

    65Web Programming

    It must be located in the project root of the directorystructure recommended by the Apache Software Foundationfor web application development.

    Additionally, there must also exist a lib directory in the

    project root that will contain all JAR dependencies of theapplication.

    There must exist a file named build.properties in the same directoryas the build script and must contain values for the followingproperties:

    app.name the name of the application / project. appserver.home the installation directory of a Sun Application Server 8.1

    instance.

    Using an Ant Build File

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    66/80

    Using an Ant Build File

    66Web Programming

    The following is the directory structure recommended forweb application development:

    This directory structure was designed to be separate from thedirectory structure required by the servlet specification.

    After build script has executed, will contain the application in a directory structure recognized byservlet containers.

    After build script has executed, will contain the WAR file.

    Used to contain whatever documentation is used by the dev team.

    Directory under which all Java source files must be placed.

    Directory containing all static content of the app (HTML, JSP), will be the basis of the documentroot of your project.

    Directory containing configuration files such as the deployment descriptor (web.xml),tag library descriptors, etc.

    Using an Ant Build File

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    67/80

    Using an Ant Build File

    67Web Programming

    (Directory Structure continued)

    Apache lists the following advantages for having such a separatedirectory structure:

    Contents of source directory are more easily administered, moved, or backed upif the deployment version is not intermixed.

    Source code control is easier to manage on directories that contain only sourcefiles (no compiled classes, etc.).

    The files that make up an installable distribution of the application are easier toselect when the deployment hierarchy is separate.

    Using an Ant Build File

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    68/80

    Using an Ant Build File

    68Web Programming

    (Directory Structure continued)

    To perform the packaging of an app using this structure, run thefollowing on the command-line (in the same directory containing thebuild file):

    ant dist

    This will call the dist target in the build file which will generate the WAR file andplace it into the dist directory. This WAR file can then be loaded into the targetservlet container using the admin tools provided by the container.

    Deployment into Server

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    69/80

    Deployment into Server

    69Web Programming

    Servlet containers generally contain administrative tools thatcan be used to deploy web applications.

    Steps required to deploy the generated WAR file into SunApplication Server 8.1:

    First step, log-in into the administrative console. This can beaccessed by entering the following URL in your browser:

    http://localhost:[ADMIN_PORT]

    ADMIN_PORT is the port configured during installation to handle administrativerequests.

    Deployment into Server

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    70/80

    Deployment into Server

    70Web Programming

    (Steps continued)

    Second, left click on the Web Applications tab on the panel to theleft, then click on the Deploy button found in the panel to the right.

    Deployment into Server

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    71/80

    Deployment into Server

    71Web Programming

    (Steps continued)

    In the screen that appears next, click on the Browse button to selectthe WAR file to upload. Click on the Next button found in the upperright.

    Click on the Finish button in the next screen.

    Congratulations, your application is now deployed.

    Servlet and Application

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    72/80

    Parameters

    72Web Programming

    ServletConfig and Servlet Initialization Parameters

    ServletContext and Application Parameters

    ServletConfig and Servlet

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    73/80

    Initialization Parameters

    73Web Programming

    ServletConfig object

    Passed to a specific servlet during its initialization phase.

    Using this, a servlet can:

    Retrieve information specific to itself, such as initialization parameters.

    Gain access to an instance of the ServletContext object.

    Initialization parameters are of great use:

    When dealing with information that may vary with each deploymentof the application.

    Allows deployers the ability to change servlet behaviour withouthaving to recompile the code.

    ServletConfig and ServletI i i li i P

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    74/80

    Initialization Parameters

    74Web Programming

    We can add initialization parameters to the servlet byspecifying them in the servlet's definition in the deploymentdescriptor.

    ...

    FirstServlet

    jedi.servlet.FirstServlet

    debugEnabled

    true

    ...

    ServletConfig and ServletI iti li ti P t

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    75/80

    Initialization Parameters

    75Web Programming

    (Adding Initialization Parameters continued)

    The and tags tell the container that weare starting and ending parameter definition, respectively:

    defines the name of the parameter defines its value

    ServletConfig and ServletI iti li ti P t

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    76/80

    Initialization Parameters

    76Web Programming

    To gain access to the servlet parameters, a servlet must firstget a handle on its ServletConfig object, which can be doneby calling on the getServletConfig() method. Afterwards, the

    parameter value can be retrieved as a String by calling thegetInitParameter method and supplying the value of as the parameter.

    public void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {

    ServletConfig config = getServletConfig();String isDebugEnabled = config.getInitParameter("debugEnabled");if (isDebugEnabled.equals("true") {

    ...}

    ServletContext andA li ti P t

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    77/80

    Application Parameters

    77Web Programming

    The ServletContext object gives the servlet access to theapplication context.

    Application context

    Area which an application moves in. Provided by the container for each web application with each application's

    context being separate from each other an application may not access thecontext of another app.

    Having access to this context is important:

    Servlet can retrieve application-wide parameters and data.

    Servlet can also store data that can be retrieved by any components in theapplication.

    ServletContext andA li ti P t

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    78/80

    Application Parameters

    78Web Programming

    In much the same way that initialization parameters can besupplied for individual servlets, they can also be supplied foruse by the entire application.

    Example of how to add application-wide parameters:

    databaseURLjdbc:postgresql://localhost:5432/jedidb

    ServletContext andA li ti P t

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    79/80

    Application Parameters

    79Web Programming

    (Adding Application-wide Parameters continued)

    Each instance of defines a parameter for use bythe whole application.

    and works the same way as their counterparts

    NOTE: Again, be reminded that the specification is strict about theordering of elements inside the deployment descriptor. To keep yourweb.xml valid, all entries must be located BEFOREany entries.

    ServletContext andApplication Parameters

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter02 Basic Servlets

    80/80

    Application Parameters

    80Web Programming

    Retrieving the parameter values is very similar to that usedfor retrieving servlet-specific parameters. Only this time, it isan instance of ServletContext that the servlet must have a

    handle to. This can be retrieved by calling thegetServletContext() method from an instance of the servlet'sServletConfig object.

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

    ServletContext ctxt = getServletConfig().getServletContext();String jdbcURL = ctxt.getInitParameter("databaseURL");// custom codesetURL(jdbcURL);

    ....

    }