J2EE Enterprise Architecture

entomologistsamoanΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 5 χρόνια και 3 μέρες)

312 εμφανίσεις

1


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Introduction to J2EE Enterprise
Architecture



The Web Tier


Servlets

2


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Multitiered Distributed Application Model


Generally regarded as three tier systems


Client tier, Application server tier, database tier

Database


Web Form

Results
Page

JavaServer

Page (JSP)/

Servlet

Enterprise
JavaBeans
(EJB)

Request

Response

Application
Server

4


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 Enterprise Architecture


Enterprise Applications CE00465
-
M

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 server’s 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 Java’s Swing or AWT APIs, but a
command
-
line interface is also possible

6


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

The Different Components

Web browser

Dynamic web pages

Applet & optional

JavaBeans

components

Application Client

JavaServer

Pages

Servlets

JavaBeans

components

(optional)

Entity Beans

Session Beans

Message
-
driven

Beans

Database

and Legacy

Systems

Web Tier

Business Tier

Client Tier

J2EE Server (Container)

8


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

The Different Containers


Web browser


Java Plug
-
in

JavaServer

Pages

Servlets

Entity Beans

Session Beans

Message
-
driven

Beans

Database

and Legacy

Systems

Web Container

EJB Container

J2EE Server (Container)

Application client

Container

Application client

Applet Container

9


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 Sun’s 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; we’ll have a look later at a suitable policy for
choosing when to use servlets or JSPs

10


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 servlet’s 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 it’s environment (the container)


String getServiceInfo()


Returns information such as the servlet’s 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 it’s container

11


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Servlet’s lifecycle
-

UML state diagram

Does not exist

Instantiated

Unavailable

Initialised and/or

Ready for requests

Service

Destroyed

Instantiation based on

a request or at

container start up

Initialisation

Initialisation failed

Back to service

In case of temporary

unavailability

HTTP request(s)

From client(s)

End of

Service

thread

Temporary or permanent

failure

Time out or container shutdown

12


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 do
XXX
methods listed above).

13


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 browser’s 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 browser’s 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 you’re using a servlet to display information without an
associated html page


then use doGet() method

14


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 servlet’s URL to the servlet’s Java
class


Usually this is generated for you by the IDE (NetBeans in this case)

15


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

The web client


This file is called
index.html


Note the form tags


The form’s action attribute specifies the servlet’s URL, i.e.
hello

<html>


<head>


<title>HelloServlet</title>


</head>



<body>


<form action="hello" method="get">


<p>press Submit to invoke servlet HelloServlet</p>


<p><input type="submit" name="Submit" value="Submit"></p>


</form>


</body>

</html>

16


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

web.xml


Note for each servlet you need two tags


<servlet>


<servlet
-
mapping>

<web
-
app>


<display
-
name>HelloWorld</display
-
name>



<servlet>


<servlet
-
name>helloservlet</servlet
-
name>


<servlet
-
class>entapps.HelloServlet</servlet
-
class>


</servlet>



<servlet
-
mapping>


<servlet
-
name>helloservlet</servlet
-
name>


<url
-
pattern>/hello</url
-
pattern>


</servlet
-
mapping>

</web
-
app>

17


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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(
"
<html>
"
);


out.println(
"
<head><title>Hello Servlet</title></head>
"
);


out.println(
"
<body bgcolor=
\
"
lightblue
\
"
>
"
);


out.println(
"
<p>Hello World.</p>
"
);


out.println(
"
</body></html>
"
);


}

}


18


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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://localhost:8080/SimpleServlet/


When you hit the submit button Hello World is displayed and the
URL becomes


http://localhost:8080/SimpleServlet/hello?Submit=Submit


If you changed the doGet() method to a doPost() method and
submit the form the URL becomes


http://localhost:8080/
SimpleServlet/hello


You can’t see the input parameters


If you bookmark it then you can’t retrieve the URL

19


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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


UserID:<input type ="text" name = "requsername" >


in the html file


and


out.println("<p>from"+request.getParameter("requsername"));


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”

<input type = "hidden" name = "action" value ="entryform">


This will be hidden from the user, you can use it in the servlet by


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

20


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 don’t
read initialisation parameters



e.g. to set up data structures that don’t change during the life cycle
of the servlet, to load information from disk, etc.

21


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Example of Initialising parameters

<web
-
app>


<display
-
name>HelloWorld</display
-
name>


<servlet>


<init
-
param>


<param
-
name>defaultusername</param
-
name>


<param
-
value>Harry</param
-
value>


</init
-
param>



<servlet
-
name>helloservlet</servlet
-
name>


<servlet
-
class>web.HelloServlet</servlet
-
class>


</servlet>



<servlet
-
mapping>


<servlet
-
name>helloservlet</servlet
-
name>


<url
-
pattern>/helloservlet</url
-
pattern>


</servlet
-
mapping>

</web
-
app>


22


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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("<html>");


out.println("<head><title>HelloServlet</title></head>");


out.println("<body bgcolor=
\
"lightblue
\
">");


out.println("<p>Hello World.</p>");


out.println("<p>from " + request.getParameter("requsername"));


out.println("<p>and from " +


config.getInitParameter("defaultusername") +



"the default user");


out.println("</body></html>");


}

23


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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(HttpServletRequest request,


HttpServletResponse response)


throws ServletException, IOException


{


response.setContentType("text/html");


PrintWriter out = response.getWriter();


String title = "Servlet Example: Showing Request Headers";


24


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Request Headers


out.println(


"
<head><title>Servlet Example:
"

+


"
Showing Request Headers</title></head>
"

+


"
<body bgcolor=
\
"
#B0C4DE
\
"
>
\
n
"

+


"
<h1 align=center>
"

+ title +
"
</h1>
\
n
"

+


"
<b>Request Method: </b>
"

+ request.getMethod() +
"
<br>
\
n
"

+


"
<b>Request URI: </b>
"

+


request.getRequestURI() +
"
<br>
\
n
"

+


"
<b>Request Protocol: </b>
"

+


request.getProtocol() +
"
<br><br>
\
n
"

+


"
<table border=1 align=center>
\
n
"

+


"
<tr bgcolor=#6495ed
\
"
>
\
n
"

+


"
<th>Header Name<th>Header Value
"
);


Enumeration headerNames = request.getHeaderNames();


while (headerNames.hasMoreElements())


{


String headerName = (String)headerNames.nextElement();


out.println(
"
<tr><td>
"

+ headerName + "</td><td>"

);


out.println(request.getHeader(headerName) + "</td><td>"

);


}


out.println(
"
</table>
\
n</body></html>
"
);


}

}

25


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Request Headers

26


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 doesn’t 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


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 it’s 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 <session
-
config>

28


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Using the state management methods

String un = request.getParameter("username");

request.getSession().setAttribute("user", un);




String un=(String)request.getSession().getAttribute("user");

30


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

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 servlet’s response

31


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Examples of Request Dispatching

RequestDispatcher rd =


request.getRequestDispatcher("oracleconnection");

rd.include(request, response);


String status =


(String)request.getSession().getAttribute("status");


if (status.equalsIgnoreCase("OK"))

{


response.sendRedirect("connection_established.html");

}

else

{


rd = request.getRequestDispatcher("viewerror");


rd.forward(request, response);

}

32


J2EE Enterprise Architecture


Enterprise Applications CE00465
-
M

Examples of Request Dispatching


oracleconnection is the name of a servlet, OracleConnection.java


Specified in web.xml

<servlet>


<servlet
-
name>oracleconnection</servlet
-
name>


<servlet
-
class>entapps.OracleConnection</servlet
-
class>


</servlet>

<servlet
-
mapping>


<servlet
-
name>oracleconnection</servlet
-
name>


<url
-
pattern>/oracleconnection</url
-
pattern>


</servlet
-
mapping>


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.