Introduction to J2EE Enterprise Architecture The Web Tier Servlets - PowerPoint PPT Presentation

1 / 32
About This Presentation
Title:

Introduction to J2EE Enterprise Architecture The Web Tier Servlets

Description:

Page (JSP)/ Servlet. Enterprise JavaBeans ... Servlets and JavaServer Pages (JSP ) technology components are Web components ... Either Servlets or JSP pages ... – PowerPoint PPT presentation

Number of Views:379
Avg rating:3.0/5.0
Slides: 33
Provided by: davidgil9
Category:

less

Transcript and Presenter's Notes

Title: Introduction to J2EE Enterprise Architecture The Web Tier Servlets


1
Introduction to J2EE Enterprise Architecture
The Web TierServlets
2
J2EE Architecture
  • Multi-tiered, distributed application model
  • Component based
  • Unified security model
  • Flexible transaction control
  • Web services support
  • Open systems development - not tied into one
    vendor

3
Multitiered Distributed Application Model
  • Generally regarded as three tier systems
  • Client tier, Application server tier, database
    tier

Application Server
Request
Web Form
JavaServer Page (JSP)/ Servlet
Response
Database
Enterprise JavaBeans (EJB)
Results Page
4
J2EE Components
  • A component is a self-contained functional
    software unit that is assembled into a J2EE
    application with its related classes and files
    and that communicates with other components.
  • Application clients and applets are components
    that run on the client.
  • Java Servlets and JavaServer Pages (JSP)
    technology components are Web components that run
    on the server.
  • Enterprise JavaBeans (EJB) components
    (enterprise beans) are business components that
    run on the server.

5
J2EE Components
  • Application client
  • Web client
  • Consists of two parts (1) dynamic web pages
    containing various types of markup language
    (HTML, XML, and so on), which are generated by
    web components running in the servers web tier,
    and (2) a web browser, which renders the pages
    received from the server
  • Applets
  • A web page received from the web tier can include
    an embedded applet. An applet is a small client
    application written in the Java programming
    language that executes in the Java virtual
    machine (JVM) installed in the web browser
  • Application client
  • An application client runs on a client machine
    and provides a way for users to handle tasks that
    require a richer user interface than can be
    provided by a mark up language. It typically has
    a graphical user interface (GUI) created from
    Javas Swing or AWT APIs, but a command-line
    interface is also possible

6
J2EE Components
  • JavaBeans Components
  • Application may include JavaBeans
  • Have properties, get- and set- methods
  • Not considered J2EE components by the J2EE
    specification
  • J2EE Web Components
  • Either Servlets or JSP pages
  • Servlets are Java programming language classes
    that dynamically process requests and construct
    responses.
  • JavaServer Pages are text-based documents that
    execute as servlets but allow a more natural
    approach to creating static content.
  • Business Components (Enterprise JavaBeans)
  • Business code, which is logic that solves or
    meets the needs of a particular business domain
    such as banking is handled by enterprise beans
    running in the business tier.

7
The Different Components
Client Tier
Web Tier
Business Tier
J2EE Server (Container)
8
The Different Containers
J2EE Server (Container)
Applet Container
Web Container
EJB Container
Application clientContainer
9
Containers and Server-side Technologies
  • A container is a runtime service provides the
    interface between components and the low-level
    functionality that supports the component
  • A container manages components that have been
    developed according to the API specifications
  • We shall use Suns Java System Application Server
    as our J2EE container. It provides both a web
    container (for servlets and JSPs) and an EJB
    container (for enterprise beans)
  • Servlets and JSPs are server-side technologies
    that accept HTTP requests from an HTML form and
    return responses in the form of HTML, XHTML or
    XML documents
  • At runtime, servlets and JSPs are equivalent You
    could write an application just using servlets or
    just using JSPs or you could mix them up well
    have a look later at a suitable policy for
    choosing when to use servlets or JSPs

10
Servlet interface
  • Architecturally all servlets must implement the
    servlet interface
  • The methods of the Servlet interface are invoked
    automatically by the servlet container
  • The interface has five methods
  • void init(ServletConfig config)
  • This method is called once during the servlets
    execution cycle to initialise the servlet (the
    argument is supplied by the container)
  • ServletConfig getServletConfig()
  • Returns an object reference to an object that
    implements interface ServletConfig (provides
    access to servlet configuration information as
    well as information about its environment (the
    container)
  • String getServiceInfo()
  • Returns information such as the servlets author
    and version
  • void service(ServletRequest request,
    ServletResponse response)
  • This method is called as a result of a client
    request
  • void destroy()
  • Clean up method called when the servlet is
    destroyed by its container

11
Servlets lifecycle - UML state diagram
Instantiation based on a request or at container
start up
Does not exist
Instantiated
Initialisation
Initialisation failed
Initialised and/or Ready for requests
Unavailable
Back to service In case of temporary
unavailability
End of Service thread
HTTP request(s) From client(s)
Temporary or permanent failure
Time out or container shutdown
Service
Destroyed
12
HttpServlet class
  • Web-based servlets typically extend the
    HttpServlet class
  • HttpServlet is an abstract class that must be
    extended to create an HTTP servlet suitable for a
    Web site. A subclass of HttpServlet must override
    at least one method, usually one of these
  • doGet() if the servlet is to support HTTP GET
    requests
  • doPost() for HTTP POST requests
  • doPut() for HTTP PUT requests
  • doDelete() for HTTP DELETE requests
  • init() and destroy() to manage resources that
    are held for the life of the servlet
  • getServletInfo() if the servlet is to provide
    information about itself
  • There's almost no reason to override the service
    method, which handles standard HTTP requests by
    dispatching them to the handler methods for each
    HTTP request type (the doXXX methods listed
    above).

13
doGet() and doPost() methods
  • doGet(HttpServletRequest req, HttpServletResponse
    resp)
  • Processes an HTTP GET request e.g. to retrieve
    the contents of a specified URL (an HTML or XHTML
    or XML page)
  • The response content can be generated dynamically
    by the servlet
  • URL can be typed into a browsers address or
    Location field and can be bookmarked
  • doPost(HttpServletRequest req, HttpServletResponse
    resp)
  • Processes an HTTP POST request typically used to
    post data from an HTML form to a server-side form
    handler that processes the data (save it in a
    database or retrieve data from the database.)
  • Cannot be typed into a browsers address or
    Location field and cannot be bookmarked
  • an HTTP POST request does not have a restriction
    on the amount of data transmitted
  • Safer to use doPost() method!
  • Except if youre using a servlet to display
    information without an associated html page
    then use doGet() method

14
Simple example using doGet() method
  • On the Client side we need
  • An HTML client e.g. a web browser
  • On the server side we need
  • A servlet with a doGet() method
  • A web.xml file that relates the servlets URL to
    the servlets Java class
  • Usually this is generated for you by the IDE
    (NetBeans in this case)

15
The web client
lthtmlgt ltheadgt lttitlegtHelloServletlt/titlegt
lt/headgt ltbodygt ltform action"hello"
method"get"gt ltpgtpress Submit to invoke
servlet HelloServletlt/pgt ltpgtltinput
type"submit" name"Submit" value"Submit"gtlt/pgt
lt/formgt lt/bodygt lt/htmlgt
  • This file is called index.html
  • Note the form tags
  • The forms action attribute specifies the
    servlets URL, i.e. hello

16
web.xml
ltweb-appgt ltdisplay-namegtHelloWorldlt/display-name
gt ltservletgt ltservlet-namegthelloservletlt/ser
vlet-namegt ltservlet-classgtentapps.HelloServlet
lt/servlet-classgt lt/servletgt
ltservlet-mappinggt ltservlet-namegthelloservletlt/
servlet-namegt lturl-patterngt/hellolt/url-pattern
gt lt/servlet-mappinggt lt/web-appgt
  • Note for each servlet you need two tags
  • ltservletgt
  • ltservlet-mappinggt

17
HelloServlet.java
package entapps import javax.servlet. import
javax.servlet.http. import java.io. public
class HelloServlet extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
out.println("lthtmlgt") out.println("ltheadgtlttit
legtHello Servletlt/titlegtlt/headgt")
out.println("ltbody bgcolor\"lightblue\"gt")
out.println("ltpgtHello World.lt/pgt")
out.println("lt/bodygtlt/htmlgt")
18
Running in NetBeans
  • In NetBeans you need to build the project, then
    deploy the project and finally run the project.
    If you choose the run option then NetBeans will
    automatically build, deploy and run the project.
  • Once the application is deployed and run you see
    the following URL in a web browser (assuming you
    called the project SimpleServlet)
  • http//localhost8080/SimpleServlet/
  • When you hit the submit button Hello World is
    displayed and the URL becomes
  • http//localhost8080/SimpleServlet/hello?SubmitS
    ubmit
  • If you changed the doGet() method to a doPost()
    method and submit the form the URL becomes
  • http//localhost8080/SimpleServlet/hello
  • You cant see the input parameters
  • If you bookmark it then you cant retrieve the URL

19
Adding in request parameters
  • If you wanted to add in the name of the user in
    the html page and display it in the servlets, we
    would add in
  • UserIDltinput type "text" name "requsername"
    gt
  • in the html file
  • and
  • out.println("ltpgtfrom"request.getParameter("requs
    ername"))
  • in the servlet
  • Sometimes you may want to hide the request
    parameter from the user (but still visible when
    you choose view source from within the browser)
  • Set the type attribute to hidden
  • ltinput type "hidden" name "action" value
    "entryform"gt
  • This will be hidden from the user, you can use it
    in the servlet by
  • String action request.getParameter("action")

20
Initialising Servlets
  • Common in real-life servlets
  • E.g. initialising database connection pools
  • Use SevletConfig.getInitParameters() to read
    initialisation parameters
  • Call getServletConfig() to obtain the
    ServletConfig object
  • Set initialisation parameters in web.xml
  • It is common to use the init() method even when
    you dont read initialisation parameters
  • e.g. to set up data structures that dont change
    during the life cycle of the servlet, to load
    information from disk, etc.

21
Example of Initialising parameters
ltweb-appgt ltdisplay-namegtHelloWorldlt/display-name
gt ltservletgt ltinit-paramgt
ltparam-namegtdefaultusernamelt/param-namegt
ltparam-valuegtHarrylt/param-valuegt
lt/init-paramgt ltservlet-namegthelloservletlt/ser
vlet-namegt ltservlet-classgtweb.HelloServletlt/se
rvlet-classgt lt/servletgt ltservlet-mappinggt
ltservlet-namegthelloservletlt/servlet-namegt
lturl-patterngt/helloservletlt/url-patterngt
lt/servlet-mappinggt lt/web-appgt
22
Example of Initialising parameters
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
ServletConfig config getServletConfig()
out.println("lthtmlgt") out.println("ltheadgtlttit
legtHelloServletlt/titlegtlt/headgt")
out.println("ltbody bgcolor\"lightblue\"gt")
out.println("ltpgtHello World.lt/pgt")
out.println("ltpgtfrom " request.getParameter("req
username")) out.println("ltpgtand from "
config.getInitParameter("defaultusern
ame") "the default user")
out.println("lt/bodygtlt/htmlgt")
23
Request Headers
  • Every request has header information associated
    with it e.g. whether the request is a post or get
    request, the protocol associated with the
    request, etc. The request object has methods
    associated to display these headers . Below is a
    servlet that prints these headers out for a
    particular request
  • (from corewebprogramming.com)

public class ShowRequestHeaders extends
HttpServlet public void doGet(HttpServletReque
st request,
HttpServletResponse response) throws
ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
String title "Servlet Example Showing Request
Headers"
24
Request Headers
out.println( "ltheadgtlttitlegtServlet
Example " "Showing Request
Headerslt/titlegtlt/headgt" "ltbody
bgcolor\"B0C4DE \"gt\n" "lth1
aligncentergt" title "lt/h1gt\n"
"ltbgtRequest Method lt/bgt" request.getMethod()
"ltbrgt\n" "ltbgtRequest URI lt/bgt"
request.getRequestURI() "ltbrgt\n"
"ltbgtRequest Protocol lt/bgt"
request.getProtocol() "ltbrgtltbrgt\n"
"lttable border1 aligncentergt\n" "lttr
bgcolor6495ed\"gt\n" "ltthgtHeader
NameltthgtHeader Value") Enumeration
headerNames request.getHeaderNames() while
(headerNames.hasMoreElements())
String headerName (String)headerNames.nextElemen
t() out.println("lttrgtlttdgt" headerName
"lt/tdgtlttdgt" ) out.println(request.getHeader
(headerName) "lt/tdgtlttdgt" )
out.println("lt/tablegt\nlt/bodygtlt/htmlgt")
25
Request Headers
26
Statelessness and Sessions
  • HTTP is a stateless protocol
  • Each request from a client is treated in
    isolation from all other requests from the same
    client i.e. there is no relationship between the
    different requests
  • A protocol is stateful if the response to a given
    request may depend not only on the current
    request but also on the outcome of previous
    requests
  • Stateful is important
  • With on-line banking you only need to register
    once e.g. looking at your balances, or
    transferring money from one account to another
    doesnt require you to re-register for every
    request
  • Internet shopping with a shopping cart
  • Session
  • The server should be able to identify that a
    series of requests from a single client form a
    single working session
  • State
  • The server should be able to remember information
    related to previous requests in a single session

27
Session Tracking with the Java Servlet API
  • The javax.servlet.http.HttpSession interface
    encapsulates the notion of a session
  • The request object provides the getSession()
    method which gives you access to the HttpSession
    object associated with the client making the
    request
  • The HttpSession object is an implicit object and
    is created for each client by the web container
  • The web container maintains this object for the
    duration of the client session
  • Each session consumes memory on the server-side,
    so its unwise to keep sessions open forever
  • Most e-commerce sites limit this interval to less
    than 30 minutes
  • You can specify the session limit time in the
    web.xml file using a deployment descriptor
    element ltsession-configgt

28
Session Methods for Managing State
  • setAttribute() method
  • public setAttribute(String name, Object
    attribute)
  •   Binds an object to this session, using the name
    specified
  • getAttribute() method
  • public Object getAttribute(String name)
  • This method returns the attribute bound with the
    specified name in this session, or null if no
    object is bound under the name
  • getAttributeNames() method
  • public Enumeration getAttributeNames(String name)
  • Returns an Enumeration of String objects
    containing the names of all the objects bound to
    this session.
  • removeAttribute() method
  • public void removeAttribute(String name)
  • Removes the object bound with the specified name
    from this session.

29
Using the state management methods
  • String un request.getParameter("username")
  • request.getSession().setAttribute("user", un)
  • String un(String)request.getSession().getAttribut
    e("user")

30
Request Dispatching
  • Allows a servlet or a JSP page to dispatch a
    request to an HTML page, or another servlet or
    JSP page, which will then be responsible for any
    further processing and for generating the
    response.
  • The request object has an interface for this
    purpose javax.servlet.RequestDispatcher
  • The request dispatcher object has two methods
    which allow delegation of the request-response
    processing to another resource after the
    dispatching servlet has finished any preliminary
    processing
  • public void forward(ServletRequest req,
    ServletResponse resp) throws ServletException,
    java.io.IOException)
  • Allows the request to be forwarded to another
    servlet or JSP page which then assumes all
    responsibility for producing the response
  • public void include(ServletRequest req,
    ServletResponse resp) throws ServletException,
    java.io.IOException)
  • Allows the inclusion of the content produced by
    another resource in the dispatching servlets
    response

31
Examples of Request Dispatching
RequestDispatcher rd
request.getRequestDispatcher("oracleconnection")
rd.include(request, response) String status
(String)request.getSession().getAttribute("st
atus") if (status.equalsIgnoreCase("OK"))
response.sendRedirect("connection_established.html
") else rd request.getRequestDispatcher("
viewerror") rd.forward(request, response)
32
Examples of Request Dispatching
  • oracleconnection is the name of a servlet,
    OracleConnection.java
  • Specified in web.xml
  • ltservletgt
  • ltservlet-namegtoracleconnectionlt/servlet-namegt
  • ltservlet-classgtentapps.OracleConnectionlt/servl
    et-classgt
  • lt/servletgt
  • ltservlet-mappinggt
  • ltservlet-namegtoracleconnectionlt/servlet-namegt
  • lturl-patterngt/oracleconnectionlt/url-patterngt
  • lt/servlet-mappinggt
  • Status is the name of an attribute that
    OracleConnection sets to either OK or fail
  • public void sendRedirect(java.lang.String location
    ) throws java.io.IOException
  • Sends a temporary redirect response to the client
    using the specified redirect location URL. This
    method can accept relative URLs the servlet
    container must convert the relative URL to an
    absolute URL before sending the response to the
    client. If the location is relative without a
    leading '/' the container interprets it as
    relative to the current request URI. If the
    location is relative with a leading '/' the
    container interprets it as relative to the
    servlet container root. (source java.sun.com)
  • viewerror is the name of a Servlet specified in
    web.xml.
Write a Comment
User Comments (0)
About PowerShow.com