meljun cortes jedi coursenotes web programming lesson2 basic servlets

Upload: meljun-cortes-mbampa

Post on 04-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    1/29

    Servlets

    Introduction

    Definition

    A servletis a Java programming language class used to extend the capabilities of serversthat host applications accessed via a request-response programming model as adapted

    from j2EE Tutorial. It is a Java class that implements the Servlet interface and acceptsrequests that can come from Java classes, Web clients, or other Servlets and generates

    responses.

    "Servlets" are also called "HTTP Servlet". This is because servlets are commonly usedwith HTTP, but are actually not tied to a specific client-server protocol.

    To start making servlets, you'll need to have knowledge about Java programming, client-server concepts, basic HTML and HTTP (HyperText Transfer Protocol). To create aServlet, you'll need to import in your java program the standard extension classes in the

    packages javax.servlet and javax.servlet.http.

    javax.servlet contains the basic servlet framework, while javax.servlet.http is used asan extension of the Servlet framework for Servlets that answer HTTP requests.

    Servlet Architecture Overview

    Prior to Servlets, one of the most common ways of adding functionality for a web serverwas through the use of Common Gateway Interface (CGI). CGI provides a server an

    interface to an external program, allowing it to be called by the server to handle clientrequests. However, CGI was designed in such a way that each call for a CGI resourcecreates a new process on the server; information meant for the program is passed tothis process using standard input and environment variables. Once the request isaccomplished, the process is shut down, returning resources to the system. The problemincurred by this approach was that it imposed a heavy requirement on system resources,

    limiting the number of users that the application can handle at the same time.

    Servlets were designed to be able to bypass this problem inherent in CGI and to providedevelopers a robust Java solution to creating applications for the Web. Instead of

    creating a heavy-weight process on the server each time a request from a client comesin, with servlets, there is only one process that handles ALL requests: the processrequired by the servlet container to run. When a new request comes in, the containercreates only a lightweight thread to execute the servlet.

    Servlets are also loaded into memory only once: either the container loads them intomemory on server startup, or the first time the servlet is required to service a client,unlike CGI where each client request loads and unloads the program data into and from

    memory. Once the servlet is loaded into memory, it stays loaded in memory, ready tohandle further client requests.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    2/29

    Servlet First Look

    The sample code that follows shows the structure of a basic servlet that handles GETrequests, as well as displays the traditional 'Hello World'.

    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

    }}

    Figure 1: Basic Servlet that Displays Hello World

    The first part of the code in Figure 2.1 is importing classes in java.io (for PrintWriter,etc.), javax.servlet and javax.servlet.http. The javax.servlet and javax.servlet.http arepackages that provide interfaces and classes for wrtiting servlets (for HttpServlet,HttpServletRequest and HttpServletResponse).

    By extending HttpServlet, this class inherits methods that are automatically called by the

    server depending on certain conditions which will be expound more later. By overridingthese methods, we can make our servlet perform the functionality we want it to do.

    In this case, the method inherited from HttpServlet that we overrode is the doGetmethod. To put it simply, it is the method invoked by the servlet container whenever aGETrequest is issued to a particular servlet. Remember from the previous module thatsite navigation, document retrieval, page viewing are examples of GET requests. So,whenever a user wants to view the output of our servlet, it is a GET request that is

    issued.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    3/29

    If we look at the code listing, we will see that the doGet method takes in twoparameters: an HttpServletRequest object and an HttpServletResponse object. Wherethese objects came from are no longer the concern of the developer. They are created

    and maintained by the servlet container and are simply passed to us the moment thecontainer calls the doGet method. In respect to this, the doGet method and othermethods to be discussed later, are similar in a way to the public static void

    main(String[] args) method we use in a command-line based Java program. We do notcreate the String array passed into the method; it is simply provided for us by the

    runtime environment.

    HttpServletRequest and HttpServletResponse objects provide developers with well-needed functionality:

    The HttpServletRequest object provides access to all information regarding theclient's request, including whatever form parameter values they may have put in,HTTP request headers, the HTTP request method that they used, etc.

    The HttpServletResponse object contains all the necessary methods needed bydevelopers to produce a response that will be sent back to the client. This

    includes methods to set the HTTP response headers to declare the MIME type ofthe response, as well as methods to retrieve instances of Java I/O classes that wecan use directly to produce output.

    Going back to the code, we see that, aside from the comments, there are only severallines that we use to perform the functionality of displaying "Hello World!" to the user.One is PrintWriter out = response.getWriter(), and the other, multiple calls toout.println(). For now, think of the PrintWriter simply as an object that will let us output

    text to the client browser. With that in mind, it is easy to see how multiple calls toout.println() is able to produce the following content:

    Testing the Sample Servlet

    At this point, we need to be able to display the output of the sample servlet. To initiallyabstract the details of servlet deployment and configuration, we will be making use ofthe automated tools provided by IDEs. The IDE that we will be making use of in our

    Figure 2: Output of HelloServlet

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    4/29

    example is Sun Studio Enterprise 8, which is available for free for members of the SunDeveloper Network. It has complete support for the servlet and JSP specifications, aswell as a host of additional features.

    From here on, we will assume that Enterprise 8 has already been successfully installed inyour system. For help in installation, refer to the Appendix section of this courseware.

    First off, for our servlet example here, we need to create a new web application project.

    To do this, in the menubar, select New->Project. In the screen that appears next, selectthe Web category. In the right, choose New Web Application.

    The next screen will prompt you for details about the project. For our first test servlet,let's make use of "FirstServletProject" as our project name, and make use of defaultvalues for the other fields.

    Figure 3: Creating a New Web Application Project

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    5/29

    After creating a new web project, the screen should look something like what isillustrated below:

    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/Folderinstead. In the next screen, select the Web category, then Servlet.

    Figure 4: New Web Application Project

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    6/29

    The IDE will then launch a series of screens which will ask for details about the servlet tobe created. In the first screen, name the servlet FirstServlet. Under package name, use

    jedi.servlet.

    Figure 5: Adding Servlet to the Application

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    7/29

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

    Figure 6: Changing the Class Name and Package Name

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    8/29

    This will result in something like the screen below being generated.

    From this we can see that the IDE has created and partially implemented for us amethod named processRequest . If we were to click on the box with a plus sign on the

    lower left, we would see that processRequest is simply a method that will be called byboth doGet and doPost. This means that the contents of processRequest method form

    the basis of the functionality of our servlet.

    First, remove all contents of the processRequest method. Then, copy/paste the contentsof the doGet method from the code listing for the test servlet into it.

    Figure 7: The processRequest Method

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    9/29

    To run, press Shift + F6. The IDE will then package, deploy, and invoke the servletautomatically for the production of output.

    Servlet Lifecycle

    A servlet is managed through a well-defined lifecycle described in the servletspecification. The servlet lifecycle describes how a servlet is loaded, instantiated,initialized, services requests, destroyed and finally garbage collected. The lifecycle of aservlet is controlled by the container in which the servlet has been deployed.

    The servlet life cycle allows servlet engines to address both the performance andresource problems of CGI and the security concerns of low-level server API

    programming. A servlet engine may execute all its servlets in a single Java virtualmachine (JVM). Because they are in the same JVM, servlets can efficiently share datawith each other, but they are prevented by the Java language from accessing oneanother's private data. Servlets may also be allowed to persist between requests asobject instances, taking up far less memory than full-fledged processes.

    The image above shows the major events in a servlet's life. It is important to note thatfor each of these events there is a method in the servlet that will be invoked by the

    container. Let's go through them one by one.

    Figure 8: New processRequest Method

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    10/29

    Instantiation

    In this stage, the servlet class is loaded into memory, and an instance of it created bythe servlet container.

    By default, a servlet container practices what is called lazy loading. Using this method,a servlet class is loaded into memory, instantiated, and initialized only aftera requesthas been made for it. This makes a faster startup time for the application, but this also

    means that there is a little bit of overhead associated to the first call of each servlet. Ifthis behavior were undesirable, each servlet can be configured to be loaded at server or

    application startup. More on this later in our discussion of the application's deploymentdescriptor.

    As we can see in the diagram, a servlet goes through the instantiation phase only once

    per lifetime. This means that the overhead associated with loading the servlet's classdefinition into memory happens only once. This shows the servlet's advantage over othercompeting technologies.

    The relevant method that the container will call at this stage will be the servlet's no-argument constructor. It is not really recommended that any code be placed in the

    constructor though. Most functionality that developers want to add to constructorsinvolves the set-up of the object, or the initialization of its values. Servlets have a

    separate phase for this kind of activity.

    Initialization

    In this phase, the servlet is primed for use in the application. Like the instantiationphase, a servlet goes through this stage only once. It is only after this phase that our

    object instance can start to be called a servlet.

    The method that is called by the container at this point is the init() method. Itscomplete method signature is presented below.

    public void init(ServletConfig config)

    As we can see, this method takes in one parameter: an instance of a ServletConfig

    object. This object contains the servlet's configuration information, as well as providing away for the servlet to access application-wide information and facilities.

    As mentioned before, any configuration or initialization code should not be placed in the

    servlet's constructor but should instead be placed here in the init method. If a developeris to implement this method though, it is important that he remember to make a call tosuper.init(config). This makes sure that a servlet's default initialization action is notleft out and its configuration info is properly set.

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

    This method can only be called again when the server reloads the servlet . The server

    cannot reload a servlet until after the server has destroyed the servlet by calling thedestroy method.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    11/29

    Service

    This is the phase when a servlet is in for the bulk of its lifetime. In this phase, the servlet

    can be repeatedly called by the container to provide its functionality.

    The following is the signature of the method invoked by the servlet container during thisphase:

    public void service(ServletRequest req, ServletResponse res)

    The ServletRequest and ServletResponse objects passed on to this method provide

    methods to extract information from the user's request and methods to generate theresponse.

    One important thing to note is that the servlet container makes these repeated calls to

    the service method using separate threads. Mostly, there is only one active servletinstance taking up space in memory, handling multiple requests. That is one advantagea Java servlet has. That is also one of the reasons why a servlet (and its service method)should always be designed to be thread-safe.

    For HTTP-specific servlets (servlets extending HttpServlet), developers should not

    override the service method directly. Instead, developers should override any of thefollowing 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, ...). The

    appropriate method is then called when the servlet receives a HTTP request.

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

    Destruction

    There are times when a servlet container will run out of memory, or detect that theamount of free memory it has is within a certain threshold. When this happens, the

    container will attempt to free up memory by destroying one or more servlet instances.Which servlet to be removed is determined by the servlet container and is not somethinga developer has direct control over.

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

    When a servlet is to be removed from a container's management, it is said to be in itsdestruction phase. The method called by the container before this is accomplished is the

    destroy() method. Here, our servlet should be coded to explicitly free up resources thatit has a handle to (e.g. Database connections).

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    12/29

    Garbage Collection

    This phase in the servlet lifecycle is equivalent to that in any other Java object. As a

    recap, this phase occurs just before an object instance is removed from memory (a.k.a.garbage collected). Developers have no direct control as to when this will occur.

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

    Section Quiz

    Answer the following questions about a servlet's phases:

    1. What are the 5 phases of a servlet's lifecycle?2. What are the servlet methods associated with each phase of the lifecycle?

    3. Why does code placed in a servlet's service method need to be thread-safe?

    4. When is a servlet destroyed?5. How many times can the code placed in the servlet's init() method be called? In the

    service() method?6. If our servlet extends HttpServlet, what additional methods can we override to

    produce the needed functionality?

    Handling Requests and Responses

    The main purpose of a servlet is to provide dynamic content to the user. By definition,

    dynamic content changes in response to various conditions. Examples of which are theparticulars of a user request, time of day, etc.

    To give the servlet access to the particulars of a user's request, it is provided an instanceof a ServletRequest object that encapsulates those details. HTTP-based servlets aregiven a subclass, HTTPServletRequest, that provides additional methods in retrievingHTTP-specific information, such as cookie information, header details, etc.

    Form Data and Parameters

    request.getParameter

    One of the most often encountered scenarios requiring dynamic content is when we want

    our application to respond to the user data as presented in a form.

    Take the following example:

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    13/29

    Given the form above which takes in the user's name, we want to be able to produce a

    response customized to that user's name.

    For this and other similar scenarios, Java provides the getParameter method in theHttpServletRequest object. The following is its method signature:

    public String getParameter(String parameterName)

    Basically, this method takes in the name of the parameter we wish to retrieve and

    returns the String value of that parameter.

    Below is a sample code that takes in the user's name and outputs a simple greeting,followed by the HTML used to display the form.

    public class GetParameterServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException {

    // retrieve the value supplied by the userString userName = request.getParameter("userName");

    // retrieve the PrintWriter object and use it to output the greetingPrintWriter out = response.getWriter();out.println("");out.println("HELLO AND WELCOME, " + userName + "!");out.println("");

    out.close();

    }}

    Figure 10: Sample servlet that takes int the use's name and outputs a simple greeting

    Figure 9: Input User Name

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    14/29

    Halloa!

    Enter user name:

    Figure 11: Sample HTML that displays the form

    If we were to supply "JEDI" as the value for the form we created earlier, the followingresult would be generated:

    request.getParameterValues

    There are times when we need to retrieve data from a form with multiple elements ofthe same name. In this case, simply using the getParameter method previouslydescribed will return only the value of the first element with the given name. To retrieveall of the values, we use the getParameterValues method:

    public String[] getParameterValues(String parameterName)

    This method is similar to the one we just discussed. It also takes in the name of theparameter whose values we wish to retrieve. This time though, instead of a single

    String, it returns a String array.

    Below is a sample, along with its output:

    Figure 12: Output of GetParameterServlet

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    15/29

    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]);}

    }

    }

    Choice selectionWhat sports activities do you perform?

    Biking

    Table Tennis
    Swimming

    Basketball
    Others

    If the entries "Biking", "Table Tennis", and "Swimming" were to be chosen, the outputwould be:

    Figure 13: Retreiving Data from a Form with Multiple Elements

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    16/29

    request.getParameterNames

    There are times when we want our servlet to be aware of the name(s) of one or more ofthe parameters within the form without 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 Request URL

    Remember, from our HTTP, a request URL is composed of the following parts:

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

    We can retrieve the curent values for each of these parts from the user's request bycalling on methods in the HttpServletRequest object.

    Host request.getServerName()

    Port request.getServerPort() Request Path in Java, the request path is divided into 2 logical components :

    Context the context of the web application. Can be retrieved byinvoking request.getContextPath()

    Path info the rest of the request after the context name. Can beretrieved by invoking request.getPathInfo()

    Query String request.getQueryString()

    So, for example, with a request URL of:http://www.myjedi.net:8080/HelloApp/greetUser?name=Jedi

    And if we call pm the aforementioned methods, these results are yielded:

    Figure 14: Output of GetParameterValuesServlet

    http://www.myjedi.net:8080/HelloApp/greetUser?name=Jedihttp://www.myjedi.net:8080/HelloApp/greetUser?name=Jedi
  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    17/29

    request.getServerName() www.myjedi.net

    request.getServerPort() 8080

    request.getContextPath() HelloApprequest.getPathInfo() greetUser

    request.getQueryString() name=Jedi

    Header Information

    Header information can be retrieved from within the servlet by calling on the followingmethods in HttpServletRequest:

    getHeader(String name) returns the value of the specified header as aString. If the specified header does not exist, this method returns null.

    getHeaders(String name) similar to getHeader(). However, it retrieves allvalues for the specified header as an Enumeration object.

    getHeaderNames() - this method returns the names of all headers included inthe HTTP request as an Enumeration object.

    getIntHeader(String name) - returns the value of the specified header as anint. If the specified header does not exist in the request, this method returns -1.

    getDateHeader(String name) returns the value of the specified header as along value that represents a Date object. If the specified header does not exist,this method returns -1. If the header cannot be converted to a Date, this methodthrows an IllegalArgumentException.

    Output Generation

    In all the previous examples, we've been able to generate dynamic output for the user.We've done this by using methods exposed in the HttpServletResponse object.

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

    PrintWriter object associated with our response to the user. To help put things in properperspective, we should remember that the System.out object that we regularly use tooutput content to the console is also an instance of a PrintWriter object. That is, theybehave mostly the same way: if you have an instance of a PrintWriter object, simply callits provided print or println methods to provide output.

    The code for our first servlet is replicated here for recall, with the output code in bold

    font.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    18/29

    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}

    }

    Figure 15: Recalling HelloServlet

    Other notable methods in the HttpServletResponse object are:

    setContentType this informs the client's browser of the MIME type of theoutput it is about to receive. All of the content we've generated so far have beenHTML. We could easily send other types of content such as JPEG, PDF, DOC, XLS,

    etc. For non-text output though, the print methods in the PrintWriter object we'vebeen using so far are insufficient. To generate non-text output, we make use of

    another method. getOutputStream this retrieves an instance of the OutputStream object

    associated with our response to the user. With this OutputStream, we can then

    use standard Java I/O objects and methods to produce all kinds of output.

    Below is a sample code that will output a JPG file contained in the web application to theuser.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    19/29

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

    // define a byte array to hold data

    byte bufferArray[] = new byte[1024];

    // retrieve the ServletContext which we will use to retrieve the resource

    ServletContext 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 response

    ServletOutputStream os = response.getOutputStream();

    // retrieve the resource as an input stream

    InputStream 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 used

    is.close();os.close();

    }}

    Figure 16: Sample Code to Output a JPG File

    Request Handling/Response Generation Exercises

    1. Given the following form:

    Enter number 1 :

    Enter number 2 :

    Create a servlet named AddServlet that will retrieve the 2 numbers given by theuser, add them, and then output the result.

    2. Given the following form:

    Menu

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    20/29

    Which food items do you want to order?

    Sundae P 20

    Reg. Burger P 25

    Dessert Pie P 15

    Rice Meal P 70

    Create a servlet named MenuSelectionServlet that will retrieve the selections

    made by the user, add their values, and return the computed result to the user.

    Configuration, Packaging, and Deployment

    In all the examples we have done so far, we have used the tools inherent in theEnterprise IDE to abstract the details of web application configuration, packaging, and

    deployment. We will take a closer look at those details now.

    Web Application Configuration

    The servlet specification defines an XML file named web.xml that acts as a configuration

    file for our web applications. This file is also called the deployment descriptor.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    21/29

    FirstServletjedi.servlet.FirstServlet

    FirstServlet/FirstServlet

    30

    index.jsp

    Figure 17: web.xml for FirstServlet

    Listed above is the web.xml we used for our FirstServletexample. We will use this as ourstarting point in the exploration of web.xml.

    NOTE : The web.xml for Enterprise web application projects can be found by expandingthe Configuration Files tab in the project view.

    This line serves as both the root element of the configuration file and a declaration of tge

    necessary information (through its attributes) for the servlet container to recognize thefile as a valid deployment descriptor file.

    Each instance of this element defines a servlet to be used by the application. It has the

    following child nodes: - A logical name supplied by the developer which will be used for

    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 value

    for this element is a number which dictates the order of its loading compared toother servlets.

    Each instance of this element defines a mapping to a servlet. It has the following child

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    22/29

    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 avalue of /* will make all requests to your application redirected to your servlet.

    In the given example, the url pattern of FirstServlet is /FirstServlet. This means that allURL requests to http://[host]:[port]/FirstServletProject/FirstServletwill be handled by

    FirstServlet.

    Take note that all servlet definitions must first be supplied before adding any servletmappings.

    This element defines configuration details for session management. It will be discussedin the next chapter.

    This element defines a web component that will be automatically loaded if the userenters a request for the application without specifying a particular resource. Forexample, a request to http://[host]:[port]/FirstServletProjectwill cause the file definedhere to be loaded.

    More than one file can be specified in this list. Only the first one visible to the webcontainer will be loaded.

    Packaging the Web Application

    Let us take a look again at the structure of a web application as mandated by the servletspecification:

    Our application can be deployed to a server by making use of what is called a WAR file.WAR files are the same as JARs; they contain Java application code compressed usingthe ZIP format. Informally, WAR stands for Web Archive.

    Generating WAR files from existing Enterprise projects

    It is very simple to produce the WAR file containing our web application from an existing

    Figure 18: Directory Structure of Java Web Application

    Contains HTML, images, other static content, plus JSPs

    Contains meta-information about your application

    (optional)

    All contents of this folder ca nnot be seen from the web

    browserContains 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

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    23/29

    project in Sun Studio Enterprise 8. It is as simple as right clicking on the project name inthe Project view, and selecting Build Project. The IDE will then proceed to package yourapplication.

    The IDE will inform you if the build operation is successful and inform you of the locationof the created WAR file.

    Figure 19: Build Project

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    24/29

    Using an Ant build file to package the application

    Aside from using an IDE to package the web application, we can also make use of a buildtool that can automate the compilation and packaging process for us.

    A build tool that has wide industry acceptance is Ant. It is an open-source project of theApache Software Foundation, and can be downloaded from http://ant.apache.org.

    Basically, Ant reads in a build file (traditionally named build.xml). This build file is made

    up of targets, which essentially define logical activities that can be carried out by the

    build file. These targets are, in turn, composed of one or more tasks that define thedetails of how the targets perform their activities.

    A build file that can perform compilation and packaging tasks is included in thecourseware and can be found in the samples/blankWebApp directory.

    Requirements of the build file:

    It must be located in the project root of the directory structure recommended by

    the Apache Software Foundation for web application development. Additionally, there must also exist a lib directory in the project root that will

    contain all JAR dependencies of the application.

    Figure 20: Build Successful

    http://ant.apache.org/http://ant.apache.org/http://ant.apache.org/http://ant.apache.org/
  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    25/29

    There must exist a file named build.properties in the same directory asthe build script and must contain values for the following properties:

    app.name the name of the application / project

    appserver.home the installation directory of a Sun ApplicationServer 8.1 instance

    The following is the directory structure recommended for web application development:

    This directory structure was designed to be separated from the directory structurerequired by the servlet specification. Apache lists the following advantages for having

    such a separate directory 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 is easier toselect when the deployment hierarchy is separate.

    Things may be a bit hard to understand at first glance. To help in understanding, all of

    the requirements to compile and package our FirstServlet example is provided in thesamples/FirstServletdirectory.

    To perform the packaging of an applicatio using this structure, run the following on thecommand-line (in the same directory containing the build file).

    ant dist

    This will call the dist target in the build file which will generate the WAR file and place itinto the dist directory. This WAR file can then be loaded into the target servlet container

    using the admin tools provided by the container.

    Deployment into Server

    Servlet containers generally contain administrative tools that can be used to deploy web

    applications. Here we will cover the steps required to deploy the generated WAR file intoSun Application Server 8.1.

    Figure 21: Directory Structure Recommended for Web Application Development

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

    After build script has executed, wi ll contain th e 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 descr iptors, etc.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    26/29

    First step, log-in into the administrative console. This can be accessed by enteringthe following URL in your browser http://localhost:[ADMIN_PORT] where

    ADMIN_PORT is the port configured during installation to handle administrativerequests.

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

    In the screen that next appears, click on the Browse button to select the WAR file

    to upload. Click on the Next button found in the upper right. Click on the Finish button in the next screen.

    Congratulations, your application is now deployed.

    Servlet and Application Parameters

    1. Identify the web.xml element described by each of the following:a) Contains the logical name used to refer to a servlet.b) The root element of the configuration file.

    c) Defines a mapping between a servlet and a user request.2. Rearrange the following in order of their required appearance within the XML file:

    session-configservlet

    servlet-mapping

    Figure 22: Deploying the WAR File

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    27/29

    welcome-file-list3. Suppose that we have a servlet whose name is TrialServlet, create a servlet-mapping

    entry such that TrialServlet will be called for each request to:

    http://[host]/[context]/myExerciseServlet.4. What are WAR files?5. Given an existing web project in our IDE, how can a WAR file be generated?

    Servlet and Application Parameters

    ServletConfig and Servlet Initialization Parameters

    The ServletConfig object is the object passed to a specific servlet during its initializationphase. Using this, a servlet can retrieve information specific to itself (e.g. initializationparameters). The servlet can also gain access to an instance of the ServletContext objectusing the ServletConfig object.

    Initialization parameters are of great use, especially when dealing with information that

    may vary with each deployment of the application. Also, supplying some data to theservlet as parameters, as opposed to hard-coding them directly into the servlet, allows

    deployers the ability to change servlet behaviour without having to recompile the code.

    We can add initialization parameters to the servlet by specifying them in the servlet'sdefinition in the deployment descriptor. Below is a sample:

    ...

    FirstServlet

    jedi.servlet.FirstServlet

    debugEnabledtrue

    ...

    Figure 23: Adding Initialization Parameters to the Servlet

    The and tags tell the container that we are starting and

    ending parameter definition respectively. defines the name of the

    parameter, and defines its value.

    To gain access to the servlet parameters, a servlet must first get a handle on itsServletConfig object, which can be done by 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.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    28/29

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

    ServletConfig config = getServletConfig();

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

    ...

    }

    Figure 24: Accessing Servlet Parameters

    Above is a sample piece of code that illustrates the procedure.

    ServletContext and Application Parameters

    The ServletContext object is an object that gives the servlet access to the application

    context.

    Think of the application context as the area which an application moves in. This area is

    provided by the container for each web application. With each application's context beingseparated from each other, an application may not access the context of another

    application.

    Having access to this context is important because with this, the servlet can retrieveapplication-wide parameters and data. It can also store data that can be retrieved byany components in the application.

    In much the same way that initialization parameters can be supplied for individual

    servlets, they can also be supplied for use by the entire application.

    databaseURLjdbc:postgresql://localhost:5432/jedidb

    Figure 25: Adding Application-wide Parameters

    The above code shows an example of how to add application-wide parameters. The xmlelement used here is . Each instance of such an element defines aparameter for use by the whole application. and work

    the same way as their counterparts.

    NOTE : Again, be reminded that the specification is strict about the ordering of elementsinside the deployment descriptor. To keep your web.xml valid, all entries must be located BEFORE any entries.

    The procedure to retrieve the parameter values is very similar to that used for retrievingservlet-specific parameters. This time though, it is an instance of ServletContext that theservlet must have a handle to. This can be retrieved by calling the getServletContext()method from an instance of the servlet's ServletConfig object.

  • 7/31/2019 MELJUN CORTES JEDI CourseNotes Web Programming Lesson2 Basic Servlets

    29/29

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

    ServletContext ctxt = getServletConfig().getServletContext();

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

    ....}

    Figure 26: Retrieving Parameter Values

    Summary

    Servlets are Java's solution to producing dynamic content for the web and itscounterpart to CGI.

    Servlets come with a number of advantages over CGI, including a reduced memoryfootprint and less overhead with each client request.

    A servlet is entirely managed by its container. The only code necessary fordevelopers is the one implementing functionality.

    To create servlets, developers will create subclasses of HttpServlet and place theirfunctional implementations in either the doGet or doPost methods.

    Request details can be retrieved from HttpServletRequest, and response-generatingmethods can be accessed from HttpServletResponse. Both are passed as parameters

    to doGet and doPost. To deploy servlets into the web container, they should first be loaded as pre-

    packaged WAR files. This packaging process can be automated for us by either anIDE or through the use of a build tool.

    Deployment descriptors are essential parts of the application. They must be locatedin the application's WEB-INF directory and must follow certain rules.

    Parameters can be supplied to the application using the deployment descriptor andcan be retrieved by using methods in ServletConfig or ServletContext instances.