Tutorial for building J2EE Applications using JBOSS and ECLIPSE

advertisement
J2EE and more – by Rinat Gotsulsky
J2EEServlet, JSP;
JDBC;
JavaBeans
Table of contents:
Introduction
Java Servlet
A Servlet's Life Cycle
Session Management
JavaServer Pages
JavaBeans
Web Application Models
Accessing Databases with JDBC
A little bit on related tools
Final
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Introduction
A web application is a web site whose contents are generated dynamically before being sent to the
browser.
HTTP is the protocol that allows web servers and browsers to exchange data over the web. It is a
request and response protocol. The client requests a file and the server responds to the request. HTTP
uses reliable TCP connections.
J2EE is a specification that defines the contract between applications and the container
- Servlets/JSP application architecture
Client
Servlets
JSP pages
DataBase
Web container
(Small to medium-size applications use this design model)
- J2EE application architecture
Servlets
JSP pages
Client
DataBase
Enterprise
Bean
EJB
container
)Especially useful for large enterprise applications that need scalability)
Web container- its runtime environment that have specific API's defined for the JSP and Servlets. A
J2EE application never directly interacts with other J2EE components; all these interactions are
controlled and managed by the container.
To use the container, we need to provide the application components and a deployment descriptor,
which declares to the container the application components and what role those components are to be
used.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Java Servlet
Servlets are programs that run on a Web server and build Web pages. Building Web pages on the fly
is useful (and commonly done) for a number of reasons:



The Web page is based on data submitted by the user. For example the results pages from
search engines are generated this way and programs that process orders for e-commerce sites
do this as well.
The data changes frequently. For example, a weather-report or news headlines page might
build the page dynamically.
The Web page uses information from corporate databases or other such sources. For
example, one should use this for making a Web page at an on-line store that lists current
prices and number of items in stock.
The distinguishing feature that makes a java class a servlet is the fact that all servlets must implement
the javax.servlet.Servlet interface. This interface is the contract between the container and the servlet.
The methods of the javax.servlet.Servlet interface that all servlets must implement:
Method Name
Description
init()
Called by the container to initialize the servlet; any
initialization parameters should be processed here. This very
important method.
Called by the container to indicate to the servlet that the
servlet is being put out of commission.
Called by a container or a tool to get information on the
servlet. The return value is a string that may contain vendor
name, copyright notice, and so on
Called by a container to obtain the
javax.servlet.ServletConfig object associated with this servlet
instance. This object is passed into the servlet when init() is
called by the container.
This is the core servlet method. It is called by a container to
pass a request for a servlet to process. The servlet must
process the request and supply a response.
destroy ()
getServletInfo()
getServletConfig()
service()
.
So, the available packages are: javax.servlet and javax.servlet.http the first one contains basic classes
and interfaces that we can use to write servlets from the scratch. The second package,
javax.servlet.http, offers more advanced classes and interfaces that extend classes and interfaces from
the first package. It is much more convenient to program using the second package.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
The javax.servlet.http Package
The package contains a number of classes and interfaces that describe and define the contracts
between a servlet class running under the HTTP protocol and the runtime environment provided for an
instance of such a class by a conforming servlet container.
The classes and interfaces in this package derive from those in javax.servlet; however, the members of
the javax.servlet.http package are much richer and more convenient to use. In this package, the
HttpServlet class represents a servlet, extending javax.servlet.GenericServlet and bringing a great
number of methods of its own. The javax.servlet.http package also has interfaces that are equivalent to
javax.servlet.ServletRequest and javax.servlet.ServletResponse interfaces- the HttpServletRequest and
the HttpServletResponse, respectively. It is not a coincidence that HttpServletRequest extends the
javax.servlet.ServletRequest interface, and HttpServletResponse is derived from the
javax.servlet.ServletResponse interface. HTTPServlet class provides helper methods for handling
HTTP requests doGet (GET); doPost (POST); doPut, doDelete (rare); doTrace, doOptions (not
overridden).
The service() method dispatches the requests to the appropriate do* methods.
It specifies, in addition to the regular request and response, tracking client information and manages
the session. Session related methods in the HttpServlet class enable you to deal with user session.
A Servlet's Life Cycle
As I mention already the Servlet interface in the javax.servlet package is the source of all activities in
servlet programming and it is the central abstraction of the Java servlet technology.
The life cycle of a servlet is determined by three of its methods:
public void init(ServletConfig config) throws ServletException
Called by the web container after the servlet class has been instantiated. The web container calls this
method exactly once to indicate to the servlet that the servlet is being placed into service. The init
method must complete successfully before the servlet can receive any requests. You can override this
method to write initialization code that needs to run only once, such as loading a database driver,
initializing values, and so on. In other cases, you normally leave this method blank.
The init method is important also because the web container passes a ServletConfig object, which
contains the configuration values. These values can be specified in the deployment descriptor,
web.xml, within the servlet declaration element.
public void service (ServletRequest request, ServletResponse response)
throws ServletException, java.io.IOException
The service method is called by the web container after the servlet's init method to allow the servlet to
respond to a request. Servlets typically run inside multithreaded web containers that can handle
multiple requests concurrently. Therefore, service() must be written in a thread-safe manner and to be
aware to synchronize access to any shared resources, such as files, network connections, and the
servlet's class and instance variables. For example, if you open a file and write to that file from a
servlet, you need to remember that a different thread of the same servlet also can open the same file.
The web container passes a ServletRequest object and the ServletResponse object. The ServletRequest
object contains the client's request and the ServletResponse contains the servlet's response. These two
objects are important because they enable you to write custom code that determines how the servlet
services the client request. The service method throws a ServletException if an exception occurs that
interferes with the servlet's normal operation. The service method also can throw a
java.io.IOException if an input or output exception occurs during the execution of this method.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
public void destroy ()
The web container calls the destroy method before removing a servlet instance from service. This
normally happens when the web container is shut down or the web container needs some free memory.
This method is called only after all threads within the servlet's service method have exited or after a
timeout period has passed. After the web container calls this method, it will not call the service method
again on this servlet.
The destroy method gives the servlet an opportunity to clean up any resources that are being held (for
example, memory, file handles, and threads) and make sure that any persistent state is synchronized
with the servlet's current state in memory.
- Releasing the resources is the developer’s responsibility
Close database connections
Stop threads
- Other threads might be running service requests, so be sure to synchronize, and/or wait for them to
quit
Destroy can not throw an exception: use server-side logging with meaningful message to identify the
problem.
Servlet Architecture Overview
Classes UserServlet (overeide one or more of: doGet(), doPost(), service()..) extends
Class HttpServlet (doGet(), doPost(), service()…) extends
Class GenericServlet implement
Interface Servlet
Debugging servlets:
Start
Write/Edit
Java Servlet
code
Compile
Servlet
Deploy to
servlets
container
Test via
browser &
server
NO
Test OK?
Yes
Done
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
-Compiling and Installing a Servlet
To compile a servlet, you must first ensure that you have the JAR file containing all Servlet API
classes in the CLASSPATH environment variable. The JAR file is distributed with all web
containers. On a Windows platform, you include the JAR file in the CLASSPATH like this
(assuming Tomcat is installed in C:\Jakarta\jakarta-tomcat-5):
C:/> set CLASSPATH=C:\Jakarta\jakarta-tomcat-5\common\lib\servlet-api.jar;
%CLASSPATH%
- We must tell the container which Servlet to invoke when it receives a request for a specific URL.
We do this with <servlet> and <servlet-mapping> elements in the application deployment
descriptor (WEB-INF/web.xml) file:
<web-app>
...
<servlet>
<servlet-name>helloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloWorld</servlet-name>
<url-pattern>/hello/*</url-pattern>
</servlet-mapping>
...
</web-app>
The <servlet> element gives the servlet class a unique name, and the <servlet-mapping> element
links a URL pattern to the named servlet.
The Servlet 2.3 specification introduced two component types beside servlets:
Filters
A filter is a component that can delay a request targeted for a servlet, JSP page, or static page, as well
as the response before it's sent to the client. This makes it easy to centralize tasks that apply to all
requests, such as access control, logging, and charging for the content or the services offered by the
application. A filter has full access to the body and headers of the request and response, so it can also
perform various transformations. One example is compressing the response body if the AcceptEncoding request header indicates that the client can handle a compressed response.
A filter can be applied to either a specific servlet or to all requests matching a URL pattern, such as
URLs starting with the same path elements or having the same extension.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Listeners
Listeners allow your application to react to certain events. Prior to Servlet 2.3, you could handle only
session attribute binding events (triggered when an object was added or removed from a session).
You could do this by letting the object saved as a session attribute (using the
HttpSession.setAttribute( ) method) Implement the HttpSessionBindingListener interface.
With the new interfaces introduced in the 2.3 and 2.4 versions of the servlet specification, you can
create listeners for servlet context, session and request lifecycle events as well as session activation
and passivation events (used by a container that temporarily saves session state to disk or migrates a
session to another server). A session attribute event listener also makes it possible to deal with
attribute binding events for all sessions in one place, instead of placing individual listener objects in
each session.
The new types of listeners follow the standard Java event model. In other words, a listener is a class
that implements one or more of the listener interfaces. The interfaces define methods that correspond
to events. The listener class is registered with the container when the application starts and the
container then calls the event methods at the appropriate times.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Session Management
HTTP connections are initiated by a client browser that sends an HTTP request. The web server then
responds with an HTTP response and closes the connection. If the same client requests another
resource from the server, it must open another HTTP connection to the server. The server always
closes the connection as soon as it sends the response, whether or not the browser user needs some
other resource from the server. Putting this in a web perspective, because the web server always
disconnects after it responds to a request, the web server does not know whether a request comes
from a user who has just requested the first page or from a user who has requested nine other pages
before. As such, HTTP is said to be stateless.
The solution- The web server is forced to associate HTTP requests and client browsers.
Session management, also called session tracking, goes beyond simply remembering a user who has
successfully logged in. Anything that makes the application remember information that has been
entered or requested by the user can be considered session management. Session management does
not change the nature of HTTP statelessness—it simply provides a way around it.
By principle, you manage a user's session by performing the following to servlets/pages that need to
remember a user's state:
1. When the user requests a servlet, in addition to sending the response, the servlet also sends a
token or an identifier.
2. If the user does not come back with the next request for the same or a different servlet, that is
fine, the token or identifier is sent back to the server. Upon encountering the token, the next
servlet should recognize the identifier and can do a certain action based on the token. When
the servlet responds to the request, it also sends the same or a different token. This goes on
and on with all the servlets that need to remember a user's session.
There are four techniques for session management. They operate based on the same principle,
although what is passed and how it is passed is different from one to another. The techniques are as
follows:
1. URL rewriting
2. Hidden fields
3. Cookies
4. Session objects (the best one for us)
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
1. URL rewriting
Appends some extra data on the end of each URL that identifies the session, and the server can
associate that session identifier with data it has stored about that session. This is also an excellent
solution, and even has the advantage that it works with browsers that don't support cookies or where
the user has disabled cookies. However, it has most of the same problems as cookies, namely that the
server-side program has a lot of straightforward but tedious processing to do. In addition, you have to
be very careful that every URL returned to the user (even via indirect means like Location fields in
server redirects) has the extra information appended. And, if the user leaves the session and comes
back via a bookmark or link, the session information can be lost.
A name and a value are separated using an equal sign (=); a parameter name/value pair is separated
from another parameter name/value pair using the ampersand (&). When the user clicks the hyperlink,
the parameter name/value pairs will be passed to the server. From a servlet, you can use the
HttpServletRequest interface's getParameter method to obtain a parameter value. For instance, to
obtain the value of the second parameter, you write the following: request.getParameter(name2);
2. Hidden Fields
HTML forms have an entry that looks like the following: <INPUT
TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the
specified name and value are included in the GET or POST data. This can be used to store information
about the session. However, it has the major disadvantage that it only works if every page is
dynamically generated, since the whole point is that each session has a unique identifier.
3. Cookies
Use HTTP cookies to store information about a shopping session, and each subsequent connection can
look up the current session and then extract information about that session from some location on the
server machine. This is an excellent alternative, and is the most widely used approach. However, even
though servlets have a high-level and easy-to-use interface to cookies, there are still a number of
relatively tedious details that need to be handled:
-
Extracting the cookie that stores the session identifier from the other cookies (there may be many,
after all),
Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably
should be reset), and
Associating information on the server with the session identifier (there may be far too much
information to actually store it in the cookie, plus sensitive data like credit card numbers should
never go in cookies).
4. Session objects
Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level
interface built on top of cookies or URL-rewriting it enables very easily to create applications that
depend on individual user data.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Steps to using the Java Session API
1. Get the Session object from the HTTPRequest object
(HttpSession session = request.getSession()- each user is automatically assigned a unique
session ID, How does this sessionID get to the user?
If the browser supports cookies the servlet will automatically create a session cookie and store
the session ID within the cookie.
If the browser does not support cookies, the servlet will try to extract the session ID from the
URL.
2. Extract Data from the user’s Session Object
3. Extract information about the session object”
- E.g. when was the session created, session ID?
4. Add data to the user’s Session Object.
The Session object works like a Hash Map
Hash Map that enables you to store any type of Java object.
You can therefore store any number of keys and their associated values.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Example (track the number of visits for each unique visitor)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
import java.util.*;
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
HttpSession session = request.getSession(true);
String heading;
Integer accessCount = (Integer)session.getAttribute("accessCount");
if (accessCount == null) { // new user
accessCount = new Integer(0);
heading = "Welcome, Newcomer";
} else { // returning user
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
// Integer is an immutable (nonmodifiable) data structure. So, you can not modify the old one in-place.
//Instead you have to allocate a new one and redo setAttribute.
session.putAttribute("accessCount", accessCount);
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" +
"<H2>Information on Your Session: </H2>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Info Type<TH>Value\n" +
"<TR>\n" +
"<TD>ID\n" +
"<TD>" + session.getId() + "\n" +
"<TR>\n" +
"<TD>Creation Time\n" +
"<TD>" +
new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +
"<TD>Time of Last Access\n" +
"<TD>" +
new Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +
"<TD>Number of Previous Accesses\n" +
"<TD>" + accessCount + "\n" +
"</TR>"+
"</TABLE>\n" +
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
"</BODY></HTML>");
}
/** Handle GET and POST requests identically. */
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
JavaServer Pages
JSP is an extension of the servlet technology, and it is common practice to use both servlets and JSP
pages in the same web applications.
It allows web designers to build interactive web pages without getting into the deep details of the
Java language.
JavaServer Pages (JSP) lets us to separate the dynamic part of our pages from the static HTML. We
simply write the regular HTML in the normal manner, using whatever Web-page-building tools we
normally use. When a JSP page request is processed, the template text and dynamic content
generated by the JSP elements are merged, and the result is sent as the response to the browser.
Example to get a better feel for how the basic JSP elements work:
<html>
<html>
<head>
<head>
<title>What
<title>What Time
Time Is
Is It?</title>
It?</title>
</head>
</head>
<body>
<body>
<h3>You
<h3>You requested
requested this
this page
page on
on ::
<%=
<%=
new
new java.util.Date()
java.util.Date()
%>
%>
</h3>
</h3>
</body>
</body>
</html>
</html>
JSP’s display results only. Servlets handle the Java logic
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
JSP Elements
There are four types of JSP elements we can use: directive, action, and scripting. A new construct
added in JSP 2.0 is an Expression Language (EL) expression; this is a forth element type, even
though it's a bit different than the other three.
DirectiveUnlike other JSP elements, directives are not used to generate output directly. They are not part of
the logic within the JSP code. Rather, they are used to control some characteristics of a JSP page.
Directives may be used to give special instructions to the JSP container, telling it how to handle
certain aspects of JSP processing.
JSP directives can be found in almost every JSP page. Directives always appear as follows:
<%@ directive name [... one or more attributes...] %>
We can use three directives within a JSP page:
- The page directive (used to provide instructions to the container that pertain to the current JSP
page. From the perspective of the container, each JSP page (together with any included JSP
fragments at translation time) is a separate translation unit. Each JSP page in the same application
can have its own page directive, resulting in a different set of instructions for each translation unit.
The instructions are specified using the attributes of the page directive. Attributes of the page
directive are optional; the default values will be used if you do not specify them.
- The taglib directive (used to tell the container which tag library a specific JSP requires. It is also
used to assign a prefix that is used within the JSP page to identify tags from a specific tag library.
After receiving this information, the container must locate the code for these tag libraries and get
them ready for use by the JSP page).
- The include directive- the general usage form of this directive is as follows: <%@ include
file=”news.jsp” %>
Here the file attribute is specified using a relative URL. For example, the news.jsp file is in the same
directory as the JSP including it. This directive has only a single mandatory file attribute. This
directive tells the container to merge the content of other external files with the current JSP during
the translation phase.
Each of these directives can have a number of attributes. Each attribute gives different directions to
the container.
Action elements
Typically perform some action based on information that is required at the exact time the JSP page is
requested by a browser. An action can, for instance, access parameters sent with the request to do a
database lookup. It can also dynamically generate HTML, such as a table filled with information
retrieved from an external system. Action elements can be either standard or custom. A standard
action is dependably available in every JSP container that conforms to the JSP 2.0 standard. For
example, <jsp:useBean>, <jsp:getProperty>, <jsp:setProperty>, and <jsp:include> are standard
actions. A custom action is an action created using JSP’s tag extension mechanism.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Scripting elements
The need for scripting elements within JSP is typically driven by the requirements of an application.
Major application requirements that demand the use of scripting elements include the following:
-To provide control-flow for JSP execution
-To set, and subsequently access, variables that are local to the JSP page
-To render a value from a complex expression that involves Java objects
-To access properties of an arbitrary Java object
-To call methods of JavaBeans or other Java objects
It allows to add small pieces of code (typically Java code) in a JSP page, such as if statement to
generate different HTML depending on a certain condition. Like actions, they are also executed
when the page is requested. You should use scripting elements with extreme care: if you embed too
much code in your JSP pages, you will end up with the same kind of maintenance problems as with
servlets embedding HTML. We should adopt the JavaServer Pages Standard Tag Library and
Expression Language (EL) style (described later and which satisfies these requirements too) of
programming and avoid the use of scripting elements whenever possible.
Tags and Tags library provides additional functionality above and beyond that provided by the
standard actions and implicit objects of JSP. It's enables to create JSP without the need of scripting
elements (embedded Java language coding within a JSP).
Custom JSP tags are collected in a tag lib. To notify the JSP container of the location of the custom
tag, a special JSP tag (taglib directive) needs to be included:
<%@ taglib prefix="tags" tagdir=" /WEB-INF/tags" %>
JSTL (JSP Standard Tag Library) open source
It is a standard set of tags designed for use especially within JSP to perform most common Web
Application programming tasks. The set of tags includes conditional flow control, data output,
databases and more.
EL
EL was not part of the JSP standard prior to 2.0. One of the main reasons for creating EL was to
ensure that presentation-level JSP pages could be created without relying on scripting elements.
Unfortunately, experience has shown that the use of scripting elements in JSPs encourages
programming practices that may tightly couple the presentation (user interface) of an application to
its business logic, reducing its flexibility and scalability. This is a highly undesirable practice in the
creation of Web applications and services. So, ideally, JSPs should be created free of scripting
elements if at all possible.
The EL is inspired by JavaScript and by XPath (a language used to access pieces of an XML
document), but it is much more forgiving when a variable doesn't contain a value (null) and
performs more data-type conversions automatically. These features are important for a web
application, because the input is mostly in the form of request parameters, which are always text
values but often need to be used as numbers or Boolean values by the application. A web application
must also handle the absence of a parameter gracefully, and the EL makes provisions for this as well.
EL expressions are always evaluated at runtime, meaning that they are run as JSP is actually
executed (while processing an actual incoming request) and not at the time when the JSP is
processed by the JSP container.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
JavaBeans
A bean is just a Java class. There is no need to extend any base class or implement any interface. To
be a bean, however, a Java class must follow certain rules specified by the JavaBeans specification.
JavaBeans are useful to represent GUI controls and other property-based applications.
In an application that uses a servlet as a frontend for all business logic, the bean is typically created
by the business logic code and sent to the JSP page to include its contents in the response.
Using JavaBeans Components
A JavaBeans component is often used in JSP as the container for the dynamic content to be
displayed by a web page. It typically represents something specific, such as a person, a product, or a
shopping order. When JSP is combined with servlets, the bean can be created and initialized with
data by the servlet and passed to a JSP page that simply adds the bean's data to the response.
A bean class must have a no-argument constructor. This allows a tool to create any bean in a generic
fashion knowing just the class name.
The bean properties are accessed through getter and setter methods. A readable property has a getter
method; a writable property has a setter method. Depending on the combination of getter and setter
methods, a property is read-only, write-only, or read/write.
Finally, the bean class should implement the java.io.Serializable or the
java.io.Externalizable interface to allow a tool to save and restore the bean's state.
Web Application Models
MVC Design Model - Using this model makes for a flexible application architecture, in which
multiple presentations (Views) can be provided and easily modified, and changes in the business
rules or physical representation of the data (the Model) can be made without touching any of the user
interface code.
request
Servlets
(Controller)
Client Browser
response
JSP pages
(View)
JavaBean
(Model)
Business objects
Server
Possible role assignments
The combination of servlets and JSP is a powerful tool for developing well-structured applications
that are easy to maintain and extend as new requirements surface. Since a servlet is a regular Java
class, you can use the full power of the Java language to implement the request processing, using
standard Java development and debugging tools. JSP pages can then be used for what they are best
at: rendering the response by including information collected or generated by the servlets.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
A common combination of servlets and JSP is to use one servlet as the Controller (or front
component) for an application, with a number of JSP pages acting as Views. This approach lets you
develop the application in a more modular fashion, with the servlet acting as a gateway, dispatching
requests to specialized processing components and picking the appropriate JSP page for the response
based on success or failure.
Moving concerns about application policies to the new component types leaves the servlet with the
tasks that are purely in the Controller domain.
All requests are sent to the servlet acting as the Controller with an indication about what needs to be
done. The indication can be in the form of a request parameter or as a part of the URI path. As in the
pure JSP scenario, beans are used to represent the Model. The servlet either performs the requested
action itself or delegates it to individual processing classes per action. Depending on the outcome of
the processing, the Controller servlet picks an appropriate JSP page to generate a response to the
user (the View). For instance, if a request to delete a document in a document archive is executed
successfully, the servlet can pick a JSP page that shows the updated archive contents. If the request
fails, it can pick a JSP page that describes exactly why it failed.
Centralized Request Processing Using a Servlet
With a servlet as the common entry point for all application requests, you gain control over the page
flow of the application. The servlet can decide which type of response to generate depending on the
outcome of the requested action, such as returning a common error page for all requests that fail, or
different responses depending on the type of client making the request
When you use a servlet as a Controller, you must deal with the following basic requirements:


All processing requests must be passed to the single Controller servlet.
The servlet must be able to distinguish requests for different types of processing.
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
Accessing Databases with JDBC (the technology that enables database access and
manipulation)
The JDBC Core API is part of the Java 2, Standard Edition (J2SE) and takes the form of the classes
and interfaces in the java.sql package
The JDBC API is a set of classes and interfaces that allows a Java application to send SQL
statements to a database in a vendor-independent way. The API consists mostly of interfaces that
define the methods you use in your program. Database engine vendors and third parties provide
implementations of these interfaces for a specific database engine; such an implementation is called
a JDBC driver. This allows developing program in a database-independent way and connecting to a
specific database engine by plugging in the appropriate JDBC driver at deployment time.
The java.sql package
DriverManager ClassThe DriverManager class provides static methods for managing JDBC drivers. Each JDBC driver
you want to use must be registered with the DriverManager. The JDBC driver of the database to
which you want to connect is supplied either by the database vendor or a third party. You use
different JDBC drivers for different database servers
Driver InterfaceThe Driver interface is implemented by every JDBC driver class. The driver class itself is loaded and
registered with the DriverManager, and the DriverManager can manage multiple drivers for any
given connection request. In the case where there are multiple drivers registered, the DriverManager
will ask each driver in turn to try to connect to the target URL
Connection InterfaceThe Connection interface represents a connection to the database. An instance of the Connection
interface is obtained from the getConnection method of the DriverManager class.
Statement InterfaceYou use the statement interface method to execute an SQL statement and obtain the results that are
produced. The two most important methods of this interface are executeQuery and executeUpdate.
ResultSet InterfaceThe ResultSet interface represents a table-like database result set. A ResultSet object maintains a
cursor pointing to its current row of data. Initially, the cursor is positioned before the first row. The
following are some important methods of the ResultSet interface
PreparedStatement Interface
ResultSetMetaData Interface
Only the DriverManager is a class (part of the standard J2SE package); the rest are interfaces
implemented by each unique JDBC driver
The Driver implementation is the entry point to all the other interface implementations. When the
Driver is loaded, it registers itself with the DriverManager. When the JDBC application needs a
connection to a database, it asks the DriverManager for one, and the DriverManager asks each
registered Driver if it knows how to create connections for the requested database. When a Driver
replies "yes," the DriverManager asks it for a Connection on the application's behalf; the Driver
attempts to create one and return it to the application.
The Connection is another core JDBC type. Through the Connection instance, the JDBC
application can create Statement instances of different types. The main Statement type can execute
Created on 1/1/2006 9:36 AM
J2EE and more – by Rinat Gotsulsky
a plain SQL statement, such as SELECT, UPDATE, or DELETE. When a SELECT statement is
executed, the result is returned as an instance of ResultSet. The ResultSet has methods for
navigating the result rows and asking for the column values in the current row.
Steps to Getting to the Database
This section explains what it takes to access a database and manipulate data in it.
Before you can manipulate data in a database, you need to connect to that database server. After you
get the connection, you can communicate with the database server. You can send an SQL query to
retrieve data from a table, update records, insert new records, or delete data you no longer need. You
also can do more than manipulate data: You can invoke a stored procedure, create a table, and more.
Accessing a database with JDBC can be summarized in the following six steps:
1. Load the driver
2. Establish the Connection
3. Create a Statement object
4. Execute a query
5. Process the result
6. Close the connection
Application
Driver
Manager
Driver
DBMS
DriverManager is provided by Java Software as part of the Java 2 Platform
Drivers are provided by DBMS vendors
The application creates a driver instance and registers it with the DriverManager.
The DriverManager tells the driver to connect to the DB
The DriverManager keeps track of registered driver instances and their connections to DB’s.
The Driver “talks” to a particular DB through the connection
Created on 1/1/2006 9:36 AM
DBM
Appli
Drive
Scatio
r
J2EE and more – by Rinat Gotsulsky
Mana
n A little bit on related tools:
ger - Version Control systems, such as CVS, enable the tracking of different versions of the code are
essential for us.
- Build tools such as Ant help automate the software build and deploy process.
- Unit testing tools such as JUnit are essential for us.
- Performance and load testing can be automated using tools such as jMaster
- Logging tools- adding a log statement to the application is a common way to debug or to trace the
behavior of along running Web application. But by doing it we affects the application performance,
increases the code size and turning on/off often requires changing the Web Application code. There
are Logging frameworks such as Log4j and Java Logging.
- Servlets available as open called Apache Struts project. It's probably the most popular framework
for integration with JSP. It assists application developers in implementing MVC Model 2
architecture in their J2EE applications.
It provides:
 Various validation techniques
 Flexibility to interact with the model layer
 Configuration infrastructure for everything from the Controller to database connections
 JSP custom tags to integrate with the framework
 Application flow control
 Resource bundles
 A highly configurable servlet
 Support for a modular design, making it easier to maintain and extend the application to
handle new types of requests
 Support for mapping of symbolic page names to the real URIs, making it easier to change the
site organization and control flow if needed
 A time-tested solution, actively supported by the Struts community, so you can focus on your
application instead of framework development
Final
There is a lot of stuff on J2EE. You can find a number of books on each subject.
So this is only a taste.
A few useful links:
http://java.sun.com/j2ee/1.4/docs/api/index.html
(Javax.servlet.http and Javax.servlet.jsp)
http://www.tusc.com.au/tutorial/html
(Tutorial for building J2EE Applications using JBOSS and ECLIPSE)
http://struts.apache.org
Latest version of JSTL that is designed to work with Tomcat 5, Servlets 2.4, and JSP 2.0 is JSTL
open source:
http://jakarta.apache.org/taglibs/doc/standard-doc/intro.html
Good Luck!
Created on 1/1/2006 9:36 AM
Download