Struts Interview Questions: (Received From Ramakrishna Potluri)

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 17

Struts Interview Questions

Q: What is Struts?
A: 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.
[ Received from Ramakrishna Potluri ]

Q: What is Jakarta Struts Framework?


A: 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 any size. Struts framework makes it much easier to design scalable, reliable Web applications
with Java.
Q: What is ActionServlet?
A: 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.
Q: How you will make available any Message Resources Definitions file to the Struts Framework
Environment?
A: T 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\" />.


Q: What is Action Class?
A: 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.
Q: What is ActionForm?
A: 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.
Q: What is Struts Validator Framework?
A: 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.

Q: Give the Details of XML files used in Validator Framework?


A: 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.
Q: How you will display validation fail errors on jsp page?
A: Following tag displays all the errors:
<html:errors/>

Q: How you will enable front-end validation based on the xml in validation.xml?
A: 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.
Q: How to get data from the velocity page in a action class?
A: We can get the values in the action classes by using data.getParameter(\"variable name defined in the
velocity page\");

DB Interview Questions

Q: What is SQL?
A: SQL stands for 'Structured Query Language'.
Q: What is SELECT statement?
A: The SELECT statement lets you select a set of values from a table in a database. The values selected from
the database table would depend on the various conditions that are specified in the SQL query.

Q: How can you compare a part of the name rather than the entire name?
A: SELECT * FROM people WHERE empname LIKE '%ab%'
Would return a recordset with records consisting empname the sequence 'ab' in empname .
Q: What is the INSERT statement?
A: The INSERT statement lets you insert information into a database.

Q: How do you delete a record from a database?


A: Use the DELETE statement to remove records or any particular column values from a database.

Q: How could I get distinct entries from a table?


A: The SELECT statement in conjunction with DISTINCT lets you select a set of distinct values from a table in a
database. The values selected from the database table would of course depend on the various conditions
that are specified in the SQL query. Example
SELECT DISTINCT empname FROM emptable
Q: How to get the results of a Query sorted in any order?
A: You can sort the results and return the sorted results to your program by using ORDER BY keyword thus
saving you the pain of carrying out the sorting yourself. The ORDER BY keyword is used for sorting.

SELECT empname, age, city FROM emptable ORDER BY empname


Q: How can I find the total number of records in a table?
A: You could use the COUNT keyword , example

SELECT COUNT(*) FROM emp WHERE age>40


Q: What is GROUP BY?
A: The GROUP BY keywords have been added to SQL because aggregate functions (like SUM) return the
aggregate of all column values every time they are called. Without the GROUP BY functionality, finding the
sum for each individual group of column values was not possible.
Q: What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a
table.
A: Dropping : (Table structure + Data are deleted), Invalidates the dependent objects ,Drops the indexes

Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete

Delete : (Data alone deleted), Doesn’t perform automatic commit


Q: What are the Large object types suported by Oracle?
A: Blob and Clob.
Q: Difference between a "where" clause and a "having" clause.
A: Having clause is used only with group functions whereas Where is not used with.

Q: What's the difference between a primary key and a unique key?


A: Both primary key and unique enforce uniqueness of the column on which they are defined. But by default
primary key creates a clustered index on the column, where are unique creates a nonclustered index by
default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL
only.
Q: What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can
you avoid cursors?
A: Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.

Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip,
where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are
also costly because they require more resources and temporary storage (results in more IO operations).
Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead of cursors.
Q: What are triggers? How to invoke a trigger on demand?
A: Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or
DELETE operation takes place on a table.

Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE,
DELETE) happens on the table on which they are defined.

Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the
referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as
constraints are much faster.

Q: What is a join and explain different types of joins.


A: Joins are used in queries to explain how different tables are related. Joins also let you select data from a
table depending upon data from another table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER
JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
Q: What is a self join?
A: Self join is just like any other join, except that two instances of the same table will be joined in the query.

Java Collection Interview Questions

Q: What is the Collections API?


A: The Collections API is a set of classes and interfaces that support operations on collections of objects.
Q: What is the List interface?
A: The List interface provides support for ordered collections of objects.
Q: What is the Vector class?
A: The Vector class provides the capability to implement a growable array of objects.
Q: What is an Iterator interface?
A: The Iterator interface is used to step through the elements of a Collection .
Q: Which java.util classes and interfaces support event handling?
A: The EventObject class and the EventListener interface support event processing.
Q: What is the GregorianCalendar class?
A: The GregorianCalendar provides support for traditional Western calendars
Q: What is the Locale class?
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or
cultural region .
Q: What is the SimpleTimeZone class?
A: The SimpleTimeZone class provides support for a Gregorian calendar .
Q: What is the Map interface?
A: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
Q: What is the highest-level event class of the event-delegation model?
A: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.
Q: What is the Collection interface?
A: The Collection interface provides support for the implementation of a mathematical bag - an unordered
collection of objects that may contain duplicates.
Q: What is the Set interface?
A: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not
allow duplicate elements.
Q: What is the typical use of Hashtable?
A: Whenever a program wants to store a key value pair, one can use Hashtable.
Q: I am trying to store an object using a key in a Hashtable. And some other object already exists in that
location, then what will happen? The existing object will be overwritten? Or the new object will be
stored elsewhere?
A: The existing object will be overwritten and thus it will be lost.
Q: What is the difference between the size and capacity of a Vector?
A: The size is the number of elements actually stored in the vector, while capacity is the maximum number of
elements it can store at a given instance of time.
Q: Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

Q: Can a ArrayList contain heterogenous objects?


A: Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.

Q: What is an enumeration?
A: An enumeration is an interface containing methods for accessing the underlying data structure from which
the enumeration is obtained. It is a construct which collection classes return when you request a collection
of all the objects stored in the collection. It allows sequential access to all the elements stored in the
collection.
Q: Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you
use ArrayList?
A: The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not.
Thus whenever there is a possibility of multiple threads accessing the same instance, one should use
Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non
synchronized data structure will give better performance than the synchronized one.
Q: Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

JSP Interview Questions

Q: What is a output comment?


A: A comment that is sent to the client in the viewable page source.The JSP engine handles an output
comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You
can see the comment by viewing the page source from your Web browser.
JSP Syntax
<!-- comment [ <%= expression %> ] -->

Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->

Displays in the page source:


<!-- This is a commnet sent to client on January 24, 2004 -->
Q: What is a Hidden Comment?
A: A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden
comment, and does not process any code within hidden comment tags. A hidden comment is not sent to
the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when
you want to hide or "comment out" part of your JSP page.

You can use any characters in the body of the comment except the closing --%> combination. If you need to
use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>

Examples
<%@ page language="java" %>
<html>
<head><title>A Hidden Comment </title></head>
<body>
<%-- This comment will not be visible to the colent in the page source --%>
</body>
</html>
Q: What is a Expression?
A: An expression tag contains a scripting language expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file. Because the value of an expression is converted to a
String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression
Q: What is a Declaration?
A: A declaration 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 they are separated by semicolons. The
declaration must be valid in the scripting language used in the JSP file.

<%! somedeclarations %>


<%! int i = 0; %>
<%! int a, b, c; %>
Q: What is a Scriptlet?
A: 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

1.Declare variables or methods to use later in the file (see also Declaration).
2.Write expressions valid in the page scripting language (see also Expression).

3.Use any of the JSP implicit objects or any object declared with a <jsp:useBean> tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet
produces output, the output is stored in the out object, from which you can display it.
Q: What are implicit objects? List them?
A: 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 re listed below
 request

 response

 pageContext

 session

 application

 out

 config

 page

 exception
Q: Difference between forward and sendRedirect?
A: When you invoke a forward request, the request is sent to another resource on the server, without the
client being informed that a different resource is going to process the request. This process occurs
completly with in the web container. When a sendRedirtect method is invoked, it causes the web container
to return to the browser indicating that a new URL should be requested. Because the browser issues a
completly new request any object that are stored as request attributes before the redirect occurs will be
lost. This extra round trip a redirect is slower than forward.
Q: What are the different scope valiues for the <jsp:useBean>?
A: The different scope values for <jsp:useBean> are

1. page
2. request
3.session
4.application
Q: Explain the life-cycle mehtods in JSP?
A: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp
package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet
interface of the javax.servlet package. the generated servlet class thus implements all the methods of the
these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that
must be implemented by all JSP pages regardless of the client-server protocol. However the JSP
specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests.
This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other
method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the
response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last
method called n the servlet instance.

JSP Interview Questions

Q: How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
A: 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
%>

Q: How does JSP handle run-time exceptions?


A: You can use the errorPage attribute of the page directive to have uncaught run-time 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\" %> 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.
Q: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
A: 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 .
Q: How do I use a scriptlet to initialize a newly instantiated bean?
A: 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 >

Q: 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?
A: 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="lastName" value="<%=blanknull(lastName)% >" >

Q: What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or
Synchronization?
A: Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not
scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit
synchronization for your shared data. The key however, is to effectively minimize the amount of code that is
synchronzied so that you take maximum advantage of multithreading.

Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most
serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that
case, all the unserviced requests are queued until something becomes free - which results in poor
performance. Since the usage is non-deterministic, it may not help much even if you did add more memory
and increased the size of the instance pool.

Q: How can I enable session tracking for JSP pages if the browser has disabled cookies?
A: 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 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());
%>
JSP Interview Questions

Q: What is the difference b/w variable declared inside a declaration part and variable declared in scriplet
part?
A: Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file
into servlet that variable will be in outside of service method or it will be declared as instance variable.And
the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a
variable inside a scriplet that variable will be declared inside a service method and the scope is with in the
service method.
Q: Is there a way to execute a JSP from the comandline or from my own application?
A: There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber
<[email protected]> & Peter Rossbach <[email protected]>) aim was not to write a full blown servlet engine,
but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific
features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated.
Nevertheless you can use it to precompile JSP for your website.
Servlet Interview Questions

Q: Explain the life cycle methods of a Servlet.


A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx()
methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and
finalized.
Q: What is the difference between the getRequestDispatcher(String path) method of
javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter
the path to the resource to be included or forwarded to, which can be relative to the request of the calling
servlet. If the path begins with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts


relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.
Q: Explain the directory structure of a web application.
A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.
WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory
Q: What are the common mechanisms used for session tracking?
A: Cookies
SSL sessions
URL- rewriting
Q: Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface
to get information such as initialization parameters for the web applicationor servlet container's version.
Every web application has one and only one ServletContext and is accessible to all active resource of that
application.
Q: What is preinitialization of a servlet?
A: A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a
request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-
startup> element, which can be specified in the deployment descriptor to make the servlet container load
and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in
is called preloading or preinitializing a servlet.
Q: What is the difference between Difference between doGet() and doPost()?
A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A
request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are
stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a
servlet only looking at a request string.
Q: What is the difference between HttpServlet and GenericServlet?
A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and
adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(),
doTrace() methods (HTTP 1.1).
Both these classes are abstract.
Q: What is the difference between ServletContext and ServletConfig?
A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for
example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is
contained within the ServletConfig object, which the Web server provides the servlet when the servlet is
initialized

ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is
created to pass initialization information to the servlet.
EJB Interview Questions

Q: What are the different kinds of enterprise beans?


A: Different kind of enterrise beans are Stateless session bean, Stateful session bean, Entity bean, Message-
driven bean...........

Q: What is Session Bean?


A: A session bean is a non-persistent object that implements some business logic running on the server. One
way to think of a session object...........
Q: What is Entity Bean?
A: The entity bean is used to represent data in the database. It provides an object-oriented interface to ...........

Q: What are the methods of Entity Bean?


A: An entity bean consists of 4 groups of methods, create methods...........

Q: What is the difference between Container-Managed Persistent (CMP) bean and Bean-Managed
Persistent(BMP) ?
A: Container-managed persistence (CMP) and bean-managed persistence (BMP). With CMP, the container
manages the persistence of the entity bean............

Q: What are the callback methods in Entity beans?


A: Callback methods allows the container to notify the bean of events in
its life cycle. The callback methods are defined in the javax.ejb.EntityBean interface............

Q: What is software architecture of EJB?


A: Session and Entity EJBs consist of 4 and 5 parts respectively, a remote interface...........

Q: Can Entity Beans have no create() methods?


A: Yes. In some cases the data is inserted NOT using Java application,...........

Q: What is bean managed transaction?


A: If a developer doesn't want a Container to manage transactions, it's possible to implement all database
operations manually...........

Q: What are transaction attributes?


A: The transaction attribute specifies how the Container must manage transactions for a method when a
client invokes the method via the enterprise bean’s home or...........

Q: What are transaction isolation levels in EJB?


A: Transaction_read_uncommitted , Transaction_read_committed , Transaction_repeatable_read...........

EJB Interview Questions


Q: How EJB Invocation happens?
A: Step 1: Retrieve Home Object reference from Naming Service via JNDI.
step 2: Return Home Object reference to the client.
step 3: Create me a new EJB Object through Home Object interface.
step 4: Create EJB Object from the Ejb Object
step 5: Return EJB Object reference to the client.
step 6: Invoke business method using EJB Object reference.
step 7: Delegate request to Bean (Enterprise Bean).
Q: 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?
A: 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 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.
Q: 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?
A: 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.
Q: Can the primary key in the entity bean be a Java primitive type such as int?
A: 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)
Q: Can you control when passivation occurs?
A: 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).
Q: 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?
A: 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. But in case of JDBC you have to explicitly do the above
features. what suresh told is exactly perfect. ofcourse, this comes under the database transations, but i
want to add this. the great thing about the entity beans of container managed, whenever the connection is
failed during the transaction processing, the database consistancy is mantained automatically. the
container writes the data stored at persistant storage of the entity beans to the database again to provide
the database consistancy. where as in jdbc api, we, developers has to do manually.
Q: What is EJB QL?
A: 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.
Q: Brief description about local interfaces?
A: EEJB 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.
Q: What are the special design care that must be taken when you work with local interfaces?
A: EIt 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.
Q: What happens if remove( ) is never invoked on a session bean?
A: 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.
Q: What is the difference between Message Driven Beans and Stateless Session beans?
A: 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 ic.

Note: 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.
Q: How can I call one EJB from inside of another EJB?
A: 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.
Q: What is an EJB Context?
A: 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.
Q: 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?
A: 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.

You might also like