B2 BWeb Container510-3pptx

Document Sample
B2 BWeb Container510-3pptx Powered By Docstoc
					                      Overview of Web Applications
    Web application is a collection of web pages
     delivered to a web browser that provide services
     to a community of users.
    Examples range from simple static cs5376 class
     webpage display to complex application such as
     provisioning of services on the web.
    Technologies involved in creating web
     applications include HTTP, HTML, Active
     Server Page (ASP), JavaScript or AJAX, PHP,
     Ruby, Java Applets, CGI, Servlets, Java
     Server Pages (JSP) and Java server Faces.
                                                                                   1




                  Generic Web Server Architecture


                                           Router
                          HTTP Request
                                                                       Programs
                                                          CGI

     Web Browser



                          HTTP Response


                                                                         Servlets



     The Web server processes the HTTP request, routes to
     respective plug-in to handle it and returns the the response as
     an HTML document.


                                                                                   2




                          J2EE Server and Containers

         Client Machine Tier               J2EE Server - tier


                                             Web Container
              Web
              Browser

                                              Servlet      JSP


          Application Client
          Container
                                              EJB Container
                 Appl
                                                    EJB
                 Client
                                                                       Data Tier
                                              EJB          EJB




                                                                                   3




                                                                                       1
                         Web Container
    It is a runtime environment for Servlets and Java Server
     Page (JSP) files as mandated by J2EE standard.
    Both Servlets and JSP are known as web components.
     (Static html pages and applets can be bundled with web
     components during assembly, but are not considered as
     web components).
    It provides services such as request dispatching, security,
     and life-cycle management.
    It also gives Web components access to the J2EE
     platform APIs such as JNDI, JavaMail, JMS, RMI, EJB etc.




                                                              4




                           Java Servlets
    A servlet is a Java class that receives HTTP requests from
     a web server, process them and then sends a response
     back to the HTTP server for transmission to clients.
    It is a set of Java API proposed by Sun to extend Web
     server capability to the full power of Java programming
     language.
    Servlet APIs allow web pages to be generated dynamically
     (also known as server side applet. Why?)
    It is not part of the core Java language standard (a
     standard extension called javax.servlet.*)
    It is coded and deployed in a web container like EJB.


                                                              5




                                 JSP
    JSP technology provides a document-centric,
     rather than programmatic way to specify
     dynamic content generation.
    A JSP page is an HTML page with special
     markups that provides customizable behavior
     for generating dynamic content at runtime.
    A JSP page is translated into a servlet when it
     is deployed.



                                                              6




                                                                   2
                  Servlet Execution Environment
                                       Web Server
                                                                         Servlet Class

       Web Browser
                                                                            S1



                                                    S2                      S2



                                                                            S3




•  the server receives a request and chooses a servlet to handle it
•  the servlet is loaded (already?) and the request is passed to it
•  the servlet responds and the server forwards the response to the
client

                                                                                         7




          Servlet Execution Environment (cont.)

   Invoked through a GET/POST from a HTML form

        <HTML>
        <BODY>
        <FORM METHOD = “GET” ACTION=“Servlet/HelloWorldServlet”>
        ….
        <INPUT TYPE=“SUBMIT” VALUE =“Submit Form”>
        </FORM>
        </BODY>
        </HTML>




                                                                                         8




          Servlet Execution Environment (Cont.)

                                                         Web Server
         Web Browser
                            HTTP Request
                            (GET)                       Invoke doGet()




                                                 HelloWorldServlet.class
                         HTTP Response




      HTTP Request is usually passed as an URL + data



                                                                                         9




                                                                                             3
            Servlet Execution Environment (Cont.)
When a server invokes a servlet instance, it supplies it with two
objects:
   ServletRequest - data and methods with information about request
   ServletResponse - methods to return results to client via server



                    ServletRequest


      Web Server               Servlet




                    ServletResponse



                                                              10




                              Servlet API
     The Servlet API is implemented in two
      packages:
          Javax.Servlet - the generic package for
           servlets that respond to requests using any
           network protocol (servletRequest and
           servletResponse objects are part of this)
          Javax.Servlet.http - the package for servlets
           that respond to requests using the HTTP
           protocol. These are also known as HTTP
           Servlets.

                                                              11




                          HTTP Servlet API
     javax.servlet.http.HttpServlet
          provides a framework for handling HTTP
           requests (e.g. GET, POST)

          new servlets are developed by overriding
           default methods such as doGet(), doPost()

          specialised HttpServletRequest and
           HttpServletResponse classes are provided


                                                              12




                                                                      4
                         Http Servlet API (Cont.)

          public class HelloWorldServlet extends HttpServlet
             {
                public void doGet(...)
                {
                   // we override the doGet() method
                   // see next slide for details
                }

                  public String getServletInfo()
                  {
                    return "The Hello World Servlet";
                  }
              }
                                                                                  13




                        HTTP Servlet API (Cont.)
     public void doGet(HttpServletRequest req,
                   HttpServletResponse res)
                   throws ServletException,IOException
       {
          res.setContentType("text/html");
          PrintWriter out = res.getWriter();
          out.println("<html>");
          out.println("<head><title>Hello!</title></head>");
          out.println("<body>");
          out.println("<h1 align=center>Hello, World!</h1>");
          out.println("</body>");
          out.println("</html>");
          out.close();
       }
                                                                                  14




                                HttpServlet Class
    The HttpServlet class provides the following
     methods:
         void service(HttpServletRequest, HttpServletResponse)
                  invoked by the web container whenever a request comes in for a

                   servlet. Its default behavior is to always call one of the doXXX().
         void doGet(HttpServletRequest, HttpServletResponse)
                  process an HTTP GET request        (i.e. query on current state of
                   server/system)
         void doPost(HttpServletRequest, HttpServletResponse)
                   process an HTTP POST request (i.e. query or update on
                   server/system)
         doPut(), doDelete(), doTrace(), doOptions()
                    handlers for other HTTP requests



                                                                                  15




                                                                                         5
                     HttpServletRequest Interface
    The HttpServletRequest interface defines the
     ServletRequest methods:
             getInputStream(), getReader(),
              getParameterNames(), getParameter(),
              getParameterValues(), etc.
    along with special-purpose methods for
     handling HTTP requests:
             String getRemoteAddr()              returns the IP address of computer that
              sends the request

             String getCookies()        returns any query string that is part of the HTTP
              request URI

             String getRequestURI()             returns the part of request's URI to
              the left of any query string
                                                                                       16




                    HttpServletResponse Interface
    The HttpServletResponse interface defines the
     ServletResponse methods:
             getOutputStream(), getWriter(), setContentType(),
              setContentLength(), etc.


    along with status codes and methods for
     handling HTTP responses, e.g.
              void setStatus(int)       sets the status code for this response




                                                                                       17




      Abstract View of How Web Server Invokes
                       Servlet
      // load the servlet class (most servlet is configured to load at
      //server startup), and set up the request/response objects
           Servlet servlet = ...
           HttpServletRequest request = ...
           HttpServletResponse response = ...

          // initialise servlet data
             servlet.init();

          while (...moreRequests...)
             // invoke servlet to process request
             servlet.service(request, response);
          // clean up after servlet
          servlet.destroy();
                                                                                       18




                                                                                             6
                                 Servlet Life-cycle
    The life cycle of a servlet is controlled by the web
     container in which the servlet has been deployed.
    When a request is mapped to a servlet, the web container
     performs the following steps.
         1.If an instance of the servlet does not exist, the Web
          container
               Loads the servlet class.
               Creates an instance of the servlet class.
               Initializes the servlet instance by calling the init method.
         2.Invokes the service method, passing a request and
          response object.
    If the web container needs to remove the servlet, it calls
     the servlet destroy method.

                                                                               19




                            Writing a simple servlet
    Example is taken from Chapter 11, page
     323-327 in WebLogic Server Bible.
    This servlet accepts a username as an input
     parameter, and then outputs that name as
     part of the HTML page that it creates on the
     fly.
    It also keeps count of how many times it has
     been called.



                                                                               20




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

           private int counter = 0;
           public class HelloServlet extends HttpServlet {

              // performs instantiation
             public HelloServlet() {
                super();
             }
            //perform one-time initialization tasks
             public void init() throws ServletException {}

                public void service(HttpServletRequest request,
                   HttpServletResponse response) throws
                 IOException { details in next slide}

                // clean up
                public void destroy(){};
           }                                                                   21




                                                                                    7
                                    HelloServlet.java (Conts)
             public void doGet(HttpServleRequest req,
                                 HttpServletResponse res) throws
                                 IOException{
                 counter++;
                 res.setContentType("text/html");
                 String you = req.getParameter("name");
                 PrintWriter out = res.getWriter();
                 out.println("<html>");
                 out.println("<head><title>Hello!</title></head>");
                 out.println("<body bgcolor=yellow>");
                 out.println("<table height=100% width=100%><tr>");
                 out.println("<td valign=center align=center>");
                 out.println("<h1>Hello, "+you+"!</h1>");
                 out.println("</td></tr></table>");
                 out.println(“This servlet has been invoked “ + counter
                              + “ times”);
                 out.println("</body></html>");
                 out.close();
               }
                                                                                                               22




                          Compiling and Deploying Servlets
           A servlet may have three names:
               Name that the client uses

               Name used for deployment

               Actual class name

           J2EE standard prescribe a particular structure for web
            application (i.e. a staging directory).
           It must also contain one or more deployment descriptors
            written in XML.
           In BEA WebLogic, the two descriptors are in files named
            web.xml and weblogic.xml ()
           The simple servlet example that follows only requires
            web.xml


                                                                                                               23




                   Web Application Directory Structure for
                                HelloServlet

                         Application Root (BibleApp.war)



                                                       Public files (images, index.html, jsp, client side classes)




                                                   WEB-INF               Classes (servlets, server-side
                                                                         classes)


                                                                         lib (.jar files used by server-side classes)
For portability, bundle as WAR file
by executing the JAR command
at the application root directory. To access                               Web.xml (Web application deployment file)
The application use:
http://localhost:8080/BibleApp/index.html
                                                                             Weblogic.xml

                                           Web.xml and weblogic.xml can be generated using
                                            java weblogic.marathon.ddinit.WebInit staging-dir
                                                                                                               24




                                                                                                                        8
                   Compiling and Deploying (Con.t)
        Compile the servlet using:

             Javac -d WEB-INF/classes HelloServlet.java

Create web.xml file with:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.
//DTD Web Application 2.3//EN“
 "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
 <welcome-file-list>
    <welcome-file>index.html</welcome-file>
 </welcome-file-list>
  <servlet>
     <servlet-name>HelloServlet</servlet-name>
     <servlet-class>HelloServlet</servlet-class>
  <servlet-mapping>
     <servlet-name>Helloservlet</servlet-name>
     <url-pattern>hello</url-pattern>
  </servlet-mapping>
</web-app>
                                                          25




                                     Adder.java
    A Java program which adds an integer to a
     running total.




                                                          26




                            AdderRemote.java




                                                          27




                                                               9
       AdderHome.java




Why do you think it requires java.io.serialization?




                                                      28




        AdderBean.java




                                                      29




       AdderClient.java




                                                      30




                                                           10
       Adder.html




                            31




   AdderServlet.java




                            32




AdderServlet.java (Conts)




                            33




                                 11
                  AdderServlet.java (Conts)




                                                            34




         The difference between GET and POST
    Sensitive data should not be used with GET
        GET’s parameter data sgiws up in the browser’s input

         bar
    POST cannot be bookmarked
        If you want to let users specify search parameters and

         save it for later, cannot use POST
    GET is supposed to be used for getting things –
     information retrieval
    POST is supposed to be used for sending data to be
     processed (update or modify in the server)



                                                            35




                  AdderServlet.java (Conts)




                                                            36




                                                                  12
               Web Application Directory Structure for
                           AdderServlet

                    Application Root (adderFall10)



                                         Public files (images, html, jsp, client side classes)




                                      WEB-INF              Classes (servlets, server-side
                                                           classes)


                                                           lib (.jar files used by server-side classes)
For portability, bundle as WAR file
by executing the JAR command
at the application root directory.                           Web.xml (Web application deployment file)


                                                               Weblogic.xml



                                                                                                 37




                            Build.xml (compile webApp)
     <target  name="compile_webapp2">
        <!--<copy file="adder.html" todir="addServlet"/>-->
        <copy file="${dist}/${ejb_client_jar}" tofile="${clientsource}/WEB-INF/lib/$
     {ejb_client_jar}"/>
        <javac srcdir="${clientsource}" destdir="${clientsource}/WEB-INF/classes"
             includes="AdderServlet.java"
             classpath="${CLASSPATH};${clientsource}/WEB-INF/lib/${ejb_client_jar}"/>
      </target>




                                                                                                 38




               RequestDispatcher: include static HTML
                              content

          package com.comp5376;
          import javax.servlet.*;
          import javax.servlet.http.*;
          import java.io.*;
          public class ImageServlet extends HttpServlet f
          public void doGet(HttpServletRequest request, HttpServletResponse ...
              String choice = request.getParameter("choice");
              String image;
          if (choice.equals("postgrad")) {
          image="/postgrad.html";
          } else {
          image="/uni.html";
          }
          RequestDispatcher rd = request.getRequestDispatcher(image);
          rd.include(request, response);
          }
          }
                                                                                                 39




                                                                                                          13
            Forwarding a request to another servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class LoginServlet extends HttpServlet {
      public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException f
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if (userName!=null && password!=null &&
userName.equals("helen") && password.equals("001")) {
RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
Else {
response.sendError("Login Error");
}


                                                                         40




                            When to use Servlets
        They were used for server-side processing in
         response to requests.
        Also used to generate extensive amount of
         HTML pages for transmission to the client (for
         example hundreds of rows of results from
         querying databases)
        This creates application maintenance
         headaches (why??)
        JSP (Java Server Page) is an HTML extension
         for embedding presentation logic in a servlet

                                                                         41




                  Evolution of Server-side scripting
        Common Gateway Interface (CGI) can be accessed in
         Web server to generate dynamic responses.
        Every CGI runs as a separate process and thus is
         very resource-expensive.
        Active Server Page (ASP) allows inline scripts using
         either VBScript or Jscript com-mingled with HTML for
         generating dynamic content (tie to IIS and run in
         interpretive environment)
        Sun Microsystems introduced JavaServer Page (JSP)
         to provide a means of inline scripting using Java, but
         excelled in performance by leveraging servlet
         technology.

                                                                         42




                                                                              14
                        JSP Tag Convention


JSP pages have two styles of syntax, one called HTML tag and the other
Called scripting tag.




       Scripting tag always begins with <% and ends with %>
            <% @ for directives
            <%! For declarations
            <%= for expressions




                                                                              43




                                  Examples

Page Directive

<%@ page import=“javax.ejb.*, java.math.*, javax.rmi.RemoteException” %>




Declarations                                    Scriplets
<%! Int x=0; %>
                                                <% String Name= fisrtName +
<%! Static public boolean validate = true; %>      lastname; %>
<%!                                             <% Random rand = new Random(); %>
 public String getCurrentDateTime() {
 …}
%>




                                                                              44




                              Converter.jsp




                                                                              45




                                                                                    15
Converter.jsp




                 46




 Converter.jsp




                 47




 Weblogic.xml




                 48




                      16
                        Build.xml for Converter




                                                               49




                                    Questions


     {Who's responsible for what?

     Container or Servlet

     Creates the request and response objects?
     Calls the service() method?
     Adds HTML content to the response object?
     Has a name that matches the
     \verb|<servlet-class>| element in the DD?
     Has a reference to the response objects?
     Finds the URLs in the DD?
     Starts a new thread to handle requests?
     Setting the content type of the response?




                                                               50




             Questions, Suggestions and Advice
    Read Chapter 11 and 12 in BEA Weblogic Server Bible

    Turn Adder.java into EJBs and write a servlet to access
     addeEJB.

    Try more advanced servlet features such as cookie and
     session tracking




                                                               51




                                                                    17

				
DOCUMENT INFO
Shared By:
Tags:
Stats:
views:18
posted:7/28/2011
language:English
pages:17