Complete Java&J2 EE
Complete Java&J2 EE
Abstraction: Showing the essential and hiding the non-Essential is known as Abstraction.
Encapsulation: The Wrapping up of data and functions into a single unit is known as
Encapsulation.
Encapsulation is the term given to the process of hiding the implementation details of
the object. Once an object is encapsulated, its implementation details are not immediately
accessible any more. Instead they are packaged and are only indirectly accessed via the
interface of the object.
Inheritance: is the Process by which the Obj of one class acquires the properties of Objs
another Class.
A reference variable of a Super Class can be assign to any Sub class derived from the
Super class.
Inheritance is the method of creating the new class based on already existing class ,
the new class derived is called Sub class which has all the features of existing class and its
own, i.e sub class.
Adv: Re-usability of code , accessibility of variables and methods of the Base class by the
Derived class.
Polymorphism: The ability to take more that one form, it supports Method Overloading &
Method Overriding.
Method overloading: When a method in a class having the same method name with
different arguments (diff Parameters or Signatures) is said to be Method Overloading. This
is Compile time Polymorphism.
o Using one identifier to refer to multiple items in the same scope.
Method Overriding: When a method in a Class having same method name with same
arguments is said to be Method overriding. This is Run time Polymorphism.
o Providing a different implementation of a method in a subclass of the class that originally
defined the method.
1. In Over loading there is a relationship between the methods available in the same class
,where as in Over riding there is relationship between the Super class method and Sub
class method.
2. Overloading does not block the Inheritance from the Super class , Where as in
Overriding blocks Inheritance from the Super Class.
3. In Overloading separate methods share the same name, where as in Overriding Sub
class method replaces the Super Class.
4. Overloading must have different method Signatures , Where as Overriding methods
must have same Signatures.
Dynamic dispatch: is a mechanism by which a call to Overridden function is resolved at
runtime rather than at Compile time , and this is how Java implements Run time
Polymorphism.
Dynamic Binding : Means the code associated with the given procedure call is not known
until the time of call the call at run time. (it is associated with Inheritance &
Polymorphism).
Bite code: Is a optimized set of instructions designed to be executed by Java-run time
system, which is called the Java Virtual machine (JVM), i.e. in its standard form, the JVM is
an Interpreter for byte code.
JIT- is a compiler for Byte code, The JIT-Complier is part of the JVM, it complies byte code
into executable code in real time, piece-by-piece on demand basis.
Final classes : String, Integer , Color, Math
Abstract class : Generic servlet, Number class
1
o variable:An item of data named by an identifier . Each variable has a type,such as int
or Object,and a scope
o class variable :A data item associated with a particular class as a whole--not with
particular instances of the class. Class variables are defined in class definitions. Also
called a static field. See also instance variable.
o instance variable :Any item of data that is associated with a particular object. Each
instance of a class has its own copy of the instance variables defined in the class. Also
called a field. See also class variable.
o local variable :A data item known within a block, but inaccessible to code outside the
block. For example, any variable defined within a method is a local variable and can't be
used outside the method.
o class method :A method that is invoked without reference to a particular object. Class
methods affect the class as a whole, not a particular instance of the class. Also called a
static method. also instance method.
o instance method :Any method that is invoked with respect to an instance of a class.
Also called simply a method. See also class method.
Interface : Interfaces can be used to implement the Inheritance relationship between the
non-related classes that do not belongs to the same hierarchy, i.e. any Class and any
where in hierarchy. Using Interface, you can specify what a class must do but not how it
does.
A class can implement more than one Interface.
An Interface can extend one or more interfaces, by using the keyword extends.
All the data members in the interface are public, static and Final by default.
An Interface method can have only Public, default and Abstract modifiers.
An Interface is loaded in memory only when it is needed for the first time.
A Class, which implements an Interface, needs to provide the implementation of all the
methods in that Interface.
If the Implementation for all the methods declared in the Interface are not provided , the
class itself has to declare abstract, other wise the Class will not compile.
If a class Implements two interface and both the Intfs have identical method declaration, it
is totally valid.
If a class implements two interfaces both have identical method name and argument list,
but different return types, the code will not compile.
An Interface cant be instantiated. Intf Are designed to support dynamic method resolution
at run time.
An interface can not be native, static, synchronize, final, protected or private.
The Interface fields cant be Private or Protected.
A Transient variables and Volatile variables can not be members of Interface.
The extends keyword should not used after the Implements keyword, the Extends must
always come before the Implements keyword.
A top level Interface can not be declared as static or final.
If an Interface species an exception list for a method, then the class implementing the
interface need not declare the method with the exception list.
If an Interface cant specify an exception list for a method, the class cant throw an
exception.
The general form of Interface is
Access interface name {
return-type method-name1(parameter-list);
type final-varname1=value;
}
-----------------------
Marker Interfaces : Serializable, Clonable, Remote, EventListener,
Java.lang is the Package of all classes and is automatically imported into all Java Program
Interfaces: Clonable , Comparable, Runnable
2
Abstract Class : Abstract classes can be used to implement the inheritance relationship
between the classes that belongs same hierarchy.
Classes and methods can be declared as abstract.
Abstract class can extend only one Class.
If a Class is declared as abstract , no instance of that class can be created.
If a method is declared as abstract, the sub class gives the implementation of that class.
Even if a single method is declared as abstract in a Class , the class itself can be declared
as abstract.
Abstract class have at least one abstract method and others may be concrete.
In abstract Class the keyword abstract must be used for method.
Abstract classes have sub classes.
Combination of modifiers Final and Abstract is illegal in java.
Abstract Class means - Which has more than one abstract method which doesnt have
method body but at least one of its methods need to be implemented in derived Class.
The general form of abstract class is :
abstract type name (parameter list);
The Number class in the java.lang package represents the abstract concept of
numbers. It makes sense to model numbers in a program, but it doesn't make sense to
create a generic number object.
Difference Between Interfaces And Abstract class ?
o All the methods declared in the Interface are Abstract, where as abstract class must have
atleast one abstract method and others may be concrete.
o In abstract class keyword abstract must be used for method, where as in Interface we
need not use the keyword for methods.
o Abstract class must have Sub class, where as Interface cant have sub classes.
o An abstract class can extend only one class, where as an Interface can extend more than
one.
What are access specifiers and access modifiers ?
Accesss specifiers Access modifiers
Public Public
Protected Abstract
Private Final
Static
Volatile
Constant
Synchronized
Transient
Native
Public : The Variables and methods can be access any where and any package.
Protected : The Variables and methods can be access same Class, same Package & sub
class.
Private : The variable and methods can be access in same class only.
Same class - Public, Protected, and Private
Same-package & subclass - Public, Protected
Same Package & non-sub classes - Public, Protected
Different package & Sub classes - Public, Protected
Different package & non- sub classes - Public
Identifiers : are the Variables that are declared under particular Data-type.
Literals: are the values assigned to the Identifiers.
3
Static : access modifier. Signature: Variable-Static int b; Method- static void math(int
x)
When a member is declared as Static, it can be accessed before calling any objects of its
class are created and without reference to any object. Eg : main(),it must call before any
object exit.
Static can be applied to Inner classes, Variables and Methods.
Local variables cant be declared as static.(Local and instance variables both are not equal)
A static method can access only static Variables. and they cant refer to this or super in
any way.
Static methods cant be abstract.
A static method may be called without creating any instance of the class.
Only one instance of static variable will exit any amount of class instances.
Final : access modifier
All the Variables, methods and classes can be declared as Final.
Classes declared as final class cant be sub classed.
Method s declared as final cant be over ridden.
If a Variable is declared as final, the value contained in the Variable cant be changed.
Static final variable must be assigned in to a value in static initialized block.
Transient : access modifier
Answer: A transient variable is a variable that may not be serialized. If you
don't want some field to be serialized, you can mark that field transient or
static.
int j = 0;
void _jspService() {}
}
Declarations (<%! %>)
Used to declare class scope variables or methods
<%! int j = 0; %>
Gets declared at class- level scope in the generated servlet
int j = 0;
void _jspService() {}
}
52
JSP to Servlet Translation
<%@ page import="javax.ejb.*,javax.naming.*,java.rmi.* ,java.util.*" %>
<HTML><HEAD><TITLE>Hello.jsp</TITLE></HEAD><BODY>
<% String checking = null;
String name = null;
checking = request.getParameter("catch");
if (checking != null) {
name = request.getParameter("name");%>
<b> Hello <%=name%>
<% } %>
<FORM METHOD='POST' action="Hello.jsp">
<table width="500" cellspacing="0" cellpadding="3" border="0">
<caption>Enter your name</caption>
<tr><td><b>Name</b></td><td><INPUT size="20" maxlength="20"
TYPE="text" NAME="name"></td></tr>
</table>
<INPUT TYPE='SUBMIT' NAME='Submit' VALUE='Submit'>
<INPUT TYPE='hidden' NAME='catch' VALUE='yes'>
</FORM></BODY></HTML>
Generated Servlet
public void _jspService(HttpServletRequest request ,
HttpServletResponse response)
throws ServletException ,IOException {
out.write("<HTML><HEAD><TITLE>Hello.jsp</TITLE></HEAD><BODY>" );
String checking = null;
String name = null;
checking = request.getParameter("catch");
if (checking != null) {
name = request.getParameter("name");
out.write("\r\n\t\t<b> Hello " );
out.print(name);
out.write("\r\n\t\t" );
}
out.write("\r\n\t\t<FORM METHOD='POST' action="
+"\"Hello.jsp\">\r\n\t\t\t<table width=\"500\" cell..
}
}
Tags & Tag Libraries
What Is a Tag Library?
JSP technology has a set of pre- defined tags
<jsp: useBean />
These are HTML like but
have limited functionality
Can define new tags
Look like HTML
Can be used by page authors
Java code is executed when tag is encountered
Allow us to keep Java code off the page
Better separation of content and logic
53
May Have Tags To
Process an SQL command
Parse XML and output HTML
Automatically call into an EJB component (EJB technology- based component)
Get called on every request to initialize script variables
Iterate over a ResultSet and display the output in an HTML table
Primary Tag Classes (javax.servlet.jsp.tagext.Tag)
implements
Simple Tag Example :
<%@ taglib uri=/WEB-INF/mylib.tld prefix=test %>
<html><body bgcolor=white>
<test:hello name=Robert />
</body> </html>
public class HelloTag extends TagSupport {
private String name = World;
public void setName(String name) { this.name = name; }
public int doEndTag() { pageContext.getOut().println(Hello + name); }
}
mylib.tld
<taglib>
<tag><name>hello</name>
<tagclass>com.pramati.HelloTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute><name>name</name></attribute>
</tag>
</taglib>
How Tag Handler methods are invoked :
<prefix:tagName
attr1=value1 ------------ setAttr1(value1)
attr2=value2 ------------ setAttr2(value2)
> ------------ doStartTag()
This tags's body
</ prefix:tagName>------------ doEndTag()
Implementation of JSP page will use the tag handler for each action on page.
Summary
The JSP specification is a powerful system for creating structured web content
JSP technology allows non- programmers to develop dynamic web pages
54
BodyTag
Interface
BodyTagSupport
class
JSP technology allows collaboration between programmers and page designers when building
web applications
JSP technology uses the Java programming language as the script language
The generated servlet can be managed by directives
JSP components can be used as the view in the MVC architecture
Authors using JSP technology are not necessarily programmers using Java technology
Want to keep Java code off a JSP Page
Custom actions (tag libraries) allow the use of elements as a replacement for Java code
What is JSP- JavaServer Pages ?
JavaServer Pages. A server-side technology, JavaServer pages are an extension to the
Java servlet technology that was developed by Sun. JSPs have dynamic scripting capability
that works in tandem with HTML code, separating the page logic from the static elements --
the actual design and display of the page. Embedded in the HTML page, the Java source
code and its extensions help make the HTML more functional, being used in dynamic
database queries, for example. JSPs are not restricted to any specific platform or server.
Jsp contains both static and dynamic resources at run time.Jsp extends web server
functionalities
What are advantages of JSP
whenever there is a change in the code, we dont have to recompile the jsp. it automatically
does the compilation. by using custom tags and tag libraries the length of the java code is
reduced.
What is the difference between include directive & jsp:include action
include directive (): if the file includes static text if the file is rarely changed (the JSP
engine may not recompile the JSP if this type of included file is modified) .
if you have a common code snippet that you can reuse across multiple pages (e.g. headers
and footers)
jsp:include : for content that changes at runtime .to select which content to render at
runtime (because the page and src attributes can take runtime expressions) for files that
change often JSP:includenull
What are Custom tags. Why do you need Custom tags. How do you create Custom
tag
1) Custom tags are those which are user defined.
2) Inorder to separate the presentation logic in a separate class rather than keeping in jsp
page we can use custom tags.
3) Step 1 : Build a class that implements the javax.servlet.jsp.tagext.Tag interface as
follows. Compile it and place it under the web-inf/classes directory (in the appropriate
package structure).
package examples;
import java.io.*; //// THIS PROGRAM IS EVERY TIME I MEAN WHEN U REFRESH THAT
PARTICULAR CURRENT DATE THIS CUSTOM TAG WILL DISPLAY
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class ShowDateTag implements Tag {
private PageContext pageContext;
private Tag parent;
public int doStartTag() throws JspException {
return SKIP_BODY; }
public int doEndTag() throws JspException {
try {
pageContext.getOut().write("" + new java.util.Date());
} catch (IOException ioe) {
throw new JspException(ioe.getMessage());
}
return EVAL_PAGE; }
55
public void release() {
}
public void setPageContext(PageContext page) {
this.pageContext = page;
}
public void setParent(Tag tag) {
this.parent = tag;
}
public Tag getParent() {
return this.parent; } }
Step 2:Now we need to describe the tag, so create a file called taglib.tld and place it under
the web-inf directory."http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 1.0 1.1
myTag http://www.mycompany.com/taglib My own tag library showDate
examples.ShowDateTag Show the current date
Step 3 : Now we need to tell the web application where to find the custom tags, and how
they will be referenced from JSP pages. Edit the web.xml file under the web-inf directory
and insert the following XML fragement.http://www.mycompany.com/taglib /WEB-
INF/taglib.tld
Step 4 : And finally, create a JSP page that uses the custom tag.Now restart the server
and call up the JSP page! You should notice that every time the page is requested, the
current date is displayed in the browser. Whilst this doesn't explain what all the various
parts of the tag are for (e.g. the tag description, page context, etc) it should get you
going. If you use the tutorial (above) and this example, you should be able to grasp what's
going on! There are some methods in context object with the help of which u can get the
server (or servlet container) information.
Apart from all this with the help of ServletContext u can implement
ServletContextListener and then use the get-InitParametermethod to read context
initialization parameters as the basis of data that will be made available to all servlets and
JSP pages.
What are the implicit objects in JSP & differences between them
There are nine implicit objects in JSP.
1. request : The request object represents httprequest that are trigged by service( )
invocation. javax.servlet
2. response:The response object represents the servers response to request.
javax.servlet
3. pageContext : The page context specifies the single entry point to many of the page
attributes and is the convient place to put shared data.
javax.servlet.jsp.pagecontext
4. session : the session object represents the session created by the current user.
javax.Servlet.http.HttpSession
5. application : the application object represents servlet context , obtained from servlet
configaration . javax.Servlet.ServletContext
6. out : the out object represents to write the out put stream .
javax.Servlet.jsp.jspWriter
7. Config :the config object represents the servlet config interface from this page,and has
scope attribute. javax.Servlet.ServletConfig
8. page : The object is th eInstance of page implementation servlet class that are
processing the current request.
java.lang.Object
9. exception : These are used for different purposes and actually u no need to create
these objects in JSP. JSP container will create these objects automatically.
56
java.lang.Throwable
You can directly use these objects.
Example:
If i want to put my username in the session in JSP.
JSP Page: In the about page, i am using session object. But this session object is not
declared in JSP file, because, this is implicit object and it will be created by the jsp
container.
If u see the java file for this jsp page in the work folder of apache tomcat, u will find these
objects are created.
What is jsp:usebean. What are the scope attributes & difference between these
attributes
page, request, session, application
What is difference between scriptlet and expression
With expressions in JSP, the results of evaluating the expression are converted to a
string and directly included within the output page. Typically expressions are used to
display simple values of variables or return values by invoking a bean's getter methods. JSP
expressions begin within tags and do not include semicolons:
But scriptlet can contain any number of language statements, variable or method
declarations, or expressions that are valid in the page scripting language. Within scriptlet
tags, you can declare variables or methods to use later in the file, write expressions valid in
the page scripting language,use any of the JSP implicit objects or any object declared with
a scriplet.
What is Declaration
Declaration is used in JSP to declare methods and variables.To add a declaration, you
must use the sequences to enclose your declarations.
How do you connect to the database from JSP
To be precise to connect jdbc from jsp is not good idea ofcourse if ur working on
dummy projects connecting to msaccess u can very well use the same connection objects
and methods in ur scriplets and define ur connection object in init() method.
But if its real time u can use DAO design patterns which is widely used. for example u
write all ur connection object and and sql quires in a defiened method later use transfer
object [TO ]which is all ur fields have get/set methods and call it in business object[BO] so
DAO is accessd with precaution as it is the crucial. Finally u define java bean which is a
class holding get/set method implementing serialization thus the bean is called in the jsp.
So never connect to jdbc directly from client side since it can be hacked by any one to get
ur password or credit card info.
How do you call stored procedures from JSP
By using callable statement we can call stored procedures and functions from the database.
How do you restrict page errors display in the JSP page
set isErrorPage=false
How do you pass control from one JSP page to another
we can forward control to aother jsp using jsp action tags forward or incllude
How do I have the JSP-generated servlet subclass my own custom servlet class,
instead of the default?
One should be very careful when having JSP pages extend custom servlet classes as
opposed to the default one generated by the JSP engine. In doing so, you may lose out on
any advanced optimization that may be provided by the JSPengine. In any case, your new
superclass has to fulfill the contract with the JSPengine by: Implementing the HttpJspPage
interface, if the protocol used is HTTP, or implementing JspPage otherwise Ensuring that all
the methods in the Servlet interface are declared final Additionally, your servlet superclass
also needs to do the following:
57
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation
error. Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends="packageName.ServletName" %<
How does a servlet communicate with a JSP page?
The following code snippet shows how a servlet instantiates a bean and initializes it with
FORM data posted by a browser. The bean is then placed into the request, and the call is
then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for
downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse response)
{
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
. . .
} }
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default
request scope via the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"/
jsp:getProperty name="fBean" property="name" /
jsp:getProperty name="fBean" property="addr" /
jsp:getProperty name="fBean" property="age" /
jsp:getProperty name="fBean" property="personalizationInfo" /
Is there a way I can set the inactivity lease period on a per-session basis?
Typically, a default inactivity lease period for all sessions is set within your JSPengine
admin screen or associated properties file. However, if your JSP engine supports the Servlet
2.1 API, you can manage the inactivity lease period on a per-session basis. This is done by
invoking the HttpSession.setMaxInactiveInterval() method, right after the session has been
created.
For example:
<% session.setMaxInactiveInterval(300); %>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set
in seconds.
How can I set a cookie and delete a cookie from within a JSP page?
A cookie, mycookie, can be deleted using the following scriptlet:
<%
//creating a cookie
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
58
response.addCookie(killMyCookie);
%>
How can I declare methods within my JSP page?
You can declare methods for use within your JSP page as declarations. The methods can
then be invoked within any other methods you declare, or within JSP scriptlets and
expressions.
Do note that you do not have direct access to any of the JSP implicit objects like request,
response, session and so forth from within JSP methods. However, you should be able to
pass any of the implicit JSP variables as parameters to the methods you declare.
For example:
<%!
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<%
out.print("Hi there, I see that you are coming in from ");
%>
<%= whereFrom(request) %>
Another Example:
file1.jsp:
<%@page contentType="text/html"%>
<%!
public void test(JspWriter writer) throws IOException{
writer.println("Hello!");
}
%>
file2.jsp
<%@include file="file1.jsp"%>
<html>
<body>
<%test(out);% >
</body>
</html>
How can I enable session tracking for JSP pages if the browser has disabled
cookies?
We know that session tracking uses cookies by default to associate a session
identifier with a unique user. If the browser does not support cookies, or if cookies are
disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially
includes the session ID within the link itself as a name/value pair. However, for this to be
effective, you need to append the session ID for each and every link that is part of your
servlet response. Adding the session ID to a link is greatly simplified by means of of a
couple of methods: response.encodeURL() associates a session ID with a given URL, and if
you are using redirection, response.encodeRedirectURL() can be used by giving the
redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine
whether cookies are supported by the browser; if so, the input URL is returned unchanged
since the session ID will be persisted as a cookie.
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp,
interact with each other. Basically, we create a new session within hello1.jsp and place an
object within this session. The user can then traverse to hello2.jsp by clicking on the link
present within the page.Within hello2.jsp, we simply extract the object that was earlier
placed in the session and display its contents. Notice that we invoke the encodeURL() within
hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is
automatically appended to the URL, allowing hello2.jsp to still retrieve the session object.
Try this example first with cookies enabled. Then disable cookie support, restart the
59
brower, and try again. Each time you should see the maintenance of the session across
pages. Do note that to get this example to work with cookies disabled at the browser, your
JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session="true" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href='<%=url%>'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());
How do I use a scriptlet to initialize a newly instantiated bean?
A jsp:useBean action may optionally have a body. If the body is specified, its contents will
be automatically invoked when the specified bean is instantiated. Typically, the body will
contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although
you are not restricted to using those alone. The following example shows the "today"
property of the Foo bean initialized to the current date when it is instantiated. Note that
here, we make use of a JSP expression within the jsp:setProperty action.
<jsp:useBean id="foo" class="com.Bar.Foo" >
<jsp:setProperty name="foo" property="today"
value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date())
%>"/ >
<%-- scriptlets calling bean setter methods go here --%>
</jsp:useBean >
How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have uncaught runtime
exceptions automatically forwarded to an error processing page.
For example:
<%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught exception is encountered
during request processing. Within error.jsp, if you indicate that it is an error-processing
page, via the directive:
<%@ page isErrorPage="true" %>
the Throwable object describing the exception may be accessed within the error page via
the exception implicit object.
Note: You must always use a relative URL as the value for the errorPage attribute.
How do I prevent the output of my JSP or Servlet pages from being cached by the
browser?
You will need to set the appropriate HTTP header attributes to prevent the dynamic
content output by the JSP page from being cached by the browser. Just execute the
following scriptlet at the beginning of your JSP pages to prevent them from being cached at
the browser. You need both the statements to take care of some of the older browser
versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
How do I use comments within a JSP page
60
You can use "JSP-style" comments to selectively block out code while debugging or
simply to comment your scriptlets. JSP comments are not visible at the client.
For example:
<%-- the scriptlet is now commented out
<%
out.println("Hello World");
%> --%>
You can also use HTML-style comments anywhere within your JSP page. These comments
are visible at the client. For example:
<!-- (c) 2004 javagalaxy.com -->
Of course, you can also use comments supported by your JSP scripting language within
your scriptlets. For example, assuming Java is the scripting language, you can have:
<%
//some comment
/**
yet another comment **/ %>
Can I stop JSP execution while in the midst of processing a request?
Yes. Preemptive termination of request processing on an error condition is a good way
to maximize the throughput of a high-volume JSP engine. The trick (asuming Java is your
scripting language) is to use the return statement when you want to terminate further
processing. For example, consider:
<% if (request.getParameter("foo") != null) {
// generate some html or update bean property
} else {
/* output some error message or provide redirection back to the input form after creating a
memento bean updated with the 'valid' form elements that were input. This bean can now
be used by the previous form to initialize the input elements that were valid then, return
from the body of the _jspService() method to terminate further processing */
return;
}
%>
Is there a way to reference the "this" variable within a JSP page?
Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns
a reference to the servlet generated by the JSP page.
How do I perform browser redirection from a JSP page?
You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect("http://www.exforsys.com/path/error.html");
You can also physically alter the Location HTTP header attribute, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
You can also use the: <jsp:forward page="/newpage.jsp" /> Also note that you can only
use this before any output has been sent to the client. I beleve this is the case with the
response.sendRedirect() method as well. If you want to pass any paramateres then you can
pass using
<jsp:forward page="/servlet/login"> <jsp:param name="username"
value="HARI" /> </jsp:forward>
How do I include static files within a JSP page?
Answer Static resources should always be included using the JSP include directive. This
way, the inclusion is performed just once during the translation phase. The following
example shows the syntax:
<%@ include file="copyright.html" %>
61
Do note that you should always supply a relative URL for the file attribute. Although you
can also include static resources using the action, this is not advisable as the inclusion is
then performed for each and every request.
What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however,
override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful
for allocating resources like database connections, network connections, and so forth for
the JSP page. It is good programming practice to free any allocated resources within
jspDestroy().
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a
JSP page and are typically declared as JSP declarations:
<%! public void jspInit() {
. . . }
%>
<%!
public void jspDestroy() {
. . . }
%>
Can a JSP page process HTML FORM data?
Yes. However, unlike servlets, you are not required to implement HTTP-protocol specific
methods like doGet() or doPost() within your JSP page. You can obtain the data for the
FORM input elements via the request implicit object within a scriptlet or expression as:
<%
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intValue();
%>
or
<%= request.getParameter("item") %>
How do I mix JSP and SSI #include?
If you're just including raw HTML, use the #include directive as usual inside your .jsp file.
<!--#include file="data.inc"-->
But it's a little trickier if you want the server to evaluate any JSP code that's inside the
included file. If your data.inc file contains jsp code you will have to use <%@
vinclude="data.inc" %> The <!--#include file="data.inc"--> is used for including non-JSP
files.
How can I implement a thread-safe JSP page?
You can make your JSPs thread-safe by having them implement the SingleThreadModel
interface. This is done by adding the directive
<%@ page isThreadSafe="false" % > within your JSP page.
How do I include static files within a JSP page?
Static resources should always be included using the JSP include directive. This way, the
inclusion is performed just once during the translation phase. The following example shows
the syntax: Do note that you should always supply a relative URL for the file attribute.
Although you can also include static resources using the action, this is not advisable as the
inclusion is then performed for each and every request.
How do you prevent the Creation of a Session in a JSP Page and why?
By default, a JSP page will automatically create a session for the request if one does not
exist. However, sessions consume resources and if it is not necessary to maintain a session,
one should not be created. For example, a marketing campaign may suggest the reader
visit a web page for more information. If it is anticipated that a lot of traffic will hit that
page, you may want to optimize the load on the machine by not creating useless sessions.
What is the page directive is used to prevent a JSP page from automatically
creating a session:
62
<%@ page session="false">
Is it possible to share an HttpSession between a JSP and EJB? What happens
when I change a value in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method, only if all objects in
session are serializable.This has to be consider as "passed-by-value", that means that it's
read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to
the HttpSession of the Servlet Container.The "pass-byreference" can be used between EJBs
Remote Interfaces, as they are remote references. While it IS possible to pass an
HttpSession as a parameter to an EJB object, it is considered to be "bad practice (1)" in
terms of object oriented design. This is because you are creating an unnecessary coupling
between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level
of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which
carries with it a bunch of http semantics), create a class that acts as a value object (or
structure) that holds all the data you need to pass back and forth between front-end/back-
end. Consider the case where your ejb needs to support a non-http-based client. This
higher level of abstraction will be flexible enough to support it. (1) Core J2EE design
patterns (2001)
Can a JSP page instantiate a serialized bean?
No problem! The useBean action specifies the beanName attribute, which can be used
for indicating a serialized bean. For example:
<jsp:useBean id="shop" type="shopping.CD" beanName="CD" />
<jsp:getProperty name="shop" property="album" />
A couple of important points to note. Although you would have to name your serialized file
"filename.ser", you only indicate "filename" as the value for the beanName attribute. Also,
you will have to place your serialized file within the WEB-INFjspbeans directory for it to be
located by the JSP engine.
Can you make use of a ServletOutputStream object from within a JSP page?
No. You are supposed to make use of only a JSPWriter object (given to you in the form of
the implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered
version of the stream object returned by response.getWriter(), although from an
implementational perspective, it is not. A page author can always disable the default
buffering for any page using a page directive as:
<%@ page buffer="none" %>
Can we implements interface or extends class in JSP?
No , we can't implements interface or extends class in JSP
What are the steps required in adding a JSP Tag Libraries?
1. Create a TLD file and configure the required class Information.
2. Create the Java Implementation Source extending the JSP Tag Lib Class (TagSupport).
3. Compile and package it as loosed class file or as a jar under lib folder in Web Archive File
for Class loading.
4. Place the TLD file under the WEB-INF folder.
5. Add reference to the tag library in the web.xml file.
63
Struts 1.1
1. Introduction to MVC
a. Overview of MVC Architecture 63
b. Applying MVC in Servlets and JSP
c. View on JSP
d. JSP Model 1 Architecture
e. JSP Model 2 Architecture
f. Limitation in traditional MVC approach
g. MVC Model 2 Architecture
h. The benefits
i. Application flow
2. Overview of Struts Framework 66
a. Introduction to Struts Framework
b. Struts Architecture
c. Front Controller Design Pattern
d. Controller servlet - ActionServlet
e. Action objects
f. Action Form objects
g. Action mappings
h. Configuring web.xml file and struts-config.xml file
3. Struts View components
a. Composite View
b. Building page from templates
c. Jsp:include Vs struts template mechanism
d. Bean tags
e. Html tags
f. Logic tags
g. Template tags
4. Struts Controller components
a. Action classes
b. ActionServlet
c. Struts data source
5. Advanced Struts
a. Accessing Application Resource File
b. Use of Tokens
c. Accessing Indexed properties
d. Forward Vs Redirect
e. Dynamic creating Action Forwards
6. Struts 1.1
a. DynaActionForm
b. DynaValidatorActionForm
64
Validating Input Data
Declarative approach
Using Struts Validator
Configuring the Validator
Specifying validation rules
Client side validation
c. Plugins
d. I18N (InternationalizatioN)
Specifying a resource bundle
Generating Locale specific messages
e. Tiles
Introduction to MVC(Model View Controler)
Struts : Struts is an open source framework from Jakartha Project designed for developing
the web applications with Java SERVLET API and Java Server Pages Technologies.Struts
conforms the Model View Controller design pattern. Struts package provides unified
reusable components (such as action servlet) to build the user interface that can be applied
to any web connection. It encourages software development following the MVC design
pattern.
Overview of MVC Architecture
The MVC design pattern divides applications into three components:
The Model maintains the state and data that the application represents .
The View allows the display of information about the model to the user.
The Controller allows the user to manipulate the application .
In Struts, the view is handled by JSPs and presentation components, the model is
represented by Java Beans and the controller uses Servlets to perform its action.
65
Users
UI Components
UI Process Components
Service Interfaces
Business
Workflows
Business
Components
Business
Entities
Data Access Logic
Components
Service Agents
Data Sources
Services
S
e
c
u
r
i t
y
O
p
e
r
a
t i
o
n
a
l
m
a
n
a
g
e
m
e
n
t
C
o
m
m
u
n
i
c
a
t i
o
n
By developing a familiar Web-based shopping cart, you'll learn how to utilize the Model-
View-Controller (MVC) design pattern and truly separate presentation from content when
using Java Server Pages.
Applying MVC in Servlets and JSP
Many web applications are JSP-only or Servlets-only. With JSP, Java code is
embedded in the HTML code; with Servlets the Java code calls println methods to generate
the HTML code. Both approaches have their advantages and drawbacks; Struts gathers
their strengths to get the best of their association.
Below you will find one example on registration form processing using MVC in Servlets and
JSP:
1. In the above application Reg.jsp act as view accepts I/P from client and submits to
Controller Servlet.
2. Controller Servlet validates the form data, if valid, stores the data into DB
3. Based on the validation and DB operations Controller Servlet decides to respond
either Confirm.jsp or Error.jsp to clients browser.
4. When the Error.jsp is responded, the page must include all the list of errors with
detailed description.
5. The above shown application architecture is the model for MVC.
6. IF MVC Model 2 wants to be implemented in your application business logic and
model operations must be separated from controller program.
View on JSP
The early JSP specification follows two approaches for building applications using
JSP technology. These two approaches are called as JSP Model 1 and JSP Model 2
architectures.
JSP Model 1 Architecture
66
-___
'
_
Confirm.jsp Error.jsp
If()
If()
Controller Servlet
Reg JSP
User
In Model 1 architecture the JSP page is alone responsible for processing the
incoming request and replying back to the client. There is still separation of presentation
from content, because all data access is performed using beans. Although the JSP Model 1
Architecture is more suitable for simple applications, it may not be desirable for complex
implementations.
JSP Model 2 Architecture - MVC
The Model 2 Architecture is an approach for serving dynamic content, since it
combines the use of both Servlets and JSP. It takes advantages of the predominant
strengths of both technologies, using JSP to generate the presentation layer and Servlets to
perform process-intensive tasks. Here servlet acts as controller and is in charge of request
processing and the creation of any beans or objects used by the JSP as well as deciding
depending on the users actions, which JSP page to forward the request to. Note that there
is no processing logic within the JSP page itself; it is simply responsible for retrieving any
objects or beans that may have been previously created by the servlet, and extracting the
dynamic content from that servlet for insertion within static templates.
Limitation in traditional MVC approach
The main limitation in the traditional MVC approach is, in that there is no separation
of business logic (validation/ conditions/ anything related to business rules) from controller
(is responsible for controlling of the application flow by using static/dynamic request
dispatcher.
MVC Model 2 Architecture is Model View Controller
67
Browser
Servlet
Controller
Servlet
Validator
Servlet
Model
JSP
View
Beans
1 2
3 4
5
6
7
User
Pass
Login
o o Client submits login request to servlet application
o o Servlet application acts as controller it first decides to request validator another
servlet program which is responsible for not null checking (business rule)
o o control comes to controller back and based on the validation response, if the
response is positive, servlet controller sends the request to model
o o Model requests DB to verify whether the database is having the same user
name and password, If found login operation is successful
o o Beans are used to store if any data retrieved from the database and kept into
HTTPSession
o o Controller then gives response back to response JSP (view) which uses the
bean objects stored in HTTPSession object
o o and prepares presentation response on to the browser
Overview of Struts Framework
Introduction to Struts Framework
The goal of this project is to provide an open source framework for building Java web
applications. The core of the Struts framework is a flexible control layer based on standard
technologies like Java Servlets, JavaBeans, Resource Bundles, and XML, as well as various
Jakarta Commons packages. Struts encourages application architectures based on the
Model 2 approach, a variation of the classic Model-View-Controller (MVC) design
paradigm.
Struts provides its own Controller component and integrates with other technologies to
provide the Model and the View.
For the Model, Struts can interact with standard data access technologies, like JDBC and
EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object
Relational Bridge.
For the View, Struts works well with Java Server Pages, including JSTL and JSF, as well
as Velocity Templates, XSLT, and other presentation systems.
For Controller, ActionServlet and ActionMapping - The Controller portion of the
application is focused on receiving requests from the client deciding what business logic
function is to be performed, and then delegating responsibility for producing the next
phase of the user interface to an appropriate View component. In Struts, the primary
component of the Controller is a servlet of class ActionServlet. This servlet is
configured by defining a set of ActionMappings. An ActionMapping defines a path that is
matched against the request URI of the incoming request, and usually specifies the fully
qualified class name of an Action class. Actions encapsulate the business logic, interpret
the outcome, and ultimately dispatch control to the appropriate View component to
create the response.
The Struts project was launched in May 2000 by Craig McClanahan to provide a standard
MVC framework to the Java community. In July 2001.
In the MVC design pattern, application flow is mediated by a central Controller. The
Controller delegates requests - in our case, HTTP requests - to an appropriate handler. The
handlers are tied to a Model, and each handler acts as an adapter between the request and
the Model. The Model represents, or encapsulates, an application's business logic or state.
Control is usually then forwarded back through the Controller to the appropriate View. The
forwarding can be determined by consulting a set of mappings, usually loaded from a
68
database or configuration file. This provides a loose coupling between the View and Model,
which can make applications significantly easier to create and maintain.
Struts Architecture
Front Controller
Context
The presentation-tier request handling mechanism must control and coordinate
processing of each user across multiple requests. Such control mechanisms may be
managed in either a centralized or decentralized manner.
Problem
The system requires a centralized access point for presentation-tier request handling to
support the integration of system services, content retrieval, view management, and
navigation. When the user accesses the view directly without going through a centralized
mechanism,
Two problems may occur:
Each view is required to provide its own system services, often resulting in duplicate
code.
View navigation is left to the views. This may result in commingled view content and
view navigation.
Additionally, distributed control is more difficult to maintain, since changes will often need
to be made in numerous places.
Solution :
Use a controller as the initial point of contact for handling a request. The controller
manages the handling of the request, including invoking security services such as
authentication and authorization, delegating business processing, managing the choice of
an appropriate view, handling errors, and managing the selection of content creation
strategies.
The controller provides a centralized entry point that controls and manages Web
request handling. By centralizing decision points and controls, the controller also helps
reduce the amount of Java code, called scriptlets, embedded in the JavaServer Pages (JSP)
page.
Centralizing control in the controller and reducing business logic in the view promotes
code reuse across requests. It is a preferable approach to the alternative-embedding code
in multiple views-because that approach may lead to a more error-prone, reuse-by-copy-
and-paste environment.
Typically, a controller coordinates with a dispatcher component. Dispatchers are
responsible for view management and navigation. Thus, a dispatcher chooses the next view
for the user and vectors control to the resource. Dispatchers may be encapsulated within
the controller directly or can be extracted into a separate component.
While the Front Controller pattern suggests centralizing the handling of all
requests, it does not limit the number of handlers in the system, as does a Singleton. An
69
Request.jsp
Action
Servlet
Struts-
config.xml
ActionForm
Action
Success
Response
Error
Response
J2EE
Component
(EJB)
DB
Legac
y code
application may use multiple controllers in a system, each mapping to a set of distinct
services.
Structure
Below figure represents the Front Controller class diagram pattern.
Figure: Front Controller class diagram
Participants and Responsibilities
Below figure shows the sequence diagram representing the Front Controller pattern. It
depicts how the controller handles a request.
Figure: Front Controller sequence diagram
Controller : The controller is the initial contact point for handling all requests in the system. The
controller may delegate to a helper to complete authentication and authorization of a user
or to initiate contact retrieval.
Dispatcher :
A dispatcher is responsible for view management and navigation, managing the
choice of the next view to present to the user, and providing the mechanism for vectoring
control to this resource.
70
A dispatcher can be encapsulated within a controller or can be a separate component
working in coordination. The dispatcher provides either a static dispatching to the view or a
more sophisticated dynamic dispatching mechanism.
The dispatcher uses the Request Dispatcher object (supported in the servlet
specification) and encapsulates some additional processing.
Helper :
A helper is responsible for helping a view or controller complete its processing. Thus,
helpers have numerous responsibilities, including gathering data required by the view and
storing this intermediate model, in which case the helper is sometimes referred to as a
value bean. Additionally, helpers may adapt this data model for use by the view. Helpers
can service requests for data from the view by simply providing access to the raw data or
by formatting the data as Web content.
A view may work with any number of helpers, which are typically implemented as
JavaBeans components (JSP 1.0+) and custom tags (JSP 1.1+). Additionally, a helper may
represent a Command object, a delegate, or an XSL Transformer, which is used in
combination with a stylesheet to adapt and convert the model into the appropriate form.
View : A view represents and displays information to the client. The view retrieves information from
a model. Helpers support views by encapsulating and adapting the underlying data model
for use in the display.
Controller Servlet Action Servlet
For those of you familiar with MVC architecture, the ActionServlet represents the C - the
controller. The job of the controller is to:
process user requests,
determine what the user is trying to achieve according to the request,
pull data from the model (if necessary) to be given to the appropriate view,
and
select the proper view to respond to the user.
The Struts controller delegates most of this grunt work to the Request Processor and Action
classes.
In addition to being the front controller for your application, the ActionServlet
instance also is responsible for initialization and clean-up of resources. When the controller
initializes, it first loads the application config corresponding to the "config" init-param. It
then goes through an enumeration of all init-param elements, looking for those elements
who's name starts with config/. For each of these elements, Struts loads the configuration
file specified by the value of that init-param, and assigns a "prefix" value to that module's
ModuleConfig instance consisting of the piece of the init-param name following "config/".
For example, the module prefix specified by the init-param config/foo would be "foo".
This is important to know, since this is how the controller determines which module will be
given control of processing the request. To access the module foo, you would use a URL
like:
http://localhost:8080/myApp/foo/someAction.do
For each request made of the controller, the method process(HttpServletRequest,
HttpServletResponse) will be called. This method simply determines which module should
service the request and then invokes that module's RequestProcessor's process method,
passing the same request and response.
Request Processor :
The RequestProcessor is where the majority of the core processing occurs for each
request. Let's take a look at the helper functions the process method invokes in-turn:
processPath
Determine the path that invoked us. This will be used later to retrieve
an ActionMapping.
processLocale
Select a locale for this request, if one hasn't already been selected, and
place it in the request.
processContent
Set the default content type (with optional character encoding) for all
responses if requested.
processNoCache
If appropriate, set the following response headers: "Pragma", "Cache-
Control", and "Expires".
processPreprocess This is one of the "hooks" the RequestProcessor makes available for
subclasses to override. The default implementation simply returns
71
true. If you subclass RequestProcessor and override
processPreprocess you should either return true (indicating process
should continue processing the request) or false (indicating you have
handled the request and the process should return)
processMapping Determine the ActionMapping associated with this path.
processRoles
If the mapping has a role associated with it, ensure the requesting
user is has the specified role. If they do not, raise an error and stop
processing of the request.
processActionForm
Instantiate (if necessary) the ActionForm associated with this mapping
(if any) and place it into the appropriate scope.
processPopulate Populate the ActionForm associated with this request, if any.
processValidate
Perform validation (if requested) on the ActionForm associated with
this request (if any).
processForward
If this mapping represents a forward, forward to the path specified by
the mapping.
processInclude
If this mapping represents an include, include the result of invoking the
path in this request.
processActionCreate
Instantiate an instance of the class specified by the current
ActionMapping (if necessary).
processActionPerfor
m
This is the point at which your action's perform or execute method will
be called.
processForwardConfi
g
Finally, the process method of the RequestProcessor takes the
ActionForward returned by your Action class, and uses to select the
next resource (if any). Most often the ActionForward leads to the
presentation page that renders the response.
Action class
The Action class defines two methods that could be executed depending on your servlet
environment:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
ServletRequest request,
ServletResponse response)
throws Exception;
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception;
Since the majority of Struts projects are focused on building web applications, most
projects will only use the "HttpServletRequest" version. A non-HTTP execute() method has
been provided for applications that are not specifically geared towards the HTTP protocol.
The goal of an Action class is to process a request, via its execute method, and return an
ActionForward object that identifies where control should be forwarded (e.g. a JSP, Tile
definition, Velocity template, or another Action) to provide the appropriate response. In the
MVC/Model 2 design pattern, a typical Action class will often implement logic like the
following in its execute method:
Validate the current state of the user's session (for example, checking that
the user has successfully logged on). If the Action class finds that no logon exists,
the request can be forwarded to the presentation page that displays the username
and password prompts for logging on. This could occur because a user tried to enter
an application "in the middle" (say, from a bookmark), or because the session has
timed out, and the servlet container created a new one.
72
If validation is not complete, validate the form bean properties as needed. If
a problem is found, store the appropriate error message keys as a request attribute,
and forward control back to the input form so that the errors can be corrected.
Perform the processing required to deal with this request (such as saving a
row into a database). This can be done by logic code embedded within the Action
class itself, but should generally be performed by calling an appropriate method of a
business logic bean.
Update the server-side objects that will be used to create the next page of
the user interface (typically request scope or session scope beans, depending on
how long you need to keep these items available).
Return an appropriate ActionForward object that identifies the presentation
page to be used to generate this response, based on the newly updated beans.
Typically, you will acquire a reference to such an object by calling findForward on
either the ActionMapping object you received (if you are using a logical name local
to this mapping), or on the controller servlet itself (if you are using a logical name
global to the application).
In Struts 1.0, Actions called a perform method instead of the now-preferred execute
method. These methods use the same parameters and differ only in which exceptions they
throw. The elder perform method throws SerlvetException and IOException. The new
execute method simply throws Exception. The change was to facilitate the Declarative
Exception handling feature introduced in Struts 1.1.
The perform method may still be used in Struts 1.1 but is deprecated. The Struts 1.1
method simply calls the new execute method and wraps any Exception thrown as a
ServletException.
Action Form class
An ActionForm represents an HTML form that the user interacts with over one or more
pages. You will provide properties to hold the state of the form with getters and setters to
access them. ActionForms can be stored in either the session (default) or request scopes. If
they're in the session it's important to implement the form's reset method to initialize the
form before each use. Struts sets the ActionForm's properties from the request parameters
and sends the validated form to the appropriate Action's execute method.
When you code your ActionForm beans, keep the following principles in mind:
The ActionForm class itself requires no specific methods to be implemented.
It is used to identify the role these particular beans play in the overall architecture.
Typically, an ActionForm bean will have only property getter and property setter
methods, with no business logic.
The ActionForm object also offers a standard validation mechanism. If you
override a "stub" method, and provide error messages in the standard application
resource, Struts will automatically validate the input from the form (using your
method). See "Automatic Form Validation" for details. Of course, you can also
ignore the ActionForm validation and provide your own in the Action object.
Define a property (with associated getXxx and setXxx methods) for each field
that is present in the form. The field name and property name must match
according to the usual JavaBeans conventions (see the Javadoc for the
java.beans.Introspector class for a start on information about this). For example, an
input field named username will cause the setUsername method to be called.
Buttons and other controls on your form can also be defined as properties.
This can help determine which button or control was selected when the form was
submitted. Remember, the ActionForm is meant to represent your data-entry form,
not just the data beans.
Think of your ActionForm beans as a firewall between HTTP and the Action.
Use the validate method to ensure all required properties are present, and that they
contain reasonable values. An ActionForm that fails validation will not even be
presented to the Action for handling.
73
You may also place a bean instance on your form, and use nested property
references. For example, you might have a "customer" bean on your ActionForm,
and then refer to the property "customer.name" in your presentation page. This
would correspond to the methods customer.getName() and
customer.setName(string Name) on your customer bean. See the Tag Library
Developer Guides for more about using nested syntax with the Struts JSP tags.
Caution: If you nest an existing bean instance on your form, think about the
properties it exposes. Any public property on an ActionForm that accepts a single
String value can be set with a query string. It may be useful to place beans that can
affect the business state inside a thin "wrapper" that exposes only the properties
required. This wrapper can also provide a filter to be sure runtime properties are not
set to inappropriate values.
Action class Design guidelines
Remember the following design guidelines when coding Action classes:
Write code for a multi-threaded environment - The controller servlet creates only
one instance of your Action class, and uses this one instance to service all requests.
Thus, you need to write thread-safe Action classes. Follow the same guidelines you would
use to write thread-safe Servlets. Here are two general guidelines that will help you write
scalable, thread-safe Action classes:
o Only Use Local Variables - The most important principle that aids in thread-safe coding
is to use only local variables, not instance variables, in your Action class. Local
variables are created on a stack that is assigned (by your JVM) to each request thread, so
there is no need to worry about sharing them. An Action can be factored into several local
methods, so long as all variables needed are passed as method parameters. This assures
thread safety, as the JVM handles such variables internally using the call stack which is
associated with a single Thread.
o Conserve Resources - As a general rule, allocating scarce resources and keeping them
across requests from the same user (in the user's session) can cause scalability problems.
For example, if your application uses JDBC and you allocate a separate JDBC connection
for every user, you are probably going to run in some scalability issues when your site
suddenly shows up on Slashdot. You should strive to use pools and release resources (such
as database connections) prior to forwarding control to the appropriate View component --
even if a bean method you have called throws an exception.
Don't throw it, catch it! - Ever used a commercial website only to have a stack trace or
exception thrown in your face after you've already typed in your credit card number and
clicked the purchase button? Let's just say it doesn't inspire confidence. Now is your
chance to deal with these application errors - in the Action class. If your application
specific code throws expections you should catch these exceptions in your Action class, log
them in your application's log (servlet.log("Error message", exception)) and return
the appropriate ActionForward.
It is wise to avoid creating lengthy and complex Action classes. If you start to embed too
much logic in the Action class itself, you will begin to find the Action class hard to
understand, maintain, and impossible to reuse. Rather than creating overly complex Action
classes, it is generally a good practice to move most of the persistence, and "business
logic" to a separate application layer. When an Action class becomes lengthy and
procedural, it may be a good time to refactor your application architecture and move some
of this logic to another conceptual layer; otherwise, you may be left with an inflexible
application which can only be accessed in a web-application environment. Struts should be
viewed as simply the foundation for implementing MVC in your applications. Struts
provides you with a useful control layer, but it is not a fully featured platform for building
MVC applications, soup to nuts.
The MailReader example application included with Struts stretches this design principle
somewhat, because the business logic itself is embedded in the Action classes. This should
74
be considered something of a bug in the design of the example, rather than an intrinsic
feature of the Struts architecture, or an approach to be emulated. In order to demonstrate,
in simple terms, the different ways Struts can be used, the MailReader application does not
always follow best practices.
Action mapping implementation
In order to operate successfully, the Struts controller servlet needs to know several things
about how each request URI should be mapped to an appropriate Action class. The
required knowledge has been encapsulated in a Java class named ActionMapping, the most
important properties are as follows:
o type - Fully qualified Java class name of the Action implementation class used by this
mapping.
o name - The name of the form bean defined in the config file that this action will use.
o path - The request URI path that is matched to select this mapping. See below for
examples of how matching works and how to use wildcards to match multiple request
URIs.
o unknown - Set to true if this action should be configured as the default for this application,
to handle all requests not handled by another action. Only one action can be defined as a
default within a single application.
o validate - Set to true if the validate method of the action associated with this mapping
should be called.
o forward - The request URI path to which control is passed when this mapping is invoked.
This is an alternative to declaring a type property.
Writing Action Mappings
How does the controller servlet learn about the mappings you want? It would be possible
(but tedious) to write a small Java class that simply instantiated new ActionMapping
instances, and called all of the appropriate setter methods. To make this process easier,
Struts uses the Jakarta Commons Digester component to parse an XML-based description
of the desired mappings and create the appropriate objects initialized to the appropriate
default values. See the Jakarta Commons website for more information about the
Digester.
The developer's responsibility is to create an XML file named struts-config.xml and place
it in the WEB-INF directory of your application. This format of this document is described by
the Document Type Definition (DTD) maintained at
http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd. This chapter
covers the configuration elements that you will typically write as part of developing your
application. There are several other elements that can be placed in the struts-config file to
customize your application. See "Configuring Applications" for more about the other
elements in the Struts configuration file.
The controller uses an internal copy of this document to parse the configuration; an
Internet connection is not required for operation.
The outermost XML element must be <struts-config>. Inside of the <struts-config>
element, there are three important elements that are used to describe your actions:
<form-beans>
<global-forwards>
<action-mappings>
<form-beans>
This section contains your form bean definitions. Form beans are descriptors that are used
75
to create ActionForm instances at runtime. You use a <form-bean> element for each form
bean, which has the following important attributes:
name: A unique identifier for this bean, which will be used to reference it in
corresponding action mappings. Usually, this is also the name of the request or
session attribute under which this form bean will be stored.
type: The fully-qualified Java classname of the ActionForm subclass to use
with this form bean.
<global-forwards>
This section contains your global forward definitions. Forwards are instances of the
ActionForward class returned from an ActionForm's execute method. These map logical
names to specific resources (typically JSPs), allowing you to change the resource without
changing references to it throughout your application. You use a <forward> element for
each forward definition, which has the following important attributes:
name: The logical name for this forward. This is used in your ActionForm's
execute method to forward to the next appropriate resource. Example: homepage
path: The context relative path to the resource. Example: /index.jsp or
/index.do
redirect: True or false (default). Should the ActionServlet redirect to the
resource instead of forward?
<action-mappings>
This section contains your action definitions. You use an <action> element for each of the
mappings you would like to define. Most action elements will define at least the following
attributes:
path: The application context-relative path to the action.
type: The fully qualified java classname of your Action class.
name: The name of your <form-bean> element to use with this action
Other often-used attributes include:
parameter: A general-purpose attribute often used by "standard" Actions to
pass a required property.
roles: A comma-delimited list of the user security roles that can access this
mapping.
For a complete description of the elements that can be used with the action element,
see the Struts Configuration DTD and the ActionMapping documentation.
Action Mapping Example
Here's a mapping entry based on the MailReader example application. The MailReader
application now uses DynaActionForms. But in this example, we'll show a conventinal
ActionForm instead, to illustrate the usual workflow. Note that the entries for all the other
actions are left out:
<struts-config>
<form-beans>
<form-bean
name="logonForm"
type="org.apache.struts.webapp.example.LogonForm" />
</form-beans>
<global-forwards
type="org.apache.struts.action.ActionForward">
<forward
name="logon"
path="/logon.jsp"
redirect="false" />
</global-forwards>
<action-mappings>
<action
path ="/logon"
type ="org.apache.struts.webapp.example.LogonAction"
76
name ="logonForm"
scope ="request"
input ="/logon.jsp"
unknown="false"
validate="true" />
</action-mappings>
</struts-config>
First the form bean is defined. A basic bean of class
"org.apache.struts.webapp.example.LogonForm" is mapped to the logical name
"logonForm". This name is used as a request attribute name for the form bean.
The "global-forwards" section is used to create logical name mappings for commonly
used presentation pages. Each of these forwards is available through a call to your action
mapping instance, i.e. mapping.findForward("logicalName").
As you can see, this mapping matches the path /logon (actually, because the
MailReader example application uses extension mapping, the request URI you specify in a
JSP page would end in /logon.do). When a request that matches this path is received, an
instance of the LogonAction class will be created (the first time only) and used. The
controller servlet will look for a bean in request scope under key logonForm, creating and
saving a bean of the specified class if needed.
Optional but very useful are the local "forward" elements. In the MailReader example
application, many actions include a local "success" and/or "failure" forward as part of an
action mapping.
<!-- Edit mail subscription -->
<action
path="/editSubscription"
type="org.apache.struts.webapp.example.EditSubscriptionAction"
name="subscriptionForm"
scope="request"
validate="false">
<forward
name="failure"
path="/mainMenu.jsp"/>
<forward
name="success"
path="/subscription.jsp"/>
</action>
Using just these two extra properties, the Action classes are almost totally independent
of the actual names of the presentation pages. The pages can be renamed (for example)
during a redesign, with negligible impact on the Action classes themselves. If the names of
the "next" pages were hard coded into the Action classes, all of these classes would also
need to be modified. Of course, you can define whatever local forward properties makes
sense for your own application.
The Struts configuration file includes several other elements that you can use to customize
your application. See "Configuring Applications" for details.
Using Action Mapping for pages
Fronting your pages with ActionMappings is essential when using modules, since doing so is
the only way you involve the controller in the request -- and you want to! The controller
puts the application configuration in the request, which makes available all of your module-
specific configuration data (including which message resources you are using, request-
processor, datasources, and so forth).
The simplest way to do this is to use the forward property of the ActionMapping:
<action path="/view" forward="/view.jsp"/>
Configuring struts-config.xml file
The Building Controller Components chapter covered writing the form-bean
and action-mapping portions of the Struts configuration file. These elements usually play an
77
important role in the development of a Struts application. The other elements in Struts
configuration file tend to be static: you set them once and leave them alone.
These "static" configuration elements are:
controller
message-resources
plug-in
data-sources
Controller configuration
The <controller> element allows you to configure the ActionServlet. Many of the
controller parameters were previously defined by servlet initialization parameters in your
web.xml file but have been moved to this section of struts-config.xml in order to allow
different modules in the same web application to be configured differently. For full details
on available parameters see the struts-config_1_2.dtd or the list below.
bufferSize - The size (in bytes) of the input buffer used when processing file
uploads. [4096] (optional)
className - Classname of configuration bean.
[org.apache.struts.config.ControllerConfig] (optional)
contentType - Default content type (and optional character encoding) to be
set on each response. May be overridden by the Action, JSP, or other resource to
which the request is forwarded. [text/html] (optional)
forwardPattern - Replacement pattern defining how the "path" attribute of
a <forward> element is mapped to a context-relative URL when it starts with a slash
(and when the contextRelative property is false). This value may consist of any
combination of the following:
o $M - Replaced by the module prefix of this module.
o $P - Replaced by the "path" attribute of the selected <forward>
element.
o $$ - Causes a literal dollar sign to be rendered.
o $x - (Where "x" is any character not defined above) Silently
swallowed, reserved for future use.
If not specified, the default forwardPattern is consistent with the previous behavior
of forwards. [$M$P] (optional)
inputForward - Set to true if you want the input attribute of <action>
elements to be the name of a local or global ActionForward, which will then be
used to calculate the ultimate URL. Set to false to treat the input parameter of
<action> elements as a module-relative path to the resource to be used as the
input form. [false] (optional)
locale - Set to true if you want a Locale object stored in the user's session
if not already present. [true] (optional)
maxFileSize - The maximum size (in bytes) of a file to be accepted as a file
upload. Can be expressed as a number followed by a "K", "M", or "G", which are
interpreted to mean kilobytes, megabytes, or gigabytes, respectively. [250M]
(optional)
multipartClass - The fully qualified Java class name of the multipart request
handler class to be used with this module.
[org.apache.struts.upload.CommonsMultipartRequestHandler] (optional)
nocache - Set to true if you want the controller to add HTTP headers for
defeating caching to every response from this module. [false] (optional)
pagePattern - Replacement pattern defining how the page attribute of
custom tags using it is mapped to a context-relative URL of the corresponding
resource. This value may consist of any combination of the following:
o $M - Replaced by the module prefix of this module.
78
o $P - Replaced by the "path" attribute of the selected <forward>
element.
o $$ - Causes a literal dollar sign to be rendered.
o $x - (Where "x" is any character not defined above) Silently
swallowed, reserved for future use.
If not specified, the default pagePattern is consistent with the previous behavior of
URL calculation. [$M$P] (optional)
processorClass - The fully qualified Java class name of the
RequestProcessor subclass to be used with this module.
[org.apache.struts.action.RequestProcessor] (optional)
tempDir - Temporary working directory to use when processing file uploads.
[{the directory provided by the servlet container}]
This example uses the default values for several controller parameters. If you only want
default behavior you can omit the controller section altogether.
<controller
processorClass="org.apache.struts.action.RequestProcessor"
debug="0"
contentType="text/html"/>;
Message Resource configuration
Struts has built in support for internationalization (I18N). You can define one or more
<message-resources> elements for your webapp; modules can define their own resource
bundles. Different bundles can be used simultaneously in your application, the 'key'
attribute is used to specify the desired bundle.
className - Classname of configuration bean.
[org.apache.struts.config.MessageResourcesConfig] (optional)
factory - Classname of MessageResourcesFactory.
[org.apache.struts.util.PropertyMessageResourcesFactory] (optional)
key - ServletContext attribute key to store this bundle.
[org.apache.struts.action.MESSAGE] (optional)
null - Set to false to display missing resource keys in your application like
'???keyname???' instead of null. [true] (optional)
parameter - Name of the resource bundle. (required)
Example configuration:
<message-resources
parameter="MyWebAppResources"
null="false" />
This would set up a message resource bundle provided in the file
MyWebAppResources.properties under the default key. Missing resource keys would be
displayed as '???keyname???'.
PlugIn configuration
Struts PlugIns are configured using the <plug-in> element within the Struts configuration
file. This element has only one valid attribute, 'className', which is the fully qualified name
of the Java class which implements the org.apache.struts.action.PlugIn interface.
For PlugIns that require configuration themselves, the nested <set-property> element is
available.
This is an example using the Tiles plugin:
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<set-property
property="definitions-config"
value="/WEB-INF/tiles-defs.xml"/>
</plug-in>
DataSource configuration
Besides the objects related to defining ActionMappings, the Struts configuration may
contain elements that create other useful objects.
79
The <data-sources> section can be used to specify a collection of DataSources
[javax.sql.DataSource] for the use of your application. Typically, a DataSource represents a
connection pool to a database or other persistent store. As a convenience, the Struts
DataSource manager can be used to instantiate whatever standard pool your application
may need. Of course, if your persistence layer provides for its own connections, then you
do not need to specify a data-sources element.
Since DataSource implementations vary in what properties need to be set, unlike other
Struts configuration elements, the data-source element does not pre-define a slate of
properties. Instead, the generic set-property feature is used to set whatever properties
your implementation may require. Typically, these settings would include:
A driver class name
A url to access the driver
A description
And other sundry properties.
<data-source type="org.apache.commons.dbcp.BasicDataSource">
<!-- ... set-property elements ... -->
</data-source>
In Struts 1.2.0, the GenericDataSource has been removed, and it is recommended
that you use the Commons BasicDataSource or other DataSource implementation instead.
In practice, if you need to use the DataSource manager, you should use whatever
DataSource implementation works best with your container or database.
For examples of specifying a data-sources element and using the DataSource with an
Action,
The Struts configuration file
The Building Controller Components chapter covered writing the form-bean and
action-mapping portions of the Struts configuration file. These elements usually play an
important role in the development of a Struts application. The other elements in Struts
configuration file tend to be static: you set them once and leave them alone.
These "static" configuration elements are:
controller
message-resources
plug-in
data-sources
Controller Configuration
The <controller> element allows you to configure the ActionServlet. Many of the
controller parameters were previously defined by servlet initialization parameters in your
web.xml file but have been moved to this section of struts-config.xml in order to allow
different modules in the same web application to be configured differently. For full details
on available parameters see the struts-config_1_2.dtd or the list below.
bufferSize - The size (in bytes) of the input buffer used when processing file
uploads. [4096] (optional)
className - Classname of configuration bean.
[org.apache.struts.config.ControllerConfig] (optional)
contentType - Default content type (and optional character encoding) to be
set on each response. May be overridden by the Action, JSP, or other resource to
which the request is forwarded. [text/html] (optional)
forwardPattern - Replacement pattern defining how the "path" attribute of
a <forward> element is mapped to a context-relative URL when it starts with a slash
(and when the contextRelative property is false). This value may consist of any
combination of the following:
o $M - Replaced by the module prefix of this module.
o $P - Replaced by the "path" attribute of the selected <forward>
element.
o $$ - Causes a literal dollar sign to be rendered.
80
o $x - (Where "x" is any character not defined above) Silently
swallowed, reserved for future use.
If not specified, the default forwardPattern is consistent with the previous behavior
of forwards. [$M$P] (optional)
inputForward - Set to true if you want the input attribute of <action>
elements to be the name of a local or global ActionForward, which will then be
used to calculate the ultimate URL. Set to false to treat the input parameter of
<action> elements as a module-relative path to the resource to be used as the
input form. [false] (optional)
locale - Set to true if you want a Locale object stored in the user's session
if not already present. [true] (optional)
maxFileSize - The maximum size (in bytes) of a file to be accepted as a file
upload. Can be expressed as a number followed by a "K", "M", or "G", which are
interpreted to mean kilobytes, megabytes, or gigabytes, respectively. [250M]
(optional)
multipartClass - The fully qualified Java class name of the multipart request
handler class to be used with this module.
[org.apache.struts.upload.CommonsMultipartRequestHandler] (optional)
nocache - Set to true if you want the controller to add HTTP headers for
defeating caching to every response from this module. [false] (optional)
pagePattern - Replacement pattern defining how the page attribute of
custom tags using it is mapped to a context-relative URL of the corresponding
resource. This value may consist of any combination of the following:
o $M - Replaced by the module prefix of this module.
o $P - Replaced by the "path" attribute of the selected <forward>
element.
o $$ - Causes a literal dollar sign to be rendered.
o $x - (Where "x" is any character not defined above) Silently
swallowed, reserved for future use.
If not specified, the default pagePattern is consistent with the previous behavior of
URL calculation. [$M$P] (optional)
processorClass - The fully qualified Java class name of the
RequestProcessor subclass to be used with this module.
[org.apache.struts.action.RequestProcessor] (optional)
tempDir - Temporary working directory to use when processing file uploads.
[{the directory provided by the servlet container}]
This example uses the default values for several controller parameters. If you only
want default behavior you can omit the controller section altogether.
<controller
processorClass="org.apache.struts.action.RequestProcessor"
debug="0"
contentType="text/html"/>;
Message Resources Configuration
Struts has built in support for internationalization (I18N). You can define one or more
<message-resources> elements for your webapp; modules can define their own resource
bundles. Different bundles can be used simultaneously in your application, the 'key'
attribute is used to specify the desired bundle.
className - Classname of configuration bean.
[org.apache.struts.config.MessageResourcesConfig] (optional)
factory - Classname of MessageResourcesFactory.
[org.apache.struts.util.PropertyMessageResourcesFactory] (optional)
key - ServletContext attribute key to store this bundle.
[org.apache.struts.action.MESSAGE] (optional)
null - Set to false to display missing resource keys in your application like
'???keyname???' instead of null. [true] (optional)
81
parameter - Name of the resource bundle. (required)
Example configuration:
<message-resources parameter="MyWebAppResources" null="false" />
This would set up a message resource bundle provided in the file
MyWebAppResources.properties under the default key.
Missing resource keys would be displayed as '???keyname???'.
PlugIn Configuration
Struts PlugIns are configured using the <plug-in> element within the Struts configuration
file. This element has only one valid attribute, 'className', which is the fully qualified name
of the Java class which implements the org.apache.struts.action.PlugIn interface.
For PlugIns that require configuration themselves, the nested <set-property> element is
available.
This is an example using the Tiles plugin:
<plug-in className="org.apache.struts.tiles.TilesPlugin" >
<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/>
</plug-in>
Data Source Configuration
Besides the objects related to defining ActionMappings, the Struts configuration may
contain elements that create other useful objects.
The <data-sources> section can be used to specify a collection of DataSources
[javax.sql.DataSource] for the use of your application. Typically, a DataSource represents a
connection pool to a database or other persistent store. As a convenience, the Struts
DataSource manager can be used to instantiate whatever standard pool your application
may need. Of course, if your persistence layer provides for its own connections, then you
do not need to specify a data-sources element.
Since DataSource implementations vary in what properties need to be set, unlike other
Struts configuration elements, the data-source element does not pre-define a slate of
properties. Instead, the generic set-property feature is used to set whatever properties
your implementation may require. Typically, these settings would include:
A driver class name
A url to access the driver
A description
And other sundry properties.
<data-source type="org.apache.commons.dbcp.BasicDataSource">
<!-- ... set-property elements ... -->
</data-source>
In Struts 1.2.0, the GenericDataSource has been removed, and it is recommended that
you use the Commons BasicDataSource or other DataSource implementation instead. In
practice, if you need to use the DataSource manager, you should use whatever DataSource
implementation works best with your container or database.
For examples of specifying a data-sources element and using the DataSource with an
Action, see the Accessing a Database HowTo.
Configuring your application for modules
Very little is required in order to start taking advantage of the Struts module feature. Just
go through the following steps:
1. Prepare a config file for each module.
2. Inform the controller of your module.
3. Use actions to refer to your pages.
Module Configuration Files
Back in Struts 1.0, a few "boot-strap" options were placed in the web.xml file, and the bulk
of the configuration was done in a single struts-config.xml file. Obviously, this wasn't ideal
for a team environment, since multiple users had to share the same configuration file.
In Struts 1.1, you have two options: you can list multiple struts-config files as a
comma-delimited list, or you can subdivide a larger application into modules.
82
With the advent of modules, a given module has its own configuration file. This means each
team (each module would presumably be developed by a single team) has their own
configuration file, and there should be a lot less contention when trying to modify it.
Informing the Controller
In struts 1.0, you listed your configuration file as an initialization parameter to the
action servlet in web.xml. This is still done in 1.1, but it's augmented a little. In order to tell
the Struts machinery about your different modules, you specify multiple config initialization
parameters, with a slight twist. You'll still use "config" to tell the action servlet about your
"default" module, however, for each additional module, you will list an initialization
parameter named "config/module", where module is the name of your module (this gets
used when determining which URIs fall under a given module, so choose something
meaningful!). For example:
...
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/conf/struts-default.xml</param-value>
</init-param>
<init-param>
<param-name>config/module1</param-name>
<param-value>/WEB-INF/conf/struts-module1.xml</param-value>
</init-param>
...
This says I have two modules. One happens to be the "default" module, which has no
"/module" in it's name, and one named "module1" (config/module1). I've told the controller
it can find their respective configurations under /WEB-INF/conf (which is where I put all my
configuration files). Pretty simple!
(My struts-default.xml would be equivalent to what most folks call struts-config.xml. I just
like the symmetry of having all my Struts module files being named struts-<module>.xml)
If you'd like to vary where the pages for each module is stored, see the forwardPattern
setting for the Controller.
Switching Modules
There are two basic methods to switching from one module to another. You can either
use a forward (global or local) and specify the contextRelative attribute with a value of true,
or you can use the built-in org.apache.struts.actions.SwitchAction.
Here's an example of a global forward:
...
<struts-config>
...
<global-forwards>
<forward name="toModuleB"
contextRelative="true"
path="/moduleB/index.do"
redirect="true"/>
...
</global-forwards>
...
</struts-config>
You could do the same thing with a local forward declared in an ActionMapping:
...
<struts-config>
...
<action-mappings>
...
<action ... >
<forward name="success"
contextRelative="true"
path="/moduleB/index.do"
redirect="true"/>
83
</action>
...
</action-mappings>
...
</struts-config>
Finally, you could use org.apache.struts.actions.SwitchAction, like so:
...
<action-mappings>
<action path="/toModule"
type="org.apache.struts.actions.SwitchAction"/>
...
</action-mappings>
...
Now, to change to ModuleB, we would use a URI like this:
http://localhost:8080/toModule.do?prefix=/moduleB&page=/index.do
If you are using the "default" module as well as "named" modules (like "/moduleB"), you
can switch back to the "default" module with a URI like this:
http://localhost:8080/toModule.do?prefix=&page=/index.do
That's all there is to it! Happy module-switching!
The Web Application Deployment Descriptor
The final step in setting up the application is to configure the application deployment
descriptor (stored in file WEB-INF/web.xml) to include all the Struts components that are
required. Using the deployment descriptor for the example application as a guide, we see
that the following entries need to be created or modified.
Configure the Action Servlet Instance
Add an entry defining the action servlet itself, along with the appropriate initialization
parameters. Such an entry might look like this:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
The initialization parameters supported by the controller servlet are described below.
(You can also find these details in the Javadocs for the ActionServlet class.) Square
brackets describe the default values that are assumed if you do not provide a value for that
initialization parameter.
config - Context-relative path to the XML resource containing the configuration
information for the default module. This may also be a comma-delimited list of
configuration files. Each file is loaded in turn, and its objects are appended to the internal
data structure. [/WEB-INF/struts-config.xml].
WARNING - If you define an object of the same name in more than one configuration file, the
last one loaded quietly wins.
config/${module} - Context-relative path to the XML resource containing the
configuration information for the application module that will use the specified prefix (/$
{module}). This can be repeated as many times as required for multiple application
modules. (Since Struts 1.1)
convertNull - Force simulation of the Struts 1.0 behavior when populating forms. If set to
true, the numeric Java wrapper class types (like java.lang.Integer) will default to null
(rather than 0). (Since Struts 1.1) [false]
84
rulesets - Comma-delimited list of fully qualified classnames of additional
org.apache.commons.digester.RuleSet instances that should be added to the Digester
that will be processing struts-config.xml files. By default, only the RuleSet for the
standard configuration elements is loaded. (Since Struts 1.1)
validating - Should we use a validating XML parser to process the configuration file
(strongly recommended)? [true]
WARNING - Struts will not operate correctly if you define more than one <servlet>
element for a controller servlet, or a subclass of the standard controller servlet class. The
controller servlet MUST be a web application wide singleton.
Configure the Action Servlet Mapping
Note: The material in this section is not specific to Struts. The configuration of servlet
mappings is defined in the Java Servlet Specification. This section describes the most
common means of configuring a Struts application.
There are two common approaches to defining the URLs that will be processed by the
controller servlet -- prefix matching and extension matching. An appropriate mapping entry
for each approach will be described below.
Prefix matching means that you want all URLs that start (after the context path part) with a
particular value to be passed to this servlet. Such an entry might look like this:
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/do/*</url-pattern>
</servlet-mapping>
which means that a request URI to match the /logon path described earlier might look like
this:
http://www.mycompany.com/myapplication/do/logon
where /myapplication is the context path under which your application is deployed.
Extension mapping, on the other hand, matches request URIs to the action servlet based on
the fact that the URI ends with a period followed by a defined set of characters. For
example, the JSP processing servlet is mapped to the *.jsp pattern so that it is called to
process every JSP page that is requested. To use the *.do extension (which implies "do
something"), the mapping entry would look like this:
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
and a request URI to match the /logon path described earlier might look like this:
http://www.mycompany.com/myapplication/logon.do
WARNING - Struts will not operate correctly if you define more than one <servlet-
mapping> element for the controller servlet.
WARNING - If you are using the new module support in Struts 1.1, you should be aware
that only extension mapping is supported.
Configure the Struts Tag Libraries
Next, you must add an entry defining the Struts tag library.
The struts-bean taglib contains tags useful in accessing beans and their properties, as well
as defining new beans (based on these accesses) that are accessible to the remainder of
the page via scripting variables and page scope attributes. Convenient mechanisms to
create new beans based on the value of request cookies, headers, and parameters are also
provided.
The struts-html taglib contains tags used to create struts input forms, as well as other tags
generally useful in the creation of HTML-based user interfaces.
The struts-logic taglib contains tags that are useful in managing conditional generation of
output text, looping over object collections for repetitive generation of output text, and
application flow management.
The struts-tiles taglib contains tags used for combining various view components, called
"tiles", into a final composite view.
The struts-nested taglib is an extension of other struts taglibs that allows the use of nested
beans.
85
Below is how you would define all taglibs for use within your application. In practice, you
would only specify the taglibs that your application uses:
<taglib>
<taglib-uri>/tags/struts-bean
</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-html
</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-logic
</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-tiles
</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld
</taglib-location>
</taglib>
This tells the JSP system where to find the tag library descriptor for this library (in your
application's WEB-INF directory, instead of out on the Internet somewhere).
Configure the Struts Tag Libraries (Servlet 2.3)
Servlet 2.3 Users only: The Servlet 2.3 specification simplifies the deployment and
configuration of tag libraries. The instructions above will work on older containers as well as
2.3 containers (Struts only requires a servlet 2.2 container); however, if you're using a 2.3
container such as Tomcat 4.x, you can take advantage of a simplified deployment.
All that's required to install the struts tag libraries is to copy struts.jar into your /WEB-
INF/lib directory and reference the tags in your code like this:
<%@ taglib uri=http://struts.apache.org/tags-html prefix="html" %>
Note that you must use the full uri defined in the various struts tlds so that the
container knows where to find the tag's class files. You don't have to alter your web.xml file
or copy tlds into any application directories.
Add Struts Components To Your Application
To use Struts, you must copy the .tld files that you require into your WEB-INF directory,
and copy struts.jar (and all of the commons-*.jar files) into your WEB-INF/lib directory.
Struts Bean Tags
This tag library contains tags useful in accessing beans and their properties, as well as
defining new beans (based on these accesses) that are accessible to the remainder of the
page via scripting variables and page scope attributes. Convenient mechanisms to create
new beans based on the value of request cookies, headers, and parameters are also
provided.
Many of the tags in this tag library will throw a JspException at runtime when they are
utilized incorrectly (such as when you specify an invalid combination of tag attributes). JSP
allows you to declare an "error page" in the <%@ page %> directive. If you wish to process
the actual exception that caused the problem, it is passed to the error page as a request
attribute under key org.apache.struts.action.EXCEPTION.
86
If you are viewing this page from within the Struts Documentation Application (or online at
http://struts.apache.org/), you can learn more about using these tags in the Bean
Tags Developer's Guide.
Tag Name Description
cookie Define a scripting variable based on the value(s) of the specified request
cookie.
define Define a scripting variable based on the value(s) of the specified bean property.
header Load the response from a dynamic application request and make it available as a
bean
include Render an internationalized message string to the response.
message Expose a specified item from the page context as a bean.
page Define a scripting variable based on the value(s) of the specified request parameter.
parameter Load a web application resource and make it available as a bean.
resource Define a bean containing the number of elements in a Collection or Map.
size Expose a named Struts internal configuration object as a bean.
struts Render the value of the specified bean property to the current JspWriter.
Struts
The core of the Struts framework is a flexible control layer based on standard
technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various
Jakarta Commons packages. Struts encourages application architectures based on the
Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies
to provide the Model and the View. For the Model, Struts can interact with standard data
access technologies, like JDBC and EJB, as well as most any third-party packages, like
Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with
JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other
presentation systems.
The Struts framework provides the invisible underpinnings every professional web
application needs to survive. Struts helps you create an extensible development
environment for your application, based on published standards and proven design
patterns.
What is the difference between Struts 1.0 and Struts 1.1
The new features added to Struts 1.1 are 1. RequestProcessor class 2. Method
perform() replaced by execute() in Struts base Action Class 3. Changes to web.xml and
struts-config.xml 4.Declarative exception handling 5.Dynamic ActionForms 6.Plug-ins
7.Multiple Application Modules 8.Nested Tags 9.The Struts Validator 10.Change to the ORO
package 11.Change to Commons logging 12.Removal of Admin actions 13. Deprecation of
the GenericDataSource
Explain Struts navigation flow
A client requests a path that matches the Action URI pattern. The container passes the
request to the ActionServlet. If this is a modular application, the ActionServlet selects the
appropriate module. The ActionServlet looks up the mapping for the path. If the mapping
specifies a form bean, the ActionServlet sees if there is one already or creates one. If a
form bean is in play, the ActionServlet resets and populates it from the HTTP request. If the
mapping has the validate property set to true, it calls validate on the form bean. If it fails,
the servlet forwards to the path specified by the input property and this control flow ends.
If the mapping specifies an Action type, it is reused if it already exists or instantiated.
87
The Actions perform or execute method is called and passed the instantiated form
bean (or null). The Action may populate the form bean, call business objects, and do
whatever else is needed. The Action returns an ActionForward to the ActionServlet. If the
ActionForward is to another Action URI, we begin again; otherwise, its off to a display page
or some other resource. Most often, it is a JSP, in which case Jasper, or the equivalent (not
Struts), renders the page.
What is the difference between ActionForm and DynaActionForm
In struts 1.0, action form is used to populate the html tags in jsp using struts custom
tag.when the java code changes, the change in action class is needed. To avoid the chages
in struts 1.1 dyna action form is introduced.This can be used to develop using xml.The dyna
action form bloats up with the struts-config.xml based definetion.
What is DispatchAction
The DispatchAction class is used to group related actions into one class. DispatchAction
is an abstract class, so you must override it to use it. It extends the Action class.
It should be noted that you dont have to use the DispatchAction to group multiple actions
into one Action class.
You could just use a hidden field that you inspect to delegate to member() methods inside
of your action.
How to call ejb from Struts
use the Service Locator patter to look up the ejbs
Or You can use InitialContext and get the home interface.
What are the various Struts tag libraries
struts-html tag library - used for creating dynamic HTML user interfaces and forms.
struts-bean tag library - provides substantial enhancements to the basic capability
provided by .
struts-logic tag library - can manage conditional generation of output text, looping over
object collections for repetitive generation of output text, and application flow
management.
struts-template tag library - contains tags that are useful in creating dynamic JSP
templates for pages which share a common format.
What is the difference between ActionErrors and ActionMessages
The difference between the classes is zero -- all behavior in ActionErrors was pushed up
into ActionMessages and all behavior in ActionError was pushed up into ActionMessage. This
was done in the attempt to clearly signal that these classes can be used to pass any kind of
messages from the controller to the view -- errors being only one kind of message
How you will handle errors and exceptions using Struts
There are various ways to handle exception:
1) To handle errors server side validation can be used using ActionErrors classes can be
used.
2) The exceptions can be wrapped across different layers to show a user showable
exception.
3)using validators
How you will save the data across different pages for a particular client request
using Struts
Several ways. The similar to the ways session tracking is enabled. Using cookies, URL-
rewriting, SSLSession, and possibilty threw in the database.
What we will define in Struts-config.xml file. And explain their purpose
The main control file in the Struts framework is the struts-config.xml XML file, where
action mappings are specified. This file's structure is described by the struts-config DTD file,
which is defined at http://jakarta.apache.org/struts/. A copy of the DTD can be found on
88
the /docs/dtds subdirectory of the framework's installation root directory. The top-level
element is struts-config. Basically, it consists of the following elements:
data-sourcesA set of data-source elements, describing parameters needed to instantiate
JDBC 2.0 Standard Extension DataSource objects
form-beansA set of form-bean elements that describe the form beans that this
application uses
global-forwardsA set of forward elements describing general available forward URIs
action-mappingsA set of action elements describing a request-to-action mapping
What is the purpose of tiles-def.xml file, resourcebundle.properties file,
validation.xml file
The Tiles Framework is an advanced version of that comes bundled with the Struts
Webapp framework. Its purpose is reduce the duplication between jsp pages as well as
make layouts flexible and easy to maintain. It integrates with Struts using the concept of
named views or definitions.
What is Action Class. What are the methods in Action class
Action class is request handler in Struts. we will extend the Action class and over ride the
execute() method in which we will specify the business logic to be performed.
Explain about token feature in Struts
Tokens are used to check for invalid path for by the uer:
1) if the user presses back button and submits the same page
2)or if the user refreshes the page which will result to the resubmit of the previous action
and might lead to unstabality..
to solve the abv probs we use tokens
1) in previous action type saveTokens(HttpServletreuest)
2) in current action check for duplication bu
if(!isValidToken())
What part of MVC does Struts represent
Bad question. Struts is a framework which supports the MVC pattern.
What are the core classes of struts?
The core classes of struts are ActionForm, Action, ActionMapping, ActionForward etc.
What are the Important Components of Struts?
1. Action Servlet
2. Action Classes
3. Action Form
4. Validator Framework
5. Message Resources
6. Struts Configuration XML Files
7. View components like JSP
What is Struts?
Struts is a web page development framework and an open source software that helps
developers build web applications quickly and easily. Struts combines Java Servlets, Java
Server Pages, custom tags, and message resources into a unified framework. It is a
cooperative, synergistic platform, suitable for development teams, independent developers,
and everyone between.
How is the MVC design pattern used in Struts framework?
In the MVC design pattern, application flow is mediated by a central Controller. The
Controller delegates requests to an appropriate handler. The handlers are tied to a Model,
and each handler acts as an adapter between the request and the Model. The Model
represents, or encapsulates, an application's business logic or state. Control is usually then
forwarded back through the Controller to the appropriate View. The forwarding can be
determined by consulting a set of mappings, usually loaded from a database or
89
configuration file. This provides a loose coupling between the View and Model, which can
make an application significantly easier to create and maintain.
Controller--Servlet controller which supplied by Struts itself; View --- what you can see on
the screen, a JSP page and presentation components; Model --- System state and a
business logic JavaBeans.
Who makes the Struts?
Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakarta project,
like Tomcat, Ant and Velocity.
Why it called Struts?
Because the designers want to remind us of the invisible underpinnings that hold up our
houses, buildings, bridges, and ourselves when we are on stilts. This excellent description
of Struts reflect the role the Struts plays in developing web applications.
Do we need to pay the Struts if being used in commercial purpose?
No. Struts is available for commercial use at no charge under the Apache Software
License. You can also integrate the Struts components into your own framework just as if
they were writtern in house without any red tape, fees, or other hassles
What are the core classes of Struts?
Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of
Structs.
What is the design role played by Struts?
The role played by Structs is controller in Model/View/Controller(MVC) style. The View
is played by JSP and Model is played by JDBC or generic data source classes. The Struts
controller is a set of programmable components that allow developers to define exactly how
the application interacts with the user.
How Struts control data flow?
Struts implements the MVC/Layers pattern through the use of ActionForwards and
ActionMappings to keep control-flow decisions out of presentation layer.
What configuration files are used in Struts?
--ApplicationResourcesl.properties
--struts-config.xml
These two files are used to bridge the gap between the Controller and the Model.
What helpers in the form of JSP pages are provided in Struts framework?
--struts-html.tld
--struts-bean.tld
--struts-logic.tld
Is Struts efficient?
--The Struts is not only thread-safe but thread-dependent(instantiates each Action once
and allows other requests to be threaded through the original object.
--ActionForm beans minimize subclass code and shorten subclass hierarchies
--The Struts tag libraries provide general-purpose functionality
--The Struts components are reusable by the application
--The Struts localization strategies reduce the need for redundant JSPs
--The Struts is designed with an open architecture--subclass available
--The Struts is lightweight (5 core packages, 5 tag libraries)
--The Struts is open source and well documented (code to be examined easily)
--The Struts is model neutral
What is Jakarta Struts Framework? - Jakarta Struts is open source implementation of
MVC (Model-View-Controller) pattern for the development of web based applications.
Jakarta Struts is robust architecture and can be used for the development of application of
90
any size. Struts framework makes it much easier to design scalable, reliable Web
applications with Java.
What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In
the the Jakarta Struts Framework this class plays the role of controller. All the requests to
the server goes through the controller. Controller is responsible for handling all the
requests.
How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
Message Resources Definitions file are simple .properties files and these files contains the
messages that can be used in the struts project. Message Resources Definitions files can be
added to the struts-config.xml file through <message-resources /> tag.
Example:
<message-resources parameter=MessageResources />
What is Action Class?
The Action Class is part of the Model and is a wrapper around the business logic. The
purpose of Action Class is to translate the HttpServletRequest to the business logic. To use
the Action, we need to Subclass and overwrite the execute() method. In the Action Class
all the database/business processing are done. It is advisable to perform all the database
related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized
class to Action Form using the execute() method. The return type of the execute method is
ActionForward which is used by the Struts Framework to forward the request to the file as
per the value of the returned ActionForward object.
Write code of any Action Class?
Here is the code of Action Class that returns the ActionForward object.
1. import javax.servlet.http.HttpServletRequest;
2. import javax.servlet.http.HttpServletResponse;
3. import org.apache.struts.action.Action;
4. import org.apache.struts.action.ActionForm;
5. import org.apache.struts.action.ActionForward;
6. import org.apache.struts.action.ActionMapping;
7.
8. public class TestAction extends Action
9. {
10. public ActionForward execute(
11. ActionMapping mapping,
12. ActionForm form,
13. HttpServletRequest request,
14. HttpServletResponse response) throws Exception
15. {
16. return mapping.findForward(\"testAction\");
17. }
18. }
What is ActionForm?
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.
ActionForm maintains the session state for web application and the ActionForm object is
automatically populated on the server side with data entered from a form on the client
side.
What is Struts Validator Framework?
91
Struts Framework provides the functionality to validate the form data. It can be use
to validate the data on the users browser as well as on the server side. Struts
Framework emits the java scripts and it can be used validate the form data on the client
browser. Server side validation of form can be accomplished by sub classing your From
Bean with DynaValidatorForm class. The Validator framework was developed by David
Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of
Jakarta Commons project and it can be used with or without Struts. The Validator
framework comes integrated with the Struts Framework and can be used without doing
any extra settings.
Give the Details of XML files used in Validator Framework?
The Validator Framework uses two XML configuration files validator-rules.xml and
validation.xml. The validator-rules.xml defines the standard validation routines, these
are reusable and used in validation.xml. to define the form specific validations. The
validation.xml defines the validations applied to a form bean.
How you will display validation fail errors on jsp page? The following tag displays
all the errors:
<html:errors/>
How you will enable front-end validation based on the xml in validation.xml? The
<html:javascript> tag to allow front-end validation based on the xml in
validation.xml. For example the code: <html:javascript formName=logonForm
dynamicJavascript=true staticJavascript=true /> generates the client side
java script for the form logonForm as defined in the validation.xml file. The
<html:javascript> when added in the jsp file generates the client site validation
script.
92
EJB Enterprise Java Beans Enterprise Java Beans
Agenda
What is an EJB
Bean Basics
Component Contract
Bean Varieties
Session Beans
Entity Beans
Message Driven Beans
What is an EJB ?
Bean is a component
A server-side component
Contains business logic that operates on some temporary data or permanent database
Is customizable to the target environment
Is re-usable
Is truly platform-independent
So, what is an EJB?
Ready-to-use Java component
Being Java implies portability, inter-operability
Can be assembled into a distributed multi-tier application
Handles threading, transactions
Manages state and resources
Simplifies the development of complex enterprise applications
Benefits
Pure Java implies portability
exchange components without giving away the source.
Provides interoperability
assemble components from anywhere, can all work together.
Operational Benefits from EJB
Transaction management service
Distributed Transaction support
Portability
Scalability
Integration with CORBA possible
Support from multiple vendors
What Does EJB Really Define?
Component architecture
Specification to write components using Java
93
Specification to component server developers
Contract between developer roles in a components-based application project
The basis of components used in distributed transaction-oriented enterprise applications.
The Componentized Application :
Application now consists of several re-usable components.
Instances of components created at run-time for a client.
Common object for all instances of the component, usually called the Factory Object
EJB calls it Home Object
Common place where client can locate this Home Object
Objects located from a remote client through JNDI (Java Naming and Directory Interface)
service.
Application Server provides
JNDI based naming service
Implementation of Bean, Home and Remote
Complete Life Cycle Management
Resource pooling - beans, db connections, threads...
Object persistence
Transaction management
Secured access to beans
Scalability and availability
EJB: Core of J2EE
Architecture
Java Client
The Architecture Scenario
Application Responsibilities
-Create individual business and web components.
-Assemble these components into an application.
-Deploy application on an application server.
-Run application on target environment.
EJB Architecture Roles : Appointed for Responsibilities
94
J2EE Server
JSP
Servlets
Bea
ns
rmi
HTML
client
http
Business logic
EJB Component
server
Six roles in application development and deployment life cycle
Bean Provider
Application Assembler
Server Provider
Container Provider
Deployer
System Administrator
Each role performed by a different party.
Product of one role compatible with another.
Creating the Bean Instance
Look up for the Home Object through JNDI
Get the reference
Call create() method
The server generates the code for remote access using RMI (Remote Method Invocation).
The RMI code in the form of stub and skeleton: :
establishes connection,
marshals/unmarshals
places remote method calls
Bean Instance
95
Client
Bean Instance created Bean
Component Server
Component Contract :
Client-view contract
Component contract
EJB-jar file
Client-view contract :
Contract between client and container
Uniform application development model for greater re-use of components
View sharing by local and remote programs
The Client can be:
another EJB deployed in same or another container
a Java program, an applet or a Servlet
mapped to non-Java clients like CORBA clients
Component contract :
Between an EJB and the container it is hosted by
This contract needs responsibilities to be shared by:
the bean provider
the container provider
96
Client
Client View
Contract
Container
Component Server
Bean Instance
Component
Contract
_________
____
_________
____
Deployment descriptor
Deployment descriptor
EJB-jar
Bean providers
responsibilities
Container providers
responsibilities
Bean providers responsibility :
Implement business methods in the bean
Implement ejbCreate, ejbPostCreate and ejbRemove methods, and ejbFind method (in
the case of bean managed persistence)
Define home and remote interfaces of the bean
Implement container callbacks defined in the javax.ejb.Session bean interface
optionally the javax.ejb.SessionSynchronization interface
Implement container callbacks defined in javax.ejb.EntityBean interfaces for entities
Avoid programming practices that interfere with containers runtime management of bean
instances
Container providers responsibility :
Delegate client method invocations to the business methods
Invoke appropriate methods during an EJB object creation, removal and lookup
Provide classes that implement the home and remote interfaces of the bean
Invoke javax.ejb.SessionBean interface and SessionSynchronization interface
callbacks at appropriate times
Invoke javax.ejb.EntityBean interface for entities and callbacks at appropriate times
Implement persistence for entity beans with container managed persistence
Provide javax.ejb.SessionContext and javax.ejb.EntityContext for session and entity bean
instances, obtain the information from container
Provide JNDI context with the beans environment to the bean instances
Manage transaction, security and exception for beans
Ejb-jar file
Standard format used by EJB tools for packaging (assembling) beans along with
declarative information
Contract between bean provider and application assembler, and between application
assembler and application deployer
The file includes:
Java class files of the beans alo
Finally, the Big Picture
Bean Varieties
Three Types of Beans:
Session Beans - Short lived and last during a session.
Entity Beans - Long lived and persist throughout.
Message Driven Beans Asynchronous Message Consumers
Asynchronous.
Session Beans
97
A session object is a non-persistent object that implements some business logic running
on the server.
Executes on behalf of a single client.
Can be transaction aware.
Does not represent directly shared data in the database, although it may access and
update such data.
Is relatively short-lived.
Is removed when the EJB container crashes. The client has to re-establish a new session
object to continue computation
Types of Session Beans
There are two types of session beans:
Stateless
Stateful
Message Consumers
Clients view of a Session Bean :
A client accesses a session object through the session beans Remote Interface or Local
Interface.
Each session object has an identity which, in general, does not survive a crash
Locating a session beans home interface
Remote Home interface
Context initialContext = new InitialContext();
CartHome cartHome = (CartHome)
javax.rmi.PortableRemoteObject.narrow(initialContext.lookup(java:comp/env/ejb/cart),
CartHome.class);
Local Home Interface
Context initialContext = new InitialContext();
CartHome cartHome = (CartHome)
initialContext.lookup(java:comp/env/ejb/cart);
JNDI : used to locate Remote Objects created by bean.
portableRemoteObject Class : It uses an Object return by Lookup( ).
narrow( ) -> Call the create( ) of HomeInterface.
IntialContext Class :
Lookup( ) -> Searches and locate the distributed Objects.
Session Beans Local Home Interface :
object that implements is called a session EJBLocalHome object.
Create a new session object.
Remove a session object.
Session Beans Remote Home Interface
object that implements is called a session EJBHome object.
Create a session object
Remove a session object
Session Beans Local Interface
Instances of a session beans remote interface are called session EJBObjects
business logic methods of the object.
98
Session Beans Local Home Interface
instances of a session beans local interface are called session EJBLocalObjects
business logic methods of the object
Creating an EJB Object
Home Interface defines one or more create() methods
Arguments of the create methods are typically used to initialize the state of the created
session object
public interface CartHome extends javax.ejb.EJBHome
{
Cart create(String customerName, String account)
throws RemoteException, BadAccountException,
CreateException;
}
cartHome.create(John, 7506);
EJBObject or EJBLocalObject
Client never directly accesses instances of a Session Beans class
Client uses Session Beans Remote Interface or Remote Home Interface to access its
instance
The class that implements the Session Beans Remote Interface or Remote Home Interface
is provided by the container.
Session Object Identity
Session Objects are meant to be private resources of the client that created them
Session Objects, from the clients perspective, appear anonymous
Session Beans Home Interface must not define finder methods
Session Object Identity
Stateful Session Beans :
A stateful session object has a unique identity that is assigned by the container at the
time of creation.
A client can determine if two object references refer to the same session object by
invoking the isIdentical(EJBObject otherEJBObject) method on one of the references.
Stateless Session Beans :
All session objects of the same stateless session bean, within the same home have the
same object identity assigned by the container.
isIdentical(EJBObject otherEJBObject) method always returns true.
99
Container Responsibilities :
Manages the lifecycle of session bean instances.
Notifies instances when bean action may be necessary .
Provides necessary services to ensure session bean implementation is scalable and can
support several clients.
Activation and Passivation :
Session bean container may temporarily transfer state of an idle stateful session bean
instance to some form of secondary storage.
Transfer from working set to secondary storage is called instance passivation.
Transfer back from the secondary storage to the instance variables is called instance
activation.
Entity Beans
Long Live Entity Beans!
A component that represents an object-oriented view of some entities stored in a
persistent storage like a database or an enterprise application.
From its creation until its destruction, an entity object lives in a container.
Transparent to the client, the Container provides security, concurrency, transactions,
persistence, and other services to support the Entity Beans functioning
Cainer Managed Persistence versus Bean Managed Persistence
Multiple clients can access an entity object concurrently
Container hosting the Entity Bean synchronizes access to the entity objects state using
transactions
Each entity object has an identity which usually survives a transaction crash
Object identity is implemented by the container with help from the enterprise bean class
Multiple enterprise beans can be deployed in a Container
Remote Clients :
Accesses an entity bean through the entity beans remote and remote home interfaces
Implements EJBObject and EJBHome Interfaces
Location Independent
Potentially Expensive, Network Latency
Useful for coarse grained component access
10
0
Local Clients :
Local client is a client that is collocated with the entity bean and which may be tightly
coupled to the bean.
Implements EJBLocalObject and EJBLocalHome Interfaces
Same JVM
Enterprise bean can-not be deployed on a node different from that of its client Restricts
distribution of components.
Better supports fine-grained component access
Locating the Entity Bean :
Location of EJB Container is usually transparent to Client
Client locates Entity Beans Home Interface using JNDI
Example
Context initialContext = new InitialContext();
AccountHome accountHome = (AccountHome)
initialContext.lookup(java:comp/env/ejb/accounts);
Entity Beans Remote Home Interface
Container provides the implementation of the Remote Home Interface for each Entity Bean
deployed in the container
Container makes the Remote Home Interface of all Entity Beans deployed in it accessible
to Clients through JNDI
The object that implements an Entity Beans Remote Home Interface is called an EJBHome
object
Entity Beans Remote Home Interface
Create new entity objects within the home
Find existing entity objects within the home
Remove an entity object from the home
Create Methods :
Entity Beans Remote Home Interface can define multiple create() methods, each defining
a way of creating an entity object
Arguments of create() initialize the state of the entity object
Return type of a create() method is Entity Beans Remote Interface
The throws clause of every create() method includes the java.rmi.RemoteException and
javax.ejb.CreateException
finder Methods
Entity Beans Home Interface defines many finder methods
Name of each finder method starts with the prefix find
Arguments of a finder method are used by the Entity Bean implementation to locate
requested entity objects
Return type of a finder method must be the Entity Beans Remote Interface, or a collection
of Remote Interfaces
The throws clause of every finder method includes the java.rmi.RemoteException and
javax.ejb.FinderException
Entity Beans Remote Interface
Client accesses an entity object through Entity Beans Remote Interface
Entity beans Remote Interface must extend javax.ejb.EJBObject interface
Remote Interface defines business methods which are callable by clients
The container provides the implementation of the methods defined in the
javax.ejb.EJBObject interface
Only business methods are delegated to the instances of the enterprise bean class
Entity Beans Local Home Interface
must extend the javax.ejb.EJBLocalHome interface
10
1
Each method must be one of the:
Create methods
Find methods
Home methods
Entity Beans Local Interface
Local client can access an entity object through the entity beans local interface.
must extend the javax.ejb.EJBLocalObject interface.
defines the business methods callable by local clients.
Persistence Management
Data access protocol for transferring state of the entity between the Entity Bean instances
and the database is referred to as object persistence
There are two ways to manage this persistence during an applications lifetime
Bean-managed
Container-managed
Bean Managed Persistence :
Entity Bean provider writes database access calls directly into the enterprise bean class
Container Managed Persistence
Bean Provider need not write database calls in the bean
Container providers tools generate database access calls at deployment time
Advantage: Entity Bean can be mostly independent from the data source in which the
entity is stored
Disadvantage: Sophisticated tools are needed at deployment time to map Entity Bean
fields to data source
EJB QL
Need for standardizing queries
Why not SQL?
EJB QL: EJB Query Language
Specification language
Based on the CMP Data Model (Abstract Persistence Schema)
Compiled to a target language: SQL
EJB QL Example
SELECT OBJECT(l) From OrderBean o, in(o.lineItems) l