Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Servlet
|
Generic Servlet
|
HttpServlet ( Class ) — we will extend this class to handle GET / PUT HTTP requests
|
MyServlet
3 . What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle requests.
HttpServlet extends GenericServlet added new methods
doGet()
doPost()
doHead()
doPut()
doOptions()
doDelete()
doTrace() methods
Both these classes are abstract.
4 . What’s the difference between servlets and applets?
Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets
have no graphical user interface.
POST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info on the browser.
At the end of the session, we can inactivate the session by using the following command
session.invalidate();
Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself,
by using RequestDispatcher object.
You can get this object using getRequestDispatcher(”URL”) method. You can get this object
from either a request or a Context.
Example :
RequestDispatcher dispatcher = request.getRequestDispatcher(”/jspsample.jsp”);
if (dispatcher != null)
dispatcher.forward(request, response);
}
14 . How Can you include other Resources in the Response?
Using include method of a RequestDispatcher object.
Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example,
setCookie) that affects the headers of the response.
getSession(true) - This method will check whether already a session is existing for the user.
If a session is existing, it will return that session object, Otherwise it will create new session
object and return taht object.
getSession(false) - This method will check existence of session. If session exists, then it
returns the reference of that session object, if not, this methods will return null.
1.What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC
decouples interface from business logic and data.
Model : The model contains the core of the application’s functionality. The model encapsulates
the state of the application. Sometimes the only functionality it contains is state. It knows
nothing about the view or controller.
View: The view provides the presentation of the model. It is the look of the application. The
view can access the model getters, but it has no knowledge of the setters. In addition, it
knows nothing about the controller. The view should be notified when changes to the model
occur. Controller:The controller reacts to the user input. It creates and sets the model.
2.What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible
way for a specific requirement.
Struts framework is an open-source framework for developing the web applications in Java EE,
based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust
architecture and can be used for the development of application of any size. Struts framework
makes it much easier to design scalable, reliable Web applications with Java.
Pages that represent MVC-style views; pages reference view roots via the JSF component tree.
6.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main
Controller component that handles client requests and determines which Action will process
each received request. It serves as an Action factory – creating specific Action classes based
on user’s request.
Pull data from the model (if necessary) to be given to the appropriate view,
ActionForm is javabean which represents the form inputs containing the request parameters
from the View referencing the Action bean.
validate() : Used to validate properties after they have been populated; Called before
FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is
the method signature for the validate() method.
11.What is ActionMapping?
Action mapping contains all the deployment information for a particular Action bean. This class
is to determine where the results of the Action will be sent once its processing is complete.
We can specify the action mapping in the configuration file called struts-config.xml. Struts
framework creates ActionMapping object from <ActionMapping> configuration element of
struts-config.xml file
<action-mappings>
<action path=“/submit”
type=“submit.SubmitAction”
name=“submitForm”
input=“/submit.jsp”
scope=“request”
validate=“true”>
<forward name=“success” path=“/success.jsp”/>
<forward name=“failure” path=“/error.jsp”/>
</action>
</action-mappings>
An Action Class performs a role of an adapter between the contents of an incoming HTTP
request and the corresponding business logic that should be executed to process this request.
16.Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be
configured as follows:
<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,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
…..
<servlet>
18.What is the difference between session scope and request scope when saving
formbean ?
when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.
<!--[if !supportLists]--><!--[endif]-->ForwardAction
<!--[if !supportLists]--><!--[endif]-->IncludeAction
<!--[if !supportLists]--><!--[endif]-->DispatchAction
<!--[if !supportLists]--><!--[endif]-->LookupDispatchAction
<!--[if !supportLists]--><!--[endif]-->SwitchAction
21.What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you
can have a method for each logical action compared than a single execute method. The
DispatchAction dispatches to one of the logical actions represented by the methods. It picks a
method to invoke based on an incoming request parameter. The value of the incoming
parameter is the name of the method that the DispatchAction will invoke.
The ForwardAction class is useful when you’re trying to integrate Struts into an existing
application that uses Servlets to perform business logic functions. You can use this class to
take advantage of the Struts controller and its functionality, without having to rewrite the
existing Servlets. Use ForwardAction to forward a request to another resource in your
application, such as a Servlet that already does business logic processing or even another JSP
page. By using this predefined action, you don’t have to write your own Action class. You just
have to set up the struts-config file properly to use ForwardAction.
24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that
uses Servlets. Use the IncludeAction class to include another resource in the response to the
request being processed.
25.What is the difference between ForwardAction and IncludeAction?
The difference is that you need to use the IncludeAction only if the action is going to be
included by another action or jsp. Use ForwardAction to forward a request to another resource
in your application, such as a Servlet that already does business logic processing or even
another JSP page.
26.What is LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its
name in the front end, but by the Locale independent key into the resource bundle. Since
the key is always the same, the LookupDispatchAction shields your application from the
side effects of I18N.
The difference between LookupDispatchAction and DispatchAction is that the actual method
that gets called in LookupDispatchAction is based on a lookup of a key value instead of
specifying the method name directly.
29.What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another
resource in a different module. SwitchAction is useful only if you have multiple modules in
your Struts application. The SwitchAction class can be used as is, without extending.
30.What if <action> element has <forward> declaration with same name as global
forward?
In this case the global forward is not used. Instead the <action> element’s <forward> takes
precendence.
31.What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets
of properties (configured in configuration file), without requiring the developer to create a Java
class for each type of form bean.
32.What are the steps need to use DynaActionForm?
<!--[if !supportLists]--><!--[endif]-->import
org.apache.struts.action.DynaActionForm
import org.apache.struts.action.DynaActionForm;
<html:errors/> tag displays all the errors. <html:errors/> iterates over ActionErrors request
attribute.
<logic:iterate> repeats the nested body content of this tag over a specified collection.
<table border=1>
<logic:iterate id=“customer“ name=“customers”>
<tr>
<td><bean:write name=“customer” property=“firstName”/></td>
<td><bean:write name=“customer” property=“lastName”/></td>
<td><bean:write name=“customer” property=“address”/></td>
</tr>
</logic:iterate>
</table>
<bean:message>: is used to retrive keyed values from resource bundle. It also supports the
ability to include parameters that can be substituted for defined placeholders in the retrieved
string.
<bean:message key=“prompt.customer.firstname”/>
<bean:write>: is used to retrieve and print the value of the bean property. <bean:write>
has no body.
Explicit try/catch blocks in any code that can throw exception. It works well when
custom value (i.e., of variable) needed when error occurs.
<global-exceptions>
<exception key=“some.key”
type=“java.lang.NullPointerException”
path=”/WEB-INF/errors/null.jsp”/>
</global-exceptions>
or
<exception key=“some.key”
type=“package.SomeException”
path=“/WEB-INF/somepage.jsp”/>
39.How can we make message resources definitions file available to the Struts
framework environment?
We can make message resources definitions file (properties file) available to Struts framework
environment by adding this file to struts-config.xml.
<message-resources parameter=“com.login.struts.ApplicationResources”/>
1. Page translation: -page is parsed, and a java file which is a servlet is created.
2. Page compilation: page is compiled into a class file
3. Page loading : This class file is loaded.
4. Create an instance :- Instance of servlet is created
5. jspInit() method is called
6. _jspService is called to handle service calls
7. _jspDestroy is called to destroy it when the servlet is not required.
JSP page can include the contents of other HTML pages or other JSP files. This is done by
using the include directive. When the JSP engine is presented with such a JSP page it is
converted to one servlet class and this is called a translation unit, Things to remember in a
translation unit is that page directives affect the whole unit, one variable declaration cannot
occur in the same unit more than once, the standard action jsp:useBean cannot declare the
same bean twice in one unit.
8 . What is a Expression
Expressions are act as place holders for language expression, expression is evaluated each
time the page is accessed.
9 . What is a Declaration
It declares one or more variables or methods for use later in the JSP source file. A declaration
must contain at least one complete declarative statement. You can declare any number of
variables or methods within one declaration tag, as long as semicolons separate them. The
declaration must be valid in the scripting language used in the JSP file.
10 . What is a Scriptlet
A 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 <?
xml:namespace prefix = jsp />.
11 . What are the implicit objects
List them. Certain objects that are available for the use in JSP documents without being
declared first. These objects are parsed by the JSP engine and inserted into the generated
servlet. The implicit objects are:
1. request
2. response
3. pageContext
4. session
5. application
6. out
7. config
8. page
9. exception
1. page
2. request
3. session
4. application
14 . Why are JSP pages the preferred API for creating a web-based client program
Because no plug-ins or security policy files are needed on the client systems(applet does).
Also, JSP pages enable cleaner and more module application design because they provide a
way to separate applications programming from web page design. This means personnel
involved in web page design do not need to understand Java programming language syntax to
do their jobs.
17 . How can I implement a thread-safe JSP page? What are the advantages and
Disadvantages of using it?
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. With this, instead of a single instance of the servlet generated for your JSP
page loaded in memory, you will have N instances of the servlet loaded and initialized, with
the service method of each instance effectively synchronized. You can typically control the
number of instances (N) that are instantiated for all servlets implementing SingleThreadModel
through the admin screen for your JSP engine. More importantly, avoid using the tag for
variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned
above. Otherwise, all requests to that page will access those variables, causing a nasty race
condition. SingleThreadModel is not recommended for normal use. There are many pitfalls,
including the example above of not being able to use <%! %>. You should try really hard to
make them thread-safe the old fashioned way: by making them thread-safe
19 . 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
%>
You can also use HTML-style comments anywhere within your JSP page. These comments are
visible at the client. For example:
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
**/
%>
25 . 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 JSP engine 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.
26 . 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(”/”);
response.addCookie(killMyCookie);
%>
28 . 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 JSP engine. In any case, your new
superclass has to fulfill the contract with the JSP engine 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:
29 . How can I prevent the word “null” from appearing in my HTML input text fields
when I populate them with a resultset that has null values
You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? “” : s;
}
%>
then use it inside your JSP form, like
<input type=”text” name=”shoesize” value=”<%=blanknull(shoesize)% >” >
30 . How can I get to print the stacktrace for an exception occuring within my JSP page
By printing out the exceptionâ?Ts stack trace, you can usually diagonse a problem better
when debugging JSP pages. By looking at a stack trace, a programmer should be able to
discern which method threw the exception and which method called that method. However,
you cannot print the stacktrace using the JSP out implicit variable, which is of type JspWriter.
You will have to use a PrintWriter object instead. The following snippet demonstrates how you
can print a stacktrace from within a JSP error page:
<%@ page isErrorPage=”true” %>
<%
out.println(” “);
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println(” “);
%>
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 is used for including non-JSP files.
Java Notes
Java is a programming language i.e. used to design the net based applications i.e. applications
that run securely over a network and work on wide range of platforms.
Every class is defined with a set of attributes and a set of functions according to requirements
of the physical objects.
We can define the constructors in a class according to the application requirement to initialize
the values of the attributes for an object at the time of constructing the object.
We must specify the returning type for a method depending on the value of the method
returns, where as for a constructor we should not specify any returning type.
The name of a method can be given by the user as any name where as the name of the
constructor should exactly match with the name of the class.
main() is declared as public in order to allow the JVM to call the method being a non member
of the class.
In java variables of user defined data types are known as references. A reference is in the
background at pointer only. References are in fact restricted pointer.
According to the principles of OOP, all the objects that are created from the same class will
have same structure and behavior, but not the same state.
Whenever instance variable names and local variable names are the same always preference
is given for local variables. In such a case instance variables are not referred at all. As a result
object state can not be changed. To overcome this problem, we make use of keyword ‘this’.
Access Specifiers: An access specifier is a keyword in java. That is associated with the
members of class to specify their visibility or accessing mode.
private Y N N N N
default Y Y Y N N
protected Y Y Y Y N
public Y Y Y Y Y
To implement encapsulation in java, define a class and create the object.
To implement abstraction in java, define a class .declare some crucial BL methods as private.
Make some methods non private.
In OOP, objects communicate one another through message passing. From the code of one
class calling the code of another class is known as message passing.
Method overloading: Within the same class defining more than one method with the same
name is known as method overloading.
When method overloading is implemented in a class and if we create the object of that class,
that object becomes polymorphic.
Inheritance: Creating new classes from the existing class for the sake of code reusability is
known as inheritance.
Sub class inherits all the variables and methods of super class irrespective of access specifiers.
Always our subject of interest will to create the objects of sub class to optimize the code
reusability.
Method overriding: Redefining the super class method in a sub class is known as method
overriding.
Method signatures should be same for super class method and sub class method. Return types
must be same.
Overriding method (sub class) should not be have lesser access privilege than that of
overridden method.
When overriding is implemented and method call is made on the sub class object always sub
class version only is executed.
1 For each instance one separate For entire class only one copy is
copy is created created
2
Memory is allocated only when No relation when object existence
object is created. as soon as class is loaded into
environment, memory is created.
A static method can not access an instance variable. Similarly it can not call an instance
method, where as an instance method can access static variable and call static method also.
An abstract class cannot be instantiated only concrete class can be instantiated. Abstract class
concept is meaningful in the context of inheritance only.
An abstract class can act as data type i.e., its reference can be created even though its object
cannot be created.
An abstract method enforces method overriding i.e. if any class is inheriting from an abstract
class, it is the responsibility of that child class to override all the abstract methods of the super
class.
overloading overriding
Final: If a method declared as a final, it is an indication to the child classes that its definition
is already finalized. Don’t try to redefine it. But can be inherited.
Abstract keyword enforces overriding of methods and final keyword prevents overriding.
Inheritance is not prevented in both cases.
In java, one class cannot inherit from more than one class. But, one class can inherit from any
no. of interfaces besides inherit from single class.
Every array in java has property called length that gives the programmer its size.
Values supplied from the commandline to the main() during the program execution are known
as commandline arguments.
Constructors in inheritance:
Whenever sub class object is created, sub class constructor is called first but not executed.
From within the sub class constructor an implicit call is made to the super class
constructor(zero argument constructor only). If the constructor is found in super class, it will
be called.
Compilation errors: are reported when the grammar(syntax) of the language is violated.
These are not all dangerous.
Execution time errors: are known as exceptions. During the program execution, if any
abnormal event occurs exception is fired.
Unchecked Exception: is that kind of exception which, even though you don’t deal within
your program does not become a syntactical error.
If any abnormal event is generated with in the code of try block, JVM encapsulates that
abnormal event as appropriate exception object and throw it from the try block.
Finally: is a keyword used to create a block of statements. In this block we write that code
which need to be executed in both cases i.e. exception generating case and exception not
generated case.
A java program never ever need to directly deal with the IO devices. Instead, it deals with the
respective objects.
Synchronization:
Whenever 2 threads concurrently access a common resource, there is a possibility of data
integrity compromise.
Synchronization can be treated as a locking mechanism. As soon as one thread enters the
monitor, code is not locked. Instead, object(shared resource) is locked.
End user interacts with business applications throw graphical user interfaces of the application.
An applet is a small java program, it is stored in the server side, dynamically loaded to client
side along with web page and executed in the client side with in the confines of java enabled
browser.
Writing some special code along with the front end code to provide functionality for GUI
controls is the basic goal of event handling.
Inner class can access all the members of outer class including private members.
2-tier arch: In this model client is responsible for presentation logic and BL along with this it
should be intelligent to communicate with server. Server is responsible to maintain business
data and in some cases consists of some parts of logic like generating auto key….like server
can be database server.
3-tier arch: In this model client takes the responsibility for the PL and some logic which helps
to communicate with the middleware server. Middleware server is responsible to encapsulate
the BL and to interact with the backend server and includes NL i.e. intelligent to take the
request from the client and send response to the client.
As generic middleware servers has been introduced which are intelligent to make and resolves
HTTP format msg’s.
Servlet Component: is a simple java class written following Servlet specification standards.
Servlet container is a 3rd party vendor application which provides all the low level services and
manages Servlet components.
Servlet API:
init(ServeltConfig)
service(ServletRequest, ServlerResponce)
destroy()
getServletConfig()
getServletInfo()
Servlet Lifecycle:
1. When container creates an instance of Servlet
After creating an instance of our Servlet class and before it is used to process the request container
creates ServletConfig type of instance for this Servlet.
Call init method on Servlet object and pass the ServletConfig type of object created.
2. When client makes a request
Locates the Servlet instance and create ServletRequest, ServlerResponce type of objects which
encapsulates request and response details.
Call service() method on Servlet object passing above ServletRequest, ServlerResponce type of
instances.
3. destroying
Container call destroy method on Servlet instance.
Request parameters: If we want to send some data from client to server and use it in the
server to process the request then we can submit this data in the form of name value pairs.
To get request parameter details in javax.servlet.ServletRequest we have given with following
methods
1. String getParameter(String)
2. String[] getParameterValues(String)
3. java.util.Enumeration getParameterNames()
Init Parameters: These are the Servlet instance level parameters where these parameters
are configured by the deployer at the time of deploying the application and are set into
ServletConfig type of object.
For one web application only one ServletContext type of object is created.
We have an option to get the other Servlet instance reference from the container using which
we can dispatch the request to other Servlet by just invoking service method on that instance.
Using include or forward: Both of these options allows us to dispatch the request from our
Servlet to other component but forward has some restrictions like our Servlet(which is
forwarding the request) should not involve in generating the response content.
Using RD we can dispatch the request to only the component in the same context.
Attributes: we want to dispatch the request from one Servlet to other web component; we
may require making some data which is generated in the source Servlet to the destination
Servlet. To meet this requirement RequestAttributes option is given under Servlet
specification.
In javax.servlet.ServletRequest:
setAttribute(String, object)
getAttribute(String)
removeAttribute(String)
RequestAttributes are thread safe since scope of these attributes is request and as we know
that one request is completely processed by only one thread.
HTTP: is an appln layer protocol and it can not maintain client data and identify the client b/w
multiple requests.
HTTPServlet: is an abstract class but doesn’t consist of any abstract methods. It is sub type
of GenericServlet and doesn’t override init, destroy and other methods except it implements
service method which is an abstract method in Generic Servlet.
Additional methods in this class are
protected void service(-,-)throws ServletException, IOEception
protected void doGet(-,-)throws ServletException, IOEception
protected void doPost(-,-)throws ServletException, IOEception and all doXXX methods……
HTTPServletRequest: This type of object encapsulates all http specific request information.
HTTPServletResponce: is declared withal the method which can be used to set the http
specific response content and headers.
Some of additional methods declared in this interface are
setHeader(String, String), addCookie(), sendRedirect()
sendRedirect(): is one of the method in HTTPServletResponce. This method sets the location
header into the response. This is used to redirect the request from one resource to the other.
Session Tracking: For each request from client can have one connection, mean the
connection is destroyed for each completion of response from the server.
Session: A set of uninterrupted request and response b/w client && server where the data
with in this set of requests is known as session data.
Session tracking is concept which explains how to keep track of session data. This is required
to be managed in our appln by the container.
URLRewritting: In this case the data which has to required in the next request will be
appended to the url which has to be used by the client to make a next request
So that without clients knowledge this data will come from the client as a request parameters.
In an HTTPRequest GET, we can pass some small amount of data from client to server(i.e.
upto 256 char’s)and this data is appended to request uri and sent to the server where ‘?’ is
the separator b/w the request uri and this data.
Where each of the parameter in the query string is separated with ‘&’ char and the name and
value of the parameter is separated by ’=’ char.
Using these fields to make the data available for the next requests is almost same as
URLRewrittin but instead of appending the data to url in the server it will be done itself in the
client when the form is submitted.
And using this option we can submit the data using POST method also.
Cookies: Cookie is a small data unit saved in the client side for given host and path.
Each of cookies consists of following attributes….
Name, value, maxTime, host, path, isSecure.
These are saved in client side and when a client makes a request all the cookies whose path &
host matches with request url’s host & path are included into the request and sent to the
server.
In javax.servlet.http.HttpServletResponce
addCookie(Cookie)
In javax.servlet.http.HttpServletRequest
Cookie[] getCookies()
HTTPSession: In this case data which is required to be maintained in the server and a unique
identity for this data unit is generated by the container is required to be maintained by client.
For each of the client one HTTPSession type of object is created and all the data of the client
will be stored into this object.
Object set into session are not thread safe by default and there is a possibility that multiple
threads may use the same object at a time. So if required we need to make it synchronized.
If multiple clients makes a request for the same Servlet then container creates or locates
multiple threads i.e. one threads for each request.
javax.servlet.SingleThreadModel: is a marker interface which marks our Servlet instance
to be thread safe and if multiple requests to same Servlet are made at a time then in this case
container may creates multiple instances to process these requests.
If we have any set of statements to be thread safe we are recommend using synchronized
blocks.
Connection Pool: To establish connection to the database & close the connection it consumes
some time and resources of DBMS.
By reducing the no. of connections establishing and closing operations, we will be able to
reduce the load on the database.
We require an intelligent appln which can be accessed by our appln and can manage the
connection objects perfectly and such an appln is known as Connection Pool Manager.
CPM is responsible for establishing the required no. of connections to DB, preparing a logical
connection & maintaining the connections.
Security: JAAS is a standard specification which allows us to provide a fine grained user
based security.
Authentication: is a process of finding whether the security details submitted by the user are
valid or not.
Authorization: is a process of finding whether an authenticated user has permission to
access the requested service or not.
Filters: These components are used to encapsulate the logic which has to be executed before
or after the actual request processing which is done by the requested resource.
Advantages: The interception points and the number of interceptions, order of various
interception can be declared at the time of deploying the appln instead of at the time of
developing the appln.
Some of the uses of filters are Session Validation, Encoding format verification, Logging
operations, Security verification, Output content transformation.
Javax.servlet.Filter interface is declared with 3 methods….
– init(FilterConfig)
– doFilter(ServlerRequest,ServletResponce,FilterChain) this method is invoked when a request
is made to the resource which is configured to be intercepted by this filter.
– destroy()
When we configure multiple filter-mappings for a Servlet, some of them with url-pattern and
some other with Servlet name in such a case first the filters configured with url-pattern are
given with preference then filter mapped with Servlet name.
Listeners: A listener is called when the user does something to the user interface that causes
an event. Although these events usually come from the user interface, they can have other
sources (eg, a Timer).
Wrappers: The Wrapper class represents the base class for a set of data sources. This class
provides library initialization services and access to the data source servers that the wrapper
supports.
In servlets2.3 specification we have been given with 4 wrapper classes i.e.
ServlerRequestWrapper, ServlerResponceWrapper
HttpServlerRequestWrapper, HttpServlerResponceWrapper
These wrapper classes allows us to perform some decorator services to the request and
response objects i.e. we can write a subclass for these wrappers and add some required
decorator logic.
As we know that Servlet allows us to provide a server side extension which is even use to
present some dynamic content and in this case this server side extension is provided in the
form of java class which follows some java standards.
JSP: provides tag based simplified approach to develop server side extension to present some
dynamic content.
Architecture:
The Servlet equivalent class which is prepared by the JSP translator should be sub type of
javax.servlet.jsp.JspPage
JSP TAGS:
Scripting Tags: these allows us to include some script content into the JSP document where
in a jsp document we are allowed to use java as scripting language.
Scriptlet: this tag used to encapsulate some script content which is part of _jsp method.
<% script code(can be multiple statements) %>
Declarative: This tag allows us to declare instance & class variables & implement some utility
methods. <%! Script content(can be multiple statements) %>
Expression: This tag takes a java expression which is resolved and then result value is
included into O/P. <% =java expression %>
Directives: These tags give some direction to jsp translator while translating the jsp
document and these tags are resolved and executed at the time of translation phase itself.
Page directive: This directive holds the directions which are used by the translator at the
time of translation and these instructions are used to effect various properties associated with
the page.
<%@page attributes %>
Attribute are import(takes imports), extends(is not recommended), erorPage(takes error page
path), isErrorPage(takes true or false), isThreadSafe(takes true or false), session(takes true or
false), language(takes scripting language), contentType(default is text/html),
autoFlush(default is true), buffer(takes buffer size).
Include Directive: is used to include some other page content into our page at a specified
location.
<%@include file=”” %>
Taglib directive: is used to declare any custom tag library in our jsp document so that tags
related to that custom tag can be used in this document.
IMPLICIT OBJECTS: this part of jsp specification standardized some object reference names
and their types so that the responsibility of initializing these ref variables in _jspService
method.
CUSTOM TAGS: The above tags are not enough to separate the PL from AL i.e. in spite of
using these we are still required to write some java code in jsp document to meet our
requirement.
Various elements involved with custom tags are
1. Tag Handler: this is java class which should sub type of tag. This class defines behavior
which has to be executed for our tag.
2. Tag Lib Declaration(TLD): this is a simple XML document where we can declare our tags
like tag name, its attributes & tag handler class where the tags behavior is defined.
Now these tags can be used in jsp document and before we use in document we need to
declare these set of tags making translator aware that there are some set of tags being used
in the document which has to be resolved. This is done using tag lib directive.
And the tags which has to be evaluated by translator has to be used with the declared prefix
i.e. <%@taglib prefix=”” uri=”” %>
Classic Tags:
For each of the attributes required we should implement one set and get method in the Tag
Handler.
While declaring the Tag we should even declare it to hold our required attributes also i.e. in tld
file.
BodyTag: if our tag is not empty tag, then the TagHandler used to define the behavior for
such a tag should sub type of BodyTag.
The additional methods which are included with respective to the body tags are
setBodyContent(BodyContent), doInitBody(), doAfterBody().
And some constants given are EVAL_BODY_BUFFERED, EVAL_BODY_INCLUDE,
EVAL_BODY_AGAIN.
Iteration Tags: In this case we are allowed to evaluate the body part of the tag for multiple
times. BodyTag interface extends this interface. One constant declared in this interface is
EVAL_BODY_AGAIN and this value can be the return value of doAfterBody which results into
evaluating the body content again.
If we want to handle abnormal conditions raised by our TagHandler methods which are called
by _jspService method or even if we want to execute some finalization logic the we can use
the following interface…….javax.servlet.jsp.tagext.TryCatchFinally with the following methods
doCatch(Throwable), doFinally().
Simple Tags:
In case of Simple Tags container uses caching i.e. as in the case of classic tags container was
using tag pool.
When a tag whose TagHandler is defined as subtype of SimpleTag is used
i. Creates a new instance using no-arg constructor.
ii. Calls setJspContext which takes JspContext as arg.
iii. Calls setParent.
iv. Calls setXXX methods
v. Calls doStart Tag.
vi. The remaining operations will be depending on return value of
doStartTag same as of Classic Tags.
1. Core tags: these set of tags allows us to perform some basic prgming oprtns like setting
the attributes, using if condition, preparing loops…
URI to use these set of tags http://java.sun.com/jstl/core
Recommended prefix is ‘c’
For ex: <%@taglib uri=”http://java.sun.com/jstl/core” prefix=”c”%>
out: this tag is used to include some values to the o/p
<c:out value=”” scope=””/>
set: is used to set an attribute.
<c:set attributes/>
Attributes are value, var, scope, property
<c:set value=”${param.uname}” var=”username” scope=”session”/>
if: takes condition & if the given condition is resolved to true then it evaluate its body content.
<c:if test=”” var=”” scope=””>body part</c:if>
when: <c:when test=””>body part</c:when>
otherwise: <c:otherwise> body part </c:otherwise>
choose: is used in combination with when & otherwise.
<c:choose> body part </c:choose>
forEach: it takes a collection & iterates its body content for each of the element in the given collection.
<c:forEach attributes> body part </c:forEach>
Attributes are collection, scope, var, start, end, step
forToken: same as forEach but it takes a String.
<c:forTokens> body part </c:forTokens>
3. Formatting tags: this part of JSTL tags allows us to present the data in locale specific format and
even get the values of given message resolve key.
URI to use these set of tags http://java.sun.com/jstl/fmt
Recommended prefix is ‘fmt’
setBundle: <fmt:setBundle attributes/>
Attributes are basename, var, scope.
setLocale: <fmt:setLocale attributes/>
Attributes are value, var, scope.
message: this tag allows us to get the value specific to the locale for the given message
resource key and print it to the o/p or store it into the o/p.
<fmt:message attributes></fmt:message>
Attributes are bundle, key, var, scope.
param: used as a child tag of a message element & used to set the parameters of a message.
One param tag can set only one value.
<fmt:param value=””/>
bundle: used to pack some message tags.
<fmt:bundle basename=”” prefix=””></fmt:bundle>
formatNumber: <fmt:formatNumber attributes/>
Attributes are value, type, pattern, currencyCode, maxIntegerDigits, minIntegerDigits,
maxFractionDigits, minFractionDigits.
parseNumber: allows us to parse the formatted no. into number.
<fmt:parseNumber attributes/>
Attributes are value, type, integerOnly, var, scope, pattern.
formatDate: <fmt:formatDate attributes/>
Attributes are value, type, pattern, dateStyle, timeStyle, var, Scope.
parseDate: allows us to parse the formatted date value into a date type.
<fmt:parseDate value=”” type=”” var=”” scope=”” pattern=””/>
4. XML tags: these tags allows us to parse the xml content & get the data from the parsed
document even we can use these to perform some logical operations & looping.
parse: <x:parse value=”” var=”” scope=””/>
Some of xml tags are out, set, if, choose, when, otherwise, forEach, transform.
JavaScript Notes
<html>
<body>
<script type=”text/javascript”>
document.write(”Hello World!”)
</script>
</body>
</html>
<!–
document.write(”Hello World!”)
//–>
The two forward slashes at the end of comment line (//) are a JavaScript comment
symbol. This prevents the JavaScript compiler from compiling the line.
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
</script>
</body>
</html>
<html>
<head>
<script type=”text/javascript”>
function message()
}
</script>
</head>
<body onload=”message()”>
</body>
</html>
Scripts in the head section: Scripts to be executed when they are called, or when an
event is triggered, go in the head section. When you place a script in the head section,
you will ensure that the script is loaded before anyone uses it.
<html>
<head>
<script type=”text/javascript”>
….
</script>
</head>
Scripts in the body section: Scripts to be executed when the page loads go in the
body section. When you place a script in the body section it generates the content of the
page.
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
….
</script>
</body>
Scripts in both the body and the head section: You can place an unlimited number
of scripts in your document, so you can have scripts in both the body and the head
section.
<html>
<head>
<script type=”text/javascript”>
….
</script>
</head>
<body>
<script type=”text/javascript”>
….
</script>
</body>
Sometimes you might want to run the same JavaScript on several pages, without
having to write the same script on every page.
To simplify this, you can write a JavaScript in an external file. Save the external
JavaScript file with a .js file extension.
To use the external script, point to the .js file in the “src” attribute of the <script>
tag:
<html>
<head>
<script src=”xxx.js”></script>
</head>
<body>
</body>
</html>
If Statement:
<script type=”text/javascript”>
var time=d.getHours()
if (time<10)
document.write(”<b>Good morning</b>”)
</script>
If…else Statement:
<script type=”text/javascript”>
document.write(”Good morning!”)
else
document.write(”Good day!”)
</script>
If…else if…else Statement:
<script type=”text/javascript”>
if (time<10)
document.write(”<b>Good morning</b>”)
document.write(”<b>Good day</b>”)
else
document.write(”<b>Hello World!</b>”)
</script>
<!--[endif]-->
The JavaScript Switch Statement:
<script type=”text/javascript”>
theDay=d.getDay()
switch (theDay)
case 5:
document.write(”Finally Friday”)
break
case 6:
document.write(”Super Saturday”)
break
case 0:
document.write(”Sleepy Sunday”)
break
default:
</script>
Conditional Operator:
JavaScript also contains a conditional operator that assigns a value to a variable based
on some condition.
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor==”PRES”)?”Dear President “:”Dear ”
If the variable visitor is equal to PRES, then put the string “Dear President ” in the
variable named greeting. If the variable visitor is not equal to PRES, then put the string
“Dear” into the variable named greeting.
Alert Box:
An alert box is often used if you want to make sure information comes through to the
user.
When an alert box pops up, the user will have to click “OK” to proceed.
Syntax
alert(”sometext”)
Confirm Box:
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either “OK” or “Cancel” to
proceed.
If the user clicks “OK”, the box returns true. If the user clicks “Cancel”, the box returns
false.
Syntax:
confirm(”sometext”)
Prompt Box:
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either “OK” or “Cancel” to
proceed after entering an input value.
If the user clicks “OK” the box returns the input value. If the user clicks “Cancel” the
box returns null.
Syntax:
prompt(”sometext”,”defaultvalue”)
onload:
The onload event is often used to check the visitor’s browser type and
browser version, and load the proper version of the web page based on the
information. Both the onload and onUnload events are also often used to deal
with cookies that should be set when a user enters or leaves a page.
The onFocus, onBlur and onChange events are often used in combination with
validation of form fields.
id=”email” onchange=”checkEmail()”>;
onSubmit:
The onSubmit event is used to validate ALL form fields before submitting it.
onSubmit=”return checkForm()”>
<a href=”http://www.w3schools.com”
</a>
Try…Catch Statement:
The try…catch statement allows you to test a block of code for errors. The try
block contains the code to be run, and the catch block contains the code to be
executed if an error occurs.
<html>
<head>
<script type=”text/javascript”>
var txt=”"
function message()
try
addalert(”Welcome guest!”)
catch(err)
if(!confirm(txt))
document.location.href=”http://www.w3schools.com/”
</script>
</head>
<body>
</body>
</html>
The throw statement allows you to create an exception. If you use this
statement together with the try…catch statement, you can control program
flow and generate accurate error messages.
<html>
<body>
<script type=”text/javascript”>
try
if(x>10)
throw “Err1″
else if(x<0)
throw “Err2″
catch(er)
if(er==”Err1″)
if(er == “Err2″)
</script>
</body>
</html>
Using the onerror event is the old standard solution to catch errors in a web
page. To use the onerror event, you must create a function to handle the
errors. Then you call the function with the onerror event handler. The event
handler is called with three arguments: msg (error message), url (the url of
the page that caused the error) and line (the line where the error occurred).
<html>
<head>
<script type=”text/javascript”>
onerror=handleErr
var txt=”"
function handleErr(msg,url,l)
txt+=”Line: ” + l + “\n\n”
txt+=”Click OK to continue.\n\n”
alert(txt)
return true
function message()
adddlert(”Welcome guest!”)
</script>
</head>
<body>
</body>
</html>
document.write(txt)
JavasScript will now output the proper text string: We are the so-called “Vikings” from the
north.
23) The Navigator object contains information about the visitor’s browser name, browser
version, and more.
<body>
<script type=”text/javascript”>
var browser=navigator.appName
var b_version=navigator.appVersion
var version=parseFloat(b_version)
document.write(”<br />”)
</script>
</body>
</html>
1 . What is EJB ?
EJB stands for Enterprise JavaBean and is a widely-adopted server side component
architecture for J2EE. It enables rapid development of mission-critical application that are
versatile, reusable and portable across middleware while protecting IT investment and
preventing vendor lock-in.
Session Facade is a design pattern to access the Entity bean through local interface than
accessing directly. It increases the performance over the network. In this case we call session
bean which on turn call entity bean.
EJB technology is the core of J2EE. It enables developers to write reusable and portable
server-side business logic for the J2EE platform.
4 . What is the difference between EJB and Java beans?
EJB is a specification for J2EE server, not a product; Java beans may be a graphical
component in IDE
1. EJB components are server-side components written entirely in the Java programming
language
2. EJB components contain business logic only - no system-level programming & services,
such as transactions, security, life-cycle, threading, persistence, etc. are automatically
managed for the EJB component by the EJB server.
3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and
secure.
4. EJB components are fully portable across any EJB server and any OS.
5. EJB architecture is wire-protocol neutral–any protocol can be utilized like IIOP,JRMP, HTTP,
DCOM,etc.
A message-driven bean combines features of a session bean and a Java Message Service
(JMS) message listener, allowing a business component to receive JMS. A message-driven
bean enables asynchronous clients to access the business logic in the EJB tier.
Entity Bean is a Java class which implements an Enterprise Bean interface and provides the
implementation of the business methods. There are two types: Container Managed
Persistence(CMP) and Bean-Managed Persistence(BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two types:
Stateless and Stateful. Stateless bean is the simplest bean. It doesn’t maintain any
conversational state with clients between method invocations. Stateful bean maintains state
between invocations.
Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference
to the client. Create me a new EJB Object through Home Object interface. Create EJB Object
from the Ejb Object. Return EJB Object reference to the client. Invoke business method using
EJB Object reference. Delegate request to Bean (Enterprise Bean).
11 . 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-by-reference 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 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 EJBs 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.
12 . The EJB container implements the EJBHome and EJBObject classes. For every request from a
unique client, does the container create a separate instance of the generated EJBHome and
EJBObject classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB
Home reference irrespective of the client request. while refering the EJB Object classes the
container creates a separate instance for each client request. The instance pool maintenance is
up to the implementation of the container. If the container provides one, it is available
otherwise it is not mandatory for the provider to implement it. Having said that, yes most of
the container providers implement the pooling functionality to increase the performance of the
application server. The way it is implemented is, again, up to the implementer.
13 . Can the primary key in the entity bean be a Java primitive type such as int?
The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For
example, you can use java.lang.Integer as the primary key class, but not int (it has to be a
class, not a primitive).
The developer, according to the specification, cannot directly control when passivation occurs.
Although for Stateful Session Beans, the container cannot passivate an instance that is inside
a transaction. So using transactions can be a a strategy to control passivation. The
ejbPassivate() method is called during passivation, so the developer has control over what to
do during this exercise and can implement the require optimized logic. Some EJB containers,
such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls.
Taken from the WebLogic 6.0 DTD -The passivation-strategy can be either default or
transaction. With the default setting the container will attempt to keep a working set of beans
in the cache. With the transaction setting, the container will passivate the bean after every
transaction (or method call for a non-transactional invocation).
15 . What is the advantage of using Entity bean for database operations, over directly using JDBC
API to do database operations? When would I use one over the other?
Entity Beans actually represents the data in a database. It is not that Entity Beans replaces
JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In
Container Managed Entity Bean - Whenever the instance of the bean is created the container
automatically retrieves the data from the DB/Persistance storage and assigns to the object
variables in bean for user to manipulate or use them. For this the developer needs to map the
fields in the database to the variables in deployment descriptor files (which varies for each
vendor). In the Bean Managed Entity Bean - The developer has to specifically make
connection, retrive values, assign them to the objects in the ejbLoad() which will be called by
the container when it instatiates a bean object. Similarly in the ejbStore() the container saves
the object values back the the persistance storage. ejbLoad and ejbStore are callback methods
and can be only invoked by the container. Apart from this, when you use Entity beans you
dont need to worry about database transaction handling, database connection pooling etc.
which are taken care by the ejb container.
EJB QL is a Query Language provided for navigation across a network of enterprise beans and
dependent objects defined by means of container managed persistence. EJB QL is introduced
in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity
beans with container managed persistenceand is portable across containers and persistence
managers. EJB QL is used for queries of two types of finder methods: Finder methods that are
defined in the home interface of an entity bean and which return entity objects. Select
methods, which are not exposed to the client, but which are used by the Bean Provider to
select persistent values that are maintained by the Persistence Manager or to select entity
objects that are related to the entity bean on which the query is defined.
EJB was originally designed around remote invocation using the Java Remote Method
Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for
these calls using RMI/IIOP. This design allowed for maximum flexibility in developing
applications without consideration for the deployment scenario, and was a strong feature in
support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is,
some or all of their EJB calls are between beans in a single container. With this feedback in
mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface
may be defined for a bean during development, to allow streamlined calls to the bean if a
caller is in the same container. This does not involve the overhead involved with RMI like
marshalling etc. This facility will thus improve the performance of applications in which co-
location is planned. Local interfaces also provide the foundation for container-managed
relationships among entity beans with container-managed persistence.
18 . What are the special design care that must be taken when you work with local interfaces?
It is important to understand that the calling semantics of local interfaces are different from
those of remote interfaces. For example, remote interfaces pass parameters using call-by-
value semantics, while local interfaces use call-by-reference. This means that in order to use
local interfaces safely, application developers need to carefully consider potential deployment
scenarios up front, then decide which interfaces can be local and which remote, and finally,
develop the application code with these choices in mind. While EJB 2.0 local interfaces are
extremely useful in some situations, the long-term costs of these choices, especially when
changing requirements and component reuse are taken into account, need to be factored into
the design decision.
In case of a stateless session bean it may not matter if we call or not as in both cases nothing
is done. The number of beans in cache is managed by the container. In case of stateful
session bean, the bean may be kept in cache till either the session times out, in which case
the bean is removed or when there is a requirement for memory in which case the data is
cached and the bean is sent to free pool.
20 . What is the difference between Message Driven Beans and Stateless Session beans?
In several ways, the dynamic creation and allocation of message-driven bean instances mimics
the behavior of stateless session EJB instances, which exist only for the duration of a
particular method call. However, message-driven beans are different from stateless session
EJBs (and other types of EJBs) in several significant ways: Message-driven beans process
multiple JMS messages asynchronously, rather than processing a serialized sequence of
method calls. Message-driven beans have no home or remote interface, and therefore cannot
be directly accessed by internal or external clients. Clients interact with message-driven beans
only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly
interacts with a message-driven bean by creating bean instances and passing JMS messages
to those instances as necessary. The Container maintains the entire lifecycle of a message-
driven bean; instances cannot be created or removed as a result of client requests or other
API calls
EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the
other bean, then acquire an instance reference, and so forth.
EJBContext is an interface that is implemented by the container, and it is also a part of the
bean-container contract. Entity beans use a subclass of EJBContext called EntityContext.
Session beans use a subclass called SessionContext. These EJBContext objects provide the
bean class with information about its container, the client using the bean and the bean itself.
They also provide other functions. See the API docs and the spec for more details.
Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class
to obtain information about the declared members that are not otherwise accessible to the
enterprise bean because of the security rules of the Java language.
Although technically it is legal, static initializer blocks are used to execute some piece of code
before executing any constructor or method while instantiating a class. Static initializer blocks
are also typically used to initialize static fields - which may be illegal in EJB if they are
read/write - In EJB this can be achieved by including the code in either the ejbCreate(),
setSessionContext() or setEntityContext() methods.
Stopping the execution of a method inside a Session Bean is not possible without writing code
inside the Session Bean. This is because you are not allowed to access Threads inside an EJB.
There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that
the deployer must specify a value for the transaction attribute for those methods having
container managed transaction. In WebLogic, the default transaction attribute for EJB is
SUPPORTS.
27 . What is the difference between session and entity beans? When should I use one or the
other?
An entity bean represents persistent global data from the database; a session bean represents
transient user-specific data that will die when the user disconnects (ends his session).
Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call
entity beans (e.g. Account.deposit, Account.withdraw)
In other words whether a cache of the data in database will be maintained in EJB ? - Caching
data from a database inside the AAApplication Server are what Entity EJB’s are used for.The
ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the
persistent storage(database). Transactions also play an important role in this scenario. If data
is removed from the database, via an external application - your Entity Bean can still be alive
the EJB container. When the transaction commits, ejbStore() is called and the row will not be
found, and the transaction rolled back.
An Entity Bean represents persistent data that is stored outside of the EJB Container/Server.
The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the
container, similar to a SELECT statement in SQL. By making this method mandatory, the client
programmer can be assured that if they have the primary key of the Entity Bean, then they
can retrieve the bean without having to create a new bean each time - which would mean
creating duplications of persistent data and break the integrity of EJB.
With the EJBHome version of the remove, you are able to delete an entity bean without first
instantiating it (you can provide a PrimaryKey object as a parameter to the remove method).
The home version only works for entity beans. On the other hand, the Remote interface
version works on an entity bean that you have already instantiated. In addition, the remote
version also works on session beans (stateless and stateful) to inform the container of your
loss of interest in this bean.
EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the
other bean, then acquire an instance reference, and so forth.
An EJB server is an application, usually a product such as BEA WebLogic, that provides (or
should provide) for concurrent client connections and manages system resources such as
threads, processes, memory, database connections, network connections, etc. An EJB
container runs inside (or within) an EJB server, and provides deployed EJB beans with
transaction and security management, etc. The EJB container insulates an EJB bean from the
specifics of an underlying EJB server by providing a simple, standard API between the EJB
bean and its container. A Connector provides the ability for any Enterprise Information System
(EIS) to plug into any EJB server which supports the Connector architecture. See Sun’s J2EE
Connectors for more in-depth information on Connectors.
Persistence in EJB is taken care of in two ways, depending on how you implement your beans:
container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB
container which your beans run under takes care of the persistence of the fields you have
declared to be persisted with the database - this declaration is in the deployment descriptor.
So, anytime you modify a field in a CMP bean, as soon as the method you have executed is
finished, the new data is persisted to the database by the container. For BMP, the EJB bean
developer is responsible for defining the persistence routines in the proper places in the bean,
for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the
bean developer to make calls to the database. The container is responsible, in BMP, to call the
appropriate method on the bean. So, if the bean is being looked up, when the create() method
is called on the Home interface, then the container is responsible for calling the ejbCreate()
method in the bean, which should have functionality inside for going to the database and
looking up the data.
EJBContext is an interface that is implemented by the container, and it is also a part of the
bean-container contract. Entity beans use a subclass of EJBContext called EntityContext.
Session beans use a subclass called SessionContext. These EJBContext objects provide the
bean class with information about its container, the client using the bean and the bean itself.
They also provide other functions. See the API docs and the spec for more details.
No. The EJB specification specifically states that the enterprise bean is not allowed to use
thread primitives. The container is responsible for managing concurrent access to beans at
runtime.
37 37. Are we allowed to change the transaction isolation property in middle of a transaction?
No. You cannot change the transaction isolation level in the middle of transaction.
38 38. For Entity Beans, What happens to an instance field not mapped to any persistent storage,
when the bean is passivated?
The specification infers that the container never serializes an instance of an Entity bean (unlike
stateful session beans). Thus passivation simply involves moving the bean from the ready to
the pooled bin. So what happens to the contents of an instance variable is controlled by the
programmer. Remember that when an entity bean is passivated the instance gets logically
disassociated from it’s remote object. Be careful here, as the functionality of
passivation/activation for Stateless Session, Stateful Session and Entity beans is completely
different. For entity beans the ejbPassivate method notifies the entity bean that it is being
disassociated with a particular entity prior to reuse or for dereference.
39 39. What is a Message Driven Bean, what functions does a message driven bean have and how
do they work in collaboration with JMS?
Message driven beans are the latest addition to the family of component bean types defined
by the EJB specification. The original bean types include session beans, which contain business
logic and maintain a state associated with client sessions, and entity beans, which map objects
to persistent data. Message driven beans will provide asynchrony to EJB based applications by
acting as JMS message consumers. A message bean is associated with a JMS topic or queue
and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and
session beans, message beans do not have home or remote interfaces. Instead, message
driven beans are instantiated by the container as required. Like stateless session beans,
message beans maintain no client-specific state, allowing the container to optimally manage a
pool of message-bean instances. Clients send JMS messages to message beans in exactly the
same manner as they would send messages to any other JMS destination. This similarity is a
fundamental design goal of the JMS capabilities of the new specification. To receive JMS
messages, message driven beans implement the javax.jms.MessageListener interface, which
defines a single onMessage() method. When a message arrives, the container ensures that a
message bean corresponding to the message topic/queue exists (instantiating it if necessary),
and calls its onMessage method passing the client’s message as the single argument. The
message bean’s implementation of this method contains the business logic required to process
the message. Note that session beans and entity beans are not allowed to function as
message beans.
40 40. Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP
connection in the same way as RMI does across a JRMP connection?
Yes. The JDK 1.2 support the dynamic class loading. The EJB container implements the
EJBHome and EJBObject classes. For every request from a unique client
41 41. Does the container create a separate instance of the generated EJBHome and EJBObject
classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB
Home reference irrespective of the client request. while refering the EJB Object classes the
container creates a separate instance for each client request. The instance pool maintainence
is up to the implementation of the container. If the container provides one, it is available
otherwise it is not mandatory for the provider to implement it. Having said that, yes most of
the container providers implement the pooling functionality to increase the performance of the
application server. The way it is implemented is again up to the implementer
42 42. What is the advantage of putting an Entity Bean instance from the Ready State to Pooled
state?
The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has
been created, but has not been yet synchronized or assigned to an EJBObject. This mean that
the instances do represent entity beans, but they can be used only for serving Home methods
(create or findBy), since those methods do not relay on the specific values of the bean. All
these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon
Thorarinsson has also added: It can be looked at it this way: If no client is using an entity
bean of a particular type there is no need for cachig it (the data is persisted in the database).
Therefore, in such cases, the container will, after some time, move the entity bean from the
Ready State to the Pooled state to save memory. Then, to save additional memory, the
container may begin moving entity beans from the Pooled State to the Does Not Exist State,
because even though the bean’s cache has been cleared, the bean still takes up some memory
just being in the Pooled State.