JSF vs Struts

JSF and Struts – Comparison

JSF does:

1. Manages UI component state across requests. Struts does not have a notion of component state
2. Supports multi=page form processing.
3. Providing a strongly typed event model that allows the application to write server-side handlers (independent of HTTP) for client generated events. Faces brings a JavaBeans like event model to the web by using the ValueBinding API. Struts has nothing similar to this.
4. Validates request data and provides appropriate error reporting . Struts however has better error handling mechanisms.
5. Enables type conversion when migrating markup values (Strings) to and from application data objects (which are often not Strings). Automatic type conversion for UI input values is available in both Struts and JSF, but is more powerful with JSF.
6. Handles page-to-page navigation in response to UI events and model interactions.
7. The Action class, to which the request is submitted from the view, is tightly coupled to the ActionServlet. Nothing in JSF calls the FacesServlet.

Questions, Questions, Questions

Q. Give a tabular definition of common Collection classes.

Q. How would you classify exceptions?

Q Can we call ordinary methods from a synchronized method?

It is good programming advice not to call methods from inside a synchronized method because you may lose track of methods being called and end up in a deadlock because of bad programming. Don’t call any methods within a synchronized block except the class Object methods (wait, notify,).

Q What are the types of validation in Struts?

Validations in Struts are server side.
1. Server side using validation.xml without using javascript and
2. Validation using ValidatorForm with validate() method
In both cases the Form Bean needs to extend ValidatorForm. What you write in validation.xml is invoked by super.validate().
Struts framework reads validation.xml and puts some request attributes as error messages which gets passed on to the tag class behind


, which then creates html and sends it to the client.
If you are overriding the validate() method and plan to use both validation.xml as well as handcode the validate() method then you need to use super.validate().
validation.xml will still work if you don’t override the validate() method in your Form Bean extending ValidatorForm because it will inherit super’s validate() method.

Q How would you compare statement, prepared statement and callable statement in SQL?

Callable statement is a different animal, comparing it to queries is like apples and oranges.
Prepared statement is the faster of the two- statement and prepared statement. You write a query “select * from blah where foo=’a’” and next time it is “select * from blah where foo=’b’”, there is a slight change in passed parameter, but the database doesn’t know the difference. It will parse the second query without any memory of the first.
If you use the prepared statement with “?” as placeholder, then the database knows that the query does NOT need to be reparsed. It is cached internally, only the parameter value is changed.

Q Compare SAX and DOM parsers.

A DOM parser processes XML data and creates a tree representation of the document that you can navigate at run-time. The tree representation occupies memory and can be a major resource overhead.
The SAX parser on the other hand raises events that you can handle as you see fit.
Because of this design, the SAX implementation is generally faster and requires fewer resources. On the other hand, SAX code is frequently complex. A SAX parser is suitable for sequential and infrequent access while a DOM parser is more useful for frequent and random access.

Q Name some xsl:fo tags.

A snippet demonstrating use of some xsl:fo tags follows:

<xsl:stylesheet version="1.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
							<xsl:apply-templates select="category" />

	<xsl:template match="category">
			<xsl:value-of select="." />


An asset to our company

Q Name some xsl tags.

A snippet demonstrating use of xsl tags follows:


<xsl:for-each select="ENTRY">
	<xsl:for-each select="ENGLISH">
		<td width="25%">
			<xsl:if test="string(.)!='null'">
					<xsl:value-of select="." />



Q Name some JSF tags:

A snippet demonstrating JSF tags follows:

		<h:panelGrid id="grid1" columns="2" border="0" width="100%">
			<h:outputText id="text1" style="color: #000099;" value="Enter ISBN Code :" />
			<h:inputText value="#{authorBean.isbnCode}" />

A similar snippet using ADF faces would look like this:

<ui:define name="body">
	<div id="MyForm" class="HeaderBlock">
		<h:panelGrid columns="2">
			<af:outputLabel for="userName" value="Enter UserName " />
			<af:inputText id=" userName " columns="30"
				value="#{MyBean.userName}" maximumLength="40" />

Q What are the implicit variables in JSP, and what are their servlet equivalents?

Implicit vars in JSP       Scope           Servlet-Equivalent

application      application       ServletContext
request          request           HttpServletRequest
session          session           HttpSession
response                         HttpServletResponse
out                              PrintWriter
config                           ServletConfig
exception                        Throwable
page                             Object

Q Name some Ant tags.

<target name="war" depends="compile">
	<war warfile="${war}" webxml="${conf.dir}/web.xml">
		<classes dir="${build.classes.dir}">
			<include name="**/**" />
		</classes><!--All files included in this fileset will end up in the WEB-INF/classes
			directory of the war file -->
		<fileset dir="${css.dir}">
			<include name="**/**" />
		</fileset><!--places files from css dir(build) into root of the war -->
		<webinf dir="${conf.dir}">
			<include name="**/**" />
		</webinf><!--places files from conf dir(build) into WEB-INF of war -->
		<zipfileset dir="${images.dir}" prefix="images" />
		<!--places folder of images dir(build and places it in folder called "images"
			in root of war) > <lib dir="${jsf.lib.dir}"/><!--places files from lib(build
			into WEB-INF/lib folder of war) -->

Q what are inner and outer joins in SQL?

Inner joins will return all rows from multiple tables where the join condition(in the “where” clause) is met.
An outer join returns all rows from one table and only those rows from a secondary table where the joined fields are equal (join condition is met).

Q. Name some Struts tags:

Some Struts tags:

Struts html tags: <html:text../> <html:form../> <html:errors/> <html:submit../> <html:reset../>
Struts bean tags: <bean:write.../> <bean:message.../>
Struts logic tags: <logic:iterate../> <logic:empty.../>
Struts nested tags: <nested:write... /> <nested:iterate.../>
Struts tiles tags: <tiles:insert../> <tiles:put../>

What is connection pooling?

A connection pool is a cache of open connections that can be used and reused, thus cutting down on the overhead of creating and destroying database connections.

Q. Briefly describe Servlet and JSP life cycles.

Servlet Life Cycle

When the Servlet Container starts up, it looks for web.xml, which includes an entry for each of the servlet the application uses. The servlet creates an instance of the compiled class and loads it. Next the servlet is initialized with initialization parameters in the ServletConfig object. The servlet is initialized after init() method returns. (Lazy loading – The servlet container does not initialize the servlet as soon as it starts up but rather when it receives a specific request for that servlet for the first time).
After the servlet instance is initialized, it is ready to service client requests. When the servlet container no longer needs the servlet instance(such as when the container is shutting down, or it is running low on resources, or no request has arrived for that servlet for a long itme), the servlet instance again goes to the unloaded state and cannot service any requests. Once destroyed, the servlet instance is garbage collected.

JSP life cycle

For each client request, the jsp container checks if the JSP page is new or has already been converted to a class file. If so, page translation occurs where the jsp code is converted to a regular java file, after checking for translation time errors. This java file is then compiled into a class file after compile time errors are checked. Once an instance of the class file is loaded it follows the same life cycle pattern as a regular servlet except that the following methods are involved
jspInit() instead of init()
jspDestroy() instead of destroy()
The container calls _jspService(), which was created during translation time by the jsp container, for each request.

Common Interview Questions On Struts:

Q. What are the methods in a Struts Action Form?

An action form defines properties that have a one to one mapping with the html form elements in the JSP page. The Action Form needs to implement public getters and setters for these properties. Later versions of Struts do not require both a getter and setter for html form elements
Optional methods:
1. public ActionErrors validate(ActionMapping, HttpServletRequest req):
This method can be implemented when the ActionForm extends ValidatorForm. It is usually used with Java based validation and when complex validations that cannot be handled by validation.xml are involved. If a form extends ValidatorForm and does not provide the validate() method, the superclass validate() is inherited from the parent ValidatorForm that allows validation using validation.xml to be implemented. For validation involving both validation.xml and code within validate() one needs to implement the validate() method and configure validation.xml as well.
2. The reset() method:
The reset method allows one to set the values of all properties in the ActionForm to default values. It also allows one to initialize ActionForm properties within the body of the method. However with DynaActionForms reset() sets all properties to default values and does not allow one to initialize ActionForm properties.

Q What is the sequence of calls when an ActionForm is called by the ActionServlet?

The reset() method is called before the ActionForm is populated. Following this the setter methods are called to populate the ActionForm. Validate() is called if the ActionForm extends ValidatorForm.

Q. Describe the control flow when a request is submitted to a Struts application.

1. When the ActionServlet receives a request, the first thing it does is to check the ActionMappings defined in struts-config.xml to check for a matching path. ActionMappings are JavaBeans that Struts creates when reading the struts-config.xml at application startup.
2. Next the ActionServlet checks for the name attribute in the ActionMapping for the FormBean mapped to this ActionMapping. The corresponding ActionForm is instantiated and its setter methods are called to populate the ActionForm.
3. The type attribute is checked to instantiate the Action class and the perform()/execute() method is called on it. A reference to the ActionForm is passed as a parameter to the perform()/execute() method.
4. Depending on the outcome of perform()/execute() ActionMapping.findForward() is called which uses a single String attribute that matches one of the “name” attributes of the nested “forward” tags within the ActionMapping described in struts-config.xml. The “path” attribute of the “forward” tag determines the url to which the flow of control is altered to generate the response. An ActionForward can also be created dynamically within the Action class to specify the url to which the flow of control needs to be passed.

Q. Can an ActionMapping in struts-config.xml not have an Action class associated with it at all?

Yes. When an ActionMapping needs to directly transfer the flow of control to a JSP page without any processing to be done, the ActionForm need not be specified. In that case the “forward” attribute of the ActionMapping is used. “type” (which associates an Action class to the Action Mapping) and “forward” elements of an ActionMapping are mutually exclusive.

Q. Can a Struts application have multiple ActionServlets?

No. A single Struts application can have only a single ActionServlet associated with it. This is the Front Controller pattern. When the ActionServlet that acts as the FrontController in the Struts framework, receives a request it routes it to a handler class that performs business operations, usually using helper classes. The ActionServlet determines which business operations are related to which request by looking up the ActionMappings in the struts-config.xml. The multi-threaded handler class (Action class) handles business operations by calling helper classes. The handler class is passed the specifics of each request used in the operation.
When the Action class returns, the ActionServlet may have to lookup an ActionForward associated with the related mapping and pass the response to the url specified in it.

Q. What are the changes to be made to web.xml to configure Struts? Compare this with how the web.xml is modified to configure JSF.

A snippet in web.xml to configure the ActionServlet looks like this:

    <!--Could also be <url-pattern>/matty/*</url-pattern -->

When the parameter 1 is specified in the load-on-startup tag, the ActionServlet is the first servlet to be loaded on application startup. When 2 is specified other servlets with a values of 1 are loaded initially. Such servlets may perform initialization operations needed to be done before the ActionServlet is invoked by the container.

web.xml also has to define taglibs used by your Struts application. A snippet follows:


Additional configuration for nested taglib, tiles taglib may also be defined in web.xml when needed.

A typical configuration in web.xml for JSF looks like this:

    <servlet-name>Faces Servlet</servlet-name>
    <servlet-name>Faces Servlet</servlet-name>

Q. Can a Struts application have multiple struts-config.xml files?

Yes. The following is an example of how separate struts-config.xml may be configured in web.xml for “matt” and “tizz” modules in addition to the default module.


Q How do you handle errors in Struts?

The validate() method of the ActionForm returns an ActionErrors object.
A snippet:

ActionErrors errors = new ActionErrors();
errors add(ActionErrors.GLOBAL_ERROR), new ActionError(my.error));
return errors;

An Action class can also generate ActionErrors.
A snippet:

ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR), new ActionError(my.error));
saveErrors(request, errors);
return new ActionForward(mappings.getInput());

The errors in the ActionErrors object are displayed using the html:errors tag in the forwarded JSP.

Q What are DynaActionForms and DynaValidatorForms?

DynaActionForms allow FormBean creation by specifying them directly in the struts-config.xml. They cannot have reset() or validate() methods. All FormBean properties are set to default values before the FormBean is populated, without allowing initialization of FormBean properties.
DynaValidatorForms are similar to DynaActionForms but they use the validator framework by allowing properties to be validated using validation.xml settings.

Q Describe some common methods used to populate custom JavaBeans (Value Objects) from ActionForms.

1. The BeanUtils calss has a describe() method that returns a Map of a JavaBean’s public properties. It also offers a corresponding populate() method that will set the public properties of a JavaBean from a Map.

public class TestVO
private Map map;
//getters and setters for map

When we go from FormBean form to VO testVO

Map map = BeanUtils.describe(form);

When we go from VO testVO to FormBean form

Map map = testVO.getMap();
BeanUtils.populate(form, map);

2. You can use copyProperties() of BeanUtils class to populate your FormBean from any other bean using the Reflection API:

BeanUtils.copyProperties(myForm, MyBean);

The code in this snippet transfers the String properties in myForm to native types in myBean. It then transfers the native types in myBean back to the all String properties in myForm after business logic processing.
Converting non-native types such as Dates may requires a bit more effort.

3. Maps can be used as ActionForm properties. But a values from a Map is treated differently from a regular JavaBean property.

public class MyForm extends ActionForm {
	private Map map = null;

	// setters and getters for map
	public void setValue(String key, Object value) {
		getMap().put(key, value);

	public void getValue(String key) {
		return getMap().get(key);

One can access the elements of the map in the jsp page thus:

<html:text property=”value(someProperty)”/>


<bean:write name=”myForm” property= “value(someProperty)”/>