Struts Interview Questions: (Received From Ramakrishna Potluri)
Struts Interview Questions: (Received From Ramakrishna Potluri)
Struts Interview Questions: (Received From Ramakrishna Potluri)
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 ]
Example:
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: 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.
Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete
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.
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.
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.
Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->
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.
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.
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
%>
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 >
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;
}
%>
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
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.
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 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............
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.