SlideShare a Scribd company logo
1 of 14
1. What is the difference between Struts 1 vs Struts 2 ?
http://struts.apache.org/2.1.6/docs/comparing-struts-1-and-2.html
2. Which design pattern the Interceptors in Struts2 is based on ?
Interceptors in Struts2 are based on Intercepting Filters.
3. What are Pull-MVC and push-MVC based architecture ? Whicharchitecture does Struts2 follow ?
Pull-MVC and Push-MVC are better understood with how the view layer is getting data i.e. Model to render. In
case of Push-MVC the data( Model) is constructed and given to the view layer by the Controllers by putting it in
the scoped variables like request or session. Typical example is Spring MVC and Struts1. Pull-MVC on the
other hand puts the model data typically constructed in Controllers are kept in a common place i.e. in actions,
which then gets rendered by view layer. Struts2 is a Pull-MVC based architecture, in which all data is stored in
Value Stack and retrieved by view layer for rendering.
4. Are Interceptors in Struts2 thread safe ?
No,Unlike Struts2 action,Interceptors are shared between requests,so thread issues will come ifnottaken care
of.
5. Are Interceptors and Filters different ? , If yes then how ?
Apart from the fact that both Interceptors and filters are based on intercepting filter,there are few differences
when it comes to Struts2.
Filters: (1)Based on Servlet Specification (2)Executes on the pattern matches on the request.(3) No t
configurable method calls
Interceptors: (1)Based on Struts2. (2)Executes for all the request qualifies for a front controller( A Servlet filter
).And can be configured to execute additional interceptor for a particular action execution.(3)Methods in the
Interceptors can be configured whether to execute or not by means of excludemethods or includeMethods. (
see tutorial on this Controlling Interceptor Behavior)
6. In Struts1, the front-controller was a Servlet but in Struts2, it is a filter. What is the possible reason to
change it to a filter ?
There are two possibilities why filter is designated as front controller in Strtus 2
(1)Servlet made as front controller needs developer to provide a right value in <load-on-startup> which lets the
framework to initialize manyimportantaspects( viz. struts configuration file)as the container starts.In absense of
which the framework gets initialized only as the first request hits.Struts2 makes our life easy by providing front-
controller as a filter,and by nature the filters in web.xml gets initialized automatically as the container
starts.There is no need of such load-on-startup tag.
(2).The second butimportantone is , the introduction of Interceptors in Struts2 framework.It not just reduce our
coding effort,but helps us write any code which we would have used filters for coding and necessary change in
the web.xml as opposed to Struts1.So now any code that fits better in Filter can now moved to interceptors(
which is more controllable than filters),all configuration can be controlled in struts.xml file, no need to touch the
web.xml file.
(3).The front controller being a filter also helps towards the new feature of Struts ie UI Themes. All the static
resources in the Themes now served through the filter
7. Which class is the front-controller in Struts2 ?
The class "org.apache.struts2.dispatcher.FilterDispatcher " is the front controller in Struts2. In recent timeStruts
2.1.3 this class is deprecated and new classes are introduced to do the job.
Refer: http://struts.apache.org/2.1.8/struts2-core/apidocs/org/apache/struts2/dispatcher/FilterDispatcher.html
8. What is the role of Action/ Model ?
Actions in Struts are POJO , is also considered as a Model. The role of Action are to execute business logic or
delegate call to business logic by the means of action methods which is mapped to request and contains
business data to be used by the view layer by means of setters and getters inside the Action class and finally
helps the framework decide which result to render
9. How does Interceptors help achieve Struts2 a better framework than Struts1 ?
> Most of the trivial work are made easier to achieve for example automatic form population.
> Intelligent configuration and defaults for example you can have struts.xml or annotation based configuration
and out of box interceptors can provide facilities that a common web application needs
>Now Struts2 can be used anywhere in desktop applications also, with minimal or no change of existing web
application,since actions are now POJO.POJO actions are even easier to unit test.Thanks to interceptors
>Easier UI and validation in form of themes and well known DOJO framework.
>Highly plugable,Integrate other technologies like Spring,Hibernate etc at ease.
> Ready for next generation RESTFUL services
10. What is the relation between ValueStack and OGNL ?
A ValueStack is a place where all the data related to action and the action itself is stored. OGNL is a mean
through which the data in the ValueStack is manipulated.
11. Can annotation-based and XML based configuration of actions coexists ?
Yes
12. What is struts.devMode and why it is used ?
struts.devMode is a key used in struts.properties file (Can also be configured in struts.xml file as <constant
name="struts.devMode"value="true" />) , to representwhether the framework is running in development mode
or production mode by setting true or false. If set to development mode, it gives the following benefits : -
> Resource bundle reload on every request; i.e. all localization properties file can be modified and the change
will be reflected without restarting the server.
> struts.xml or any configuration files can be modified without restarting or redeploying the application
> The error occurs in the application will be reported, as oppose to production mode.
Also remember that struts.devMode should be marked as false in production environment to reduce impact of
performance. By default it is "false".
13. How do you configure the annotation based action mapping ?
14. What is the difference between empty default namespace and root name space ?
If the namespace attribute is not defined in the package tag or assigned "" value then it is called empty default
namespace.While if "/" is assigned as value to the namespace attribute then it is called as root namespace.
The root namespace is treated as all other explicit namespaces and must be matched. It’s important to
distinguish between the empty default namespace, which can catch all request patterns as long as the action
name matches, and the root namespace, which is an actual namespace that must be matched.
15. Which interceptor is responsible for setting action's JavaBean properties ?
com.opensymphony.xwork2.interceptor.ParametersInterceptor is the interceptor class who sets the action's
JavaBean properties from request.
16. What is the difference between Action and ActionSupport ?
Action is interface defines some string like SUCCESS,ERROR etc and an execute() method. For convenience
Developer implement this interface to have access to String field in action methods. ActionSupport on other
hand implements Action and some other interfaces and provides some feature like data validation and localized
error messaging when extended in the action classes by developers.
17. How do you get the HttpServletRequest object in an interceptor ?
Here is the intercept method
?
1
2
3
4
5
public String intercept(ActionInvocation invoke) throws Exception {
ActionContext action=invoke.getInvocationContext();
HttpServletRequest
req=(HttpServletRequest)action.get(StrutsStatics.HTTP_REQUEST);
return null;
}
In the similar way you can get the response, by using StrutsStatics.HTTP_RESPONSE in get() method as
above.
18. What is execute and wait interceptor ?
The ExecuteAndWaitInterceptor is greatinterceptor provided out of box in Struts2 for running long-lived actions
in the background while showing the user a nice progress meter or a progress bar.For example while uploading
a large file to the server we can use this interceptor to displaya nice running progress bar instead ofleaving the
user in confusion that the application is not responding.This also prevents the HTTP request from timing out
when the action takes more than 5 or 10 minutes.
19. Does the order in which interceptors execute matters ? If yes then why ?
Well, the answer is yes and no.Some Interceptors are designed to be independent so the order doesn't
matter,but some interceptors are totally dependent on the previous interceptors execution.For example the
validation and workflow interceptors,the validation interceptors checks if there is any error in the form being
submitted to the action,then comes the workflow interceptor who checks if validation ( occured in the last) has
any error,in presence of error it will not let the rest of the interceptors ( if any ) in the stack to execute.So this is
very important that the validation interceptors execute first before the workflow. On the other hand lets say you
wrote an interceptors who is doing the authentication and you have the user credential provided ( by the time
this executes) it doesn'tmatter where this interceptors is placed( It is a different fact that you would like to keep
it in the top ).
20. Who loads the struts.xml file ? Which Struts2 API loads the struts.xml file?
In Struts2 FilterServlet is the responsible class for loading struts.xml file as we deploy the application on the
container.Unlike Servlet(as with Struts1) needs the load-on-startup tag to load the front controller,a filter doesn't
need to have load on startup tag to be loaded as the application is deployed.As with servlet specification a filter
is loaded/executed as the application starts up.
21. What is the difference between RequestAware and ServletRequestAware interface ?
RequestAware and ServletRequestAware both makes your action to deals with the servlet request, but in a
difffrent ways,RequestAware gives you the attributes in the servletrequestas a map( key as attribute name and
value is the object added),But ServletRequestAware gives you the HttpServletRequest object itslef giving you
more flexibility, with a price that ServletRequestAware makes your Action class too much tied to the Servlet
environment making it dificult to unit test. So whenever a need to access only the attributes use the
RequestAware interface.
22. What is the difference between EL and OGNL ?
OGNL is much like EL in JSPs,a language to traverse or manupulate objects like request , session or
application in web context.OGNL stands for Object graph navigation language,which is used internally by
Struts2, however we are not bound to use OGNL in our JSPs, we can use EL.But OGNL provides much more
facilities than plain EL.For example while El interacts with the objects by means of getters/setters , OGNL
supports whatever EL does along with lambda experssion, helps create functions on fly. OGNL has more
flexible ways to deal with collection of objects.
23. What are the difference between ActionContext and ServletActionContext ?
ActionContext represents the context in which Action is executed, which itselfdoesn'thold any web parameters
like session,requestetc. ServletActionContext, extends the ActionContext and provides the web parameters to
the Action.
24. What is the life cycle of Interceptor ?
25. Who executes/Which class in Struts2 executes the interceptors ?
26. In what order the interceptors execute in an interceptor stack ?
27. What is action scope and how is it different from request scope ?
28. What happens if you don't call the invoke() method in any interceptors' intercept() method ?
29. How can two interceptors in a stack communicate or If you were to pass some value from one
interceptor to another, by using this value the next interceptor executes some specific statements, how
would you do it ?
30. What is dynamic method invocation ?
31. What is the DispatchAction (Struts1) equivalent in Strtus2 ?
Struts1 provided the facility of having related action methods in a Single Action class,depending on the method
parameter,the mapped methods were executed.To achieve this we have to extend the DispatchAction class in
Struts1.But this comes as default in Struts2, We need to provide the qualified methods in the action class( no
need to inherit any class), and provide the mapping of action path/name to the method attribute in action
tag(struts.xml) and proper code in view layer.
32. What is the difference between DispatchAction and dynamic method invocation in Struts2 ?
33. How many different ways can you retrive the request parameters from within interceptor ?
Two ways.
In the first way retrieve the HttpServletRequest from the ActionContext object and retrieve the parameters the
usual way. Code
?
1
2
3
ActionContext context=(ActionContext)invocation.getInvocationContext();
HttpServletRequest
request=(HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST);
String username=(String)request.getParameter("user");
The second way is pretty much the Struts2, by invoking the getParameters method on context object. Code
?
1
2
3
ActionContext
context=(ActionContext)invocation.getInvocationContext();
Map requestParameters=context.getParameters();
String usernames=((String[])m.get("user"))[0];
As you can see the map doesn't return the parameter as String unlike the Servlet specification, but an array of
String (can be convinient for multivalued UI controls check box,single value UI controls data can be retrived as
in above code ).
34. What is abstract package in Struts2, and what is its use ?
An abstract package usually defines inheritable components such as intercetpor,different interceptor
stacks,resulttypes etc.But doesn'tcontain any actions.The way we declare a package as abstractis through the
package elements attribute as abstract and setting the value to "true". By default ( if abstract attribute is not
mentioned) it is false.Struts-default.xml is an example of abstract package.
35. Does Struts2 mandates of implementing the Action interface in action classes to have the default
Action method (execute)?
Struts2 doesn't mind if the action classes doesn't implement the Action interface, to have the execute method
executed on default action method selection.Even though it appears that Action interfaces has the execute
method declaration and one must implement it to have the execute method overriden in the action
classes,Struts2 takes it as an informal contract with the developer by letting the developer to have an e xecute
method conforming to the signature of execute method.Whenever Struts2 finds any voilation to the declaration
of the method in unimplemented action class it throws the exeception.
Feature Struts 1 Struts 2
Action
classes
Struts 1 requires Action classes to extend
an abstract base class. A common
problem in Struts 1 is programming to
abstract classes instead of interfaces.
An Struts 2 Action may implement
an Action interface, along with other
interfaces to enable optional and custom
services. Struts 2 provides a base
ActionSupport class to implement commonly
used interfaces. Albeit, the Action interface
is not required. Any POJO object with
a execute signature can be used as an
Struts 2 Action object.
Threading Struts 1 Actions are singletons and must Struts 2 Action objects are instantiated for
Model be thread-safe since there will only be one
instance of a class to handle all requests
for that Action. The singleton strategy
places restrictions on what can be done
with Struts 1 Actions and requires extra
care to develop. Action resources must be
thread-safe or synchronized.
each request, so there are no thread-safety
issues. (In practice, servlet containers
generate many throw-away objects per
request, and one more object does not
impose a performance penalty or impact
garbage collection.)
Servlet
Dependency
Struts 1 Actions have dependencies on the
servlet API since the HttpServletRequest
and HttpServletResponse is passed to
the executemethod when an Action is
invoked.
Struts 2 Actions are not coupled to a
container. Most often the servlet contexts
are represented as simple Maps, allowing
Actions to be tested in isolation. Struts 2
Actions can still access the original request
and response, if required. However, other
architectural elements reduce or eliminate
the need to access the HttpServetRequest
or HttpServletResponse directly.
Testability A major hurdle to testing Struts 1 Actions is
that the execute method exposes the
Servlet API. A third-party extension, Struts
TestCase, offers a set of mock object for
Struts 1.
Struts 2 Actions can be tested by
instantiating the Action, setting properties,
and invoking methods. Dependency
Injection support also makes testing simpler.
Harvesting
Input
Struts 1 uses an ActionForm object to
capture input. Like Actions, all
ActionForms must extend a base class.
Since other JavaBeans cannot be used as
ActionForms, developers often create
redundant classes to capture input.
DynaBeans can used as an alternative to
creating conventional ActionForm classes,
but, here too, developers may be
redescribing existing JavaBeans.
Struts 2 uses Action properties as input
properties, eliminating the need for a
second input object. Input properties may be
rich object types which may have their own
properties. The Action properties can be
accessed from the web page via the taglibs.
Struts 2 also supports the ActionForm
pattern, as well as POJO form objects and
POJO Actions. Rich object types, including
business or domain objects, can be used as
input/output objects. The ModelDriven
feature simplifies taglb references to POJO
input objects.
Expression
Language
Struts 1 integrates with JSTL, so it uses
the JSTL EL. The EL has basic object
graph traversal, but relatively weak
collection and indexed property support.
Struts 2 can use JSTL, but the framework
also supports a more powerful and flexible
expression language called "Object Graph
Notation Language" (OGNL).
Binding
values into
views
Struts 1 uses the standard JSP
mechanism for binding objects into the
page context for access.
Struts 2 uses a "ValueStack" technology so
that the taglibs can access values without
coupling your view to the object type it is
rendering. The ValueStack strategy allows
reuse of views across a range of types
which may have the same property name
but different property types.
Type
Conversion
Struts 1 ActionForm properties are usually
all Strings. Struts 1 uses Commons-
Beanutils for type conversion. Converters
are per-class, and not configurable per
instance.
Struts 2 uses OGNL for type conversion.
The framework includes converters for basic
and common object types and primitives.
Validation Struts 1 supports manual validation via
a validate method on the ActionForm, or
through an extension to the Commons
Validator. Classes can have different
validation contexts for the same class, but
cannot chain to validations on sub-objects.
Struts 2 supports manual validation via
the validate method and the XWork
Validation framework. The Xwork Validation
Framework supports chaining validation into
sub-properties using the validations defined
for the properties class type and the
validation context.
Control Of
Action
Execution
Struts 1 supports separate Request
Processors (lifecycles) for each module,
but all the Actions in the module must
share the same lifecycle.
Struts 2 supports creating different lifecycles
on a per Action basis via Interceptor Stacks.
Custom stacks can be created and used
with different Actions, as needed.
Walkme throughthe 10 stepstruts 2 request flow. Pneumonic:
1. Request- Container- Filtersincl ActionContextCleanup(optional) and/elseFilterDispatcher
2. FilterDispatcherconsultsActionMapper
3. FilterDispatchercallsActionProxy
4. ActionInvocationcreatedbyActionProxy
5. Interceptorsbefore
6. Actionexecute
7. ResultandJSP
8. Interceptorsafter
9. Response returnedthroughFilters
10. FilterDispatchercleanuporActionContextCleanup
1. Requestgoestothe Servletcontainerandispassedthrougha standardfilterchainwiththe addition
of ActionContextCleanup(optional)andFilterDispatcher.
2. FilterDispatcherconsultsActionMappertosee if anActionis to be invoked.
3. If yes,FilterDispatcherdelegatescontrol toActionProxy.
4. ActionProxyconsultsconfigurationandcreatesanActionInvocationandinitiatesthe Interceptor
stack.
5. The before clause of eachInterceptoriscalleduntil the executemethodiscalledatthe bottomof
stack.
6. When the Action'sexecute methodcompletes,the ActionInvocationreferencesand executesthe
properresultaccording to configuration.
7. If appropriate,atemplate technologysuchasJSPis renderedincludingtags and urlsforadditional
requests.
8. Afterclause of each interceptoriscalled(Reverseordersince the callsare nested)
9. Response isreturnedthroughthe Servletfilters.
10. FilterDispatcherwillnotcleanupThreadLocal if ActionContextCleanupispresentbutdoes
otherwise.
How doesone create an ActioninStruts2? Struts2 usesreflectiontofindanappropriate method
whichbydefaultisthe execute method.Bestpractice howevershouldbe toimplementthe Action
interface orextendActionSupport.
What kindof MVC is Struts2? Struts2 is a frontcontrollerMVCwhichisto say that the userinteracts
withthe controllerbefore the UI.Yousenda requestanda controllerorActionrespondswiththe
mappedUI components.Whenexaminedfromthe push/pull perspective,Struts2isa Pull-MVCbased
architecture,inwhichall datais storedinValue Stackandretrievedbyview layerforrendering.
In struts.xml,whatdoesthe attribute "method"standsforinthe "action"tag? The methodattribute
tellsthe name of the methodinvokedaftersettingthe propertiesof the action.Thisattribute can hold
the name of the methodor the index of the resultmapping.
For example:
<action class="com.company.app.Login"method="login"name="login">
<resultname="success">/success.jsp</result>
</action>
<action class="com.company.app.Login"method="{1}"name="login">
<resultname="login">/success.jsp</result>
</action>
In both,the methodsignature is
publicStringlogin()
Are Interceptorsthreadsafe? No,and theyare supposedtobe statelessaccordingtothe
documentation.
Are Actionsthreadsafe? Struts2 actionsare but oldStruts1 actionswere not. New struts
actionsare createdpereach requestinStruts2.
How are InterceptorsandServletFiltersdifferent? 1. Filtersare part of the ServletAPI,
Interceptorsare Struts2.
2. The Interceptorstackfiresonrequestsina configuredpackage while filtersonlyapplytotheir
mappedURLs.
3. Interceptorscanbe configuredtoexecute ornotdependingonspecifictargetactionmethodsvia
excludeMethodsandincludeMethodswhile Filterslackthisfeature.
4. Filtersare an implementationof the InterceptingFilterpatternwhile Interceptorsare of the
Interceptorpattern.
What isstruts.devMode andwhyitisused? struts.devMode isakeyusedinstruts.propertiesfile or
a constant configuredinstruts.xml file.Itdeterminesif the frameworkisrunningindevelopmentor
productionmode &is boolean.Devmode givesthe followingbenefits:
1. Resource bundle reloadoneveryrequest;i.e.all localizationpropertiesfile canbe modifiedandthe
change will be reflectedwithoutrestartingthe server.
2. struts.xml orany configurationfilescanbe modifiedwithoutrestartingorredeployingthe application.
3. When errorsoccur in the applicationtheywill be displayedasstacktraces, as oppose toproduction
mode.
struts.devMode shouldbe markedasfalse inproductionenvironmenttoreduce impactof performance.
By defaultitis"false"
How can duplicate formsubmissionbe handledinStruts2? The problemof duplicate form
submissionariseswhenauserclicksthe Submitbuttonmore thanonce before the response issent
back. Thismay resultininconsistenttransactionsandmustbe avoided.InStrutsthisproblemcanbe
handledbyusingthe saveToken() andisTokenValid()methodsof Actionclass.saveToken() method
createsa token(a unique string) andsavesthatinthe user’scurrentsession,while isTokenValid() checks
if the tokenstoredinthe user’scurrentsessionisthe same asthat waspassedas the request
parameter.
Whats the difference betweenthe defaultnamespaceandthe rootnamespace?The defaultnamespace
is"" - an emptystring.The defaultnamespace isusedasa "catch-all"namespace.If anaction
configurationisnotfoundina specifiednamespace,the defaultnamespace isalsosearched.Root
Namespace:A rootnamespace ("/") isalsosupported.The rootisthe namespace whenarequest
directlyunderthe contextpathisreceived.Aswithothernamespaces,itwill fall backtothe default("")
namespace if a local actionisnot found.
What are Pull andPushMVC architecture andwhicharchitecture doesStruts2follow? In Push-MVC
the model datais giventothe viewlayerbyputtingitinscopedvariableslike requestorsession.Typical
example isSpringMVCandStruts1.
Pull-MVCsupposedlyputsthe model dataina commonplace i.e.inactions,whichthengetsrendered
by viewlayer.Struts2issupposedlyaPull-MVCbasedarchitecture,inwhichall dataisstoredinthe
Value Stackand retrievedbythe view layerforrendering.Idon'tagree withthisviewpointsince by
definitionof "view",itmustbe composedof pure HTML and/orJavaScript.Thusniethertagsnorthe
Value Stackcountsas "viewlayer"asbothof these are Java or handledbyJavabefore.
Q What is web work ?
Ans. Web work is open source web development framework struts 2 use this framework.
Q. What is Struts 2 ?
Ans. Struts 2 is open source java base web development framework .
Q . Difference between Struts1.2 and struts 2 ?
Ans.
# Struts 1.2 Struts 2.0
1. Follow MVC Architecture/ Model Follow MVC Architecture/ Model
2. Has Action and FormBean classes Has only Action class
3. Has Action for execute method
andFormBean for data
Data and execute() are defined in Action class
4. Action class is singleton and thread-
safe and has only one
instanceFormBean has instance per
request
Action has instance per request so do not need to be
thread-safe
5. Single validation.xml file created for
all FormBean validation.
Separate actionname-validation.xml files are created for
each action
6. Programmatic validation is done by
overriding FormBean.validate()
method
Programmatic validation is done by overriding
Action.validate() method
8. Configuration file isStruts-config.xml Configuration file is struts.xml
9. Frond controller is ActionServlet Front controller is interceptors
11. Container dependent Container independent
Q. Who populate the data from jsp to action in struts 2 ?
Ans. Interceptor are populate the data from jsp to action class in struts2.
Q. Who dose validation in struts 2.0 ?
Ans. Struts 2.0 provide the validation framework handle the validation in struts 2.0.
Q. What is validation framework ?
Ans. Validation framework is provide by struts 2 done the input validation .
Q. Which design pattern follow by struts 2.0?
Ans. Struts 2 use the Action Class as a Model and Action class follow by commend design pattern
so struts 2 follow command design pattern its also use Interceptor that are use front control design
pattern .
Q. What are the different result types in struts 2.0 ?
Ans. Struts 2 follow many result types
 Chain
 Dispatcher
 Redirect
 Redirect Action
 Tiles
 Stream
 Plain Text
 Json
By Default it’s result type is Dispatcher .
Q. What is difference between Redirect and Redirect Action result type in struts 2 ?
Ans. Main difference between redirect and redirect action is redirect use when we send redirect our
control one url to another url we use redirect. And when we redirect our control one action to another
action at this time we are use redirectaction result type.
Q. What is Action Context in struts 2 ?
Ans. Action Context is memory area where struts 2 tags are read and write the object’s. It content
value-Stack and Ognl .
Q. What is Value-Stack in struts 2.0 ?
Ans. Value Stack is the default memory area where struts2 tags are read and write the object (data
) with the help of OGNL(object graph Navigation language) .
Q. What is OGNL ?
Ans. OGNL stands for Object graph Navigation language . It’s expression language Struts 2 tags
are use OGNL to read and write the data and object for Action Context and Value-stack .
Q. Why struts 1.2 are container dependent and Struts 2 not container Dependent ?
Ans. In Struts 1.2 we are use Action Servlet that why its Container dependent . But Struts 2 Action
class Dose not use any container dependent object like HttpSession,HttpRequest,HttpResponse etc.
that are container dependent object that is the resin the struts 2 are not container dependent .
Q . What is Aware interfaces in struts 2 ?
Ans . Aware Interfaces are use to make a struts 2 container dependent if Your Application need any
Container Dependent object like Sssion ,Application, Request etc. You can use there
Respective aware interface to implement your Action class. Aware Interface are also use to achieve
the IOC in Struts 2.
Q. How many Types validation Support by Struts validation framework ?
Ans. Struts 2 Support two types validation
 Server side Validation
 Client side validation
Q. What is Business validation and Input Validation ?
Ans. Business Validation are those validation they are need to communicate with our data base like
“Your Login Failed ”etc. And Input Validation don’t need to communicate the database like null value
insert in any filed .
Q. How to achieve the localization and internalization in struts 2 ?
Ans. Struts 2 support the Localization and Internalization with the help of .properties file.
In this post i share some frequently asked interview question in struts2 . I hope this post is help you
to crack the interview.
Q. What is the work of ActionInvocation calss ?
Ans. Function of ActionInvocation class its invock the interceptor and action class.
Q. How many Action class in Struts 2 ?
Ans. Action Class object are create a every time when request is come .
Q. What is the function of Interceptor ? Can we create a our custom Interceptor ?
Ans. Interceptor in struts 2 work like Filter its check each and every request and perform the filtering
task in our application . Yes we can Create Our Own interceptor AbstractInterceptor .
Q. What is struts.devMode in struts.xml ?
Ans. Struts.devMode it’s use to represent your application is ether Development Mode Or
Production Mode by Setting True or false . If It’s true than Your Application is Development
Mode and it’s false Than your Application is Production Mode.
- See more at: http://www.javaaster.com/struts-2-interview-question-and-
answers/#sthash.RaLN5GeI.dpuf
Struts 2 Interview Questions
1) How to create an action with Struts2?
Creating an action in Struts2 is very different from Struts1 in the sense that there is no mandatory
requirement to extend a class from the struts library. A Java bean/POJO which has the private
member variables and public getters and setters is sufficient to become a struts action class. As
far as execute() method of Struts1 is concerned, a method with return type of String is sufficient.
The method name is to be specified in the struts.xml. This change is done so that the testing of
struts based application can be done easily.
2) In struts.xml, what does the attribute "method" stands for in the "action" tag?
The method attribute tells the name of method to be invoked after setting the properties of the
action class. This attribute can either hold the actual name of the method or the index of the
result mapping.
For example:
<action method="login" name="login">
<result name="success">/success.jsp</result>
</action>
<action method="{1}" name="login">
<result name="login">/success.jsp</result>
</action>
In both the examples, the method being invoked by Struts will be login with the signature as
public String login()
3) If I have an ArrayList of say Employees class in the struts action (which may be fetched
from the database), how can I iterate and display the Employee Id and Employee Name on
the next JSP being shown?
Assume the name of ArrayList to be employee.
We can iterate such a collection as:
<s:iterator value="employee">
<s:property value="name"></s:property>
<s:property value="id"></s:property>
</s:iterator>
4) What is the advantage of having a POJO class as an action?
POJO class is light weight and easy to test with frameworks like Junit. Moreover, there is no
need to create separate ActionForms to hold the values from the source web page.
5) What is the advantage of extending the action class from ActionSupport class?
The use of ActionSupport class provides the features like validation, locale support and
serialization to an action,
6) How can one integrate Spring IoC with Struts 2?
Struts 2 comes with support for Spring and Spring can be used to inject beans to various classes.
It can also be used to inject properties to the action class of struts 2. For configuring Spring,
contextLoaderListener can be configured.
7) What tool/IDE/frameworks do you use to write code in a Struts 2 web application?
Mostly it is MyEclipse 9 which has excellent support for struts 2. Netbeans 7 has support for
Struts 1 but not
Struts 2. Other that the IDE one can also mention tools like DreamWeaver, Spring, Hibernate,
XMLSpy etc.
8) What are the steps to migrate a web application written with Struts 1 to Struts 2?
This involves moving ActionForms of Struts1 to POJO properties of Struts 2.
Converting Struts1 struts-config.xml to struts.xml of Struts2.
Rewriting the Struts action classes for Struts 2.

More Related Content

What's hot

Open source APM Scouter로 모니터링 잘 하기
Open source APM Scouter로 모니터링 잘 하기Open source APM Scouter로 모니터링 잘 하기
Open source APM Scouter로 모니터링 잘 하기GunHee Lee
 
Threads 08: Executores e Futures
Threads 08: Executores e FuturesThreads 08: Executores e Futures
Threads 08: Executores e FuturesHelder da Rocha
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented ProgrammingRajesh Ganesan
 
Connecting Connect with Spring Boot
Connecting Connect with Spring BootConnecting Connect with Spring Boot
Connecting Connect with Spring BootVincent Kok
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxNir Elbaz
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in JavaJayant Dalvi
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafLAY Leangsros
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Edureka!
 

What's hot (20)

Open source APM Scouter로 모니터링 잘 하기
Open source APM Scouter로 모니터링 잘 하기Open source APM Scouter로 모니터링 잘 하기
Open source APM Scouter로 모니터링 잘 하기
 
Java 17
Java 17Java 17
Java 17
 
Threads 08: Executores e Futures
Threads 08: Executores e FuturesThreads 08: Executores e Futures
Threads 08: Executores e Futures
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
Connecting Connect with Spring Boot
Connecting Connect with Spring BootConnecting Connect with Spring Boot
Connecting Connect with Spring Boot
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
Swagger UI
Swagger UISwagger UI
Swagger UI
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Introduction to Grails
Introduction to GrailsIntroduction to Grails
Introduction to Grails
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
AngularJS
AngularJS AngularJS
AngularJS
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Jvm Architecture
Jvm ArchitectureJvm Architecture
Jvm Architecture
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
JSP Directives
JSP DirectivesJSP Directives
JSP Directives
 

Similar to What is the difference between struts 1 vs struts 2

Similar to What is the difference between struts 1 vs struts 2 (20)

Struts2.x
Struts2.xStruts2.x
Struts2.x
 
Skillwise Struts.x
Skillwise Struts.xSkillwise Struts.x
Skillwise Struts.x
 
Struts
StrutsStruts
Struts
 
Struts 2 – Interceptors
Struts 2 – InterceptorsStruts 2 – Interceptors
Struts 2 – Interceptors
 
Struts Interceptors
Struts InterceptorsStruts Interceptors
Struts Interceptors
 
important struts interview questions
important struts interview questionsimportant struts interview questions
important struts interview questions
 
Struts Interview Questions
Struts Interview QuestionsStruts Interview Questions
Struts Interview Questions
 
Struts2
Struts2Struts2
Struts2
 
Struts
StrutsStruts
Struts
 
Struts ppt 1
Struts ppt 1Struts ppt 1
Struts ppt 1
 
Struts 1
Struts 1Struts 1
Struts 1
 
Struts2 in a nutshell
Struts2 in a nutshellStruts2 in a nutshell
Struts2 in a nutshell
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
Struts
StrutsStruts
Struts
 
strut2
strut2strut2
strut2
 
Struts 2 Overview
Struts 2 OverviewStruts 2 Overview
Struts 2 Overview
 
Struts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web ApplicationsStruts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web Applications
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
Struts by l n rao
Struts by l n raoStruts by l n rao
Struts by l n rao
 

What is the difference between struts 1 vs struts 2

  • 1. 1. What is the difference between Struts 1 vs Struts 2 ? http://struts.apache.org/2.1.6/docs/comparing-struts-1-and-2.html 2. Which design pattern the Interceptors in Struts2 is based on ? Interceptors in Struts2 are based on Intercepting Filters. 3. What are Pull-MVC and push-MVC based architecture ? Whicharchitecture does Struts2 follow ? Pull-MVC and Push-MVC are better understood with how the view layer is getting data i.e. Model to render. In case of Push-MVC the data( Model) is constructed and given to the view layer by the Controllers by putting it in the scoped variables like request or session. Typical example is Spring MVC and Struts1. Pull-MVC on the other hand puts the model data typically constructed in Controllers are kept in a common place i.e. in actions, which then gets rendered by view layer. Struts2 is a Pull-MVC based architecture, in which all data is stored in Value Stack and retrieved by view layer for rendering. 4. Are Interceptors in Struts2 thread safe ? No,Unlike Struts2 action,Interceptors are shared between requests,so thread issues will come ifnottaken care of. 5. Are Interceptors and Filters different ? , If yes then how ? Apart from the fact that both Interceptors and filters are based on intercepting filter,there are few differences when it comes to Struts2. Filters: (1)Based on Servlet Specification (2)Executes on the pattern matches on the request.(3) No t configurable method calls Interceptors: (1)Based on Struts2. (2)Executes for all the request qualifies for a front controller( A Servlet filter ).And can be configured to execute additional interceptor for a particular action execution.(3)Methods in the Interceptors can be configured whether to execute or not by means of excludemethods or includeMethods. ( see tutorial on this Controlling Interceptor Behavior) 6. In Struts1, the front-controller was a Servlet but in Struts2, it is a filter. What is the possible reason to change it to a filter ? There are two possibilities why filter is designated as front controller in Strtus 2 (1)Servlet made as front controller needs developer to provide a right value in <load-on-startup> which lets the framework to initialize manyimportantaspects( viz. struts configuration file)as the container starts.In absense of which the framework gets initialized only as the first request hits.Struts2 makes our life easy by providing front- controller as a filter,and by nature the filters in web.xml gets initialized automatically as the container starts.There is no need of such load-on-startup tag. (2).The second butimportantone is , the introduction of Interceptors in Struts2 framework.It not just reduce our coding effort,but helps us write any code which we would have used filters for coding and necessary change in the web.xml as opposed to Struts1.So now any code that fits better in Filter can now moved to interceptors( which is more controllable than filters),all configuration can be controlled in struts.xml file, no need to touch the web.xml file. (3).The front controller being a filter also helps towards the new feature of Struts ie UI Themes. All the static resources in the Themes now served through the filter 7. Which class is the front-controller in Struts2 ? The class "org.apache.struts2.dispatcher.FilterDispatcher " is the front controller in Struts2. In recent timeStruts
  • 2. 2.1.3 this class is deprecated and new classes are introduced to do the job. Refer: http://struts.apache.org/2.1.8/struts2-core/apidocs/org/apache/struts2/dispatcher/FilterDispatcher.html 8. What is the role of Action/ Model ? Actions in Struts are POJO , is also considered as a Model. The role of Action are to execute business logic or delegate call to business logic by the means of action methods which is mapped to request and contains business data to be used by the view layer by means of setters and getters inside the Action class and finally helps the framework decide which result to render 9. How does Interceptors help achieve Struts2 a better framework than Struts1 ? > Most of the trivial work are made easier to achieve for example automatic form population. > Intelligent configuration and defaults for example you can have struts.xml or annotation based configuration and out of box interceptors can provide facilities that a common web application needs >Now Struts2 can be used anywhere in desktop applications also, with minimal or no change of existing web application,since actions are now POJO.POJO actions are even easier to unit test.Thanks to interceptors >Easier UI and validation in form of themes and well known DOJO framework. >Highly plugable,Integrate other technologies like Spring,Hibernate etc at ease. > Ready for next generation RESTFUL services 10. What is the relation between ValueStack and OGNL ? A ValueStack is a place where all the data related to action and the action itself is stored. OGNL is a mean through which the data in the ValueStack is manipulated. 11. Can annotation-based and XML based configuration of actions coexists ? Yes 12. What is struts.devMode and why it is used ? struts.devMode is a key used in struts.properties file (Can also be configured in struts.xml file as <constant name="struts.devMode"value="true" />) , to representwhether the framework is running in development mode or production mode by setting true or false. If set to development mode, it gives the following benefits : - > Resource bundle reload on every request; i.e. all localization properties file can be modified and the change will be reflected without restarting the server. > struts.xml or any configuration files can be modified without restarting or redeploying the application > The error occurs in the application will be reported, as oppose to production mode. Also remember that struts.devMode should be marked as false in production environment to reduce impact of performance. By default it is "false". 13. How do you configure the annotation based action mapping ? 14. What is the difference between empty default namespace and root name space ? If the namespace attribute is not defined in the package tag or assigned "" value then it is called empty default namespace.While if "/" is assigned as value to the namespace attribute then it is called as root namespace. The root namespace is treated as all other explicit namespaces and must be matched. It’s important to distinguish between the empty default namespace, which can catch all request patterns as long as the action name matches, and the root namespace, which is an actual namespace that must be matched.
  • 3. 15. Which interceptor is responsible for setting action's JavaBean properties ? com.opensymphony.xwork2.interceptor.ParametersInterceptor is the interceptor class who sets the action's JavaBean properties from request. 16. What is the difference between Action and ActionSupport ? Action is interface defines some string like SUCCESS,ERROR etc and an execute() method. For convenience Developer implement this interface to have access to String field in action methods. ActionSupport on other hand implements Action and some other interfaces and provides some feature like data validation and localized error messaging when extended in the action classes by developers. 17. How do you get the HttpServletRequest object in an interceptor ? Here is the intercept method ? 1 2 3 4 5 public String intercept(ActionInvocation invoke) throws Exception { ActionContext action=invoke.getInvocationContext(); HttpServletRequest req=(HttpServletRequest)action.get(StrutsStatics.HTTP_REQUEST); return null; } In the similar way you can get the response, by using StrutsStatics.HTTP_RESPONSE in get() method as above. 18. What is execute and wait interceptor ? The ExecuteAndWaitInterceptor is greatinterceptor provided out of box in Struts2 for running long-lived actions in the background while showing the user a nice progress meter or a progress bar.For example while uploading a large file to the server we can use this interceptor to displaya nice running progress bar instead ofleaving the user in confusion that the application is not responding.This also prevents the HTTP request from timing out when the action takes more than 5 or 10 minutes. 19. Does the order in which interceptors execute matters ? If yes then why ? Well, the answer is yes and no.Some Interceptors are designed to be independent so the order doesn't matter,but some interceptors are totally dependent on the previous interceptors execution.For example the validation and workflow interceptors,the validation interceptors checks if there is any error in the form being submitted to the action,then comes the workflow interceptor who checks if validation ( occured in the last) has any error,in presence of error it will not let the rest of the interceptors ( if any ) in the stack to execute.So this is very important that the validation interceptors execute first before the workflow. On the other hand lets say you wrote an interceptors who is doing the authentication and you have the user credential provided ( by the time this executes) it doesn'tmatter where this interceptors is placed( It is a different fact that you would like to keep it in the top ). 20. Who loads the struts.xml file ? Which Struts2 API loads the struts.xml file? In Struts2 FilterServlet is the responsible class for loading struts.xml file as we deploy the application on the container.Unlike Servlet(as with Struts1) needs the load-on-startup tag to load the front controller,a filter doesn't need to have load on startup tag to be loaded as the application is deployed.As with servlet specification a filter is loaded/executed as the application starts up.
  • 4. 21. What is the difference between RequestAware and ServletRequestAware interface ? RequestAware and ServletRequestAware both makes your action to deals with the servlet request, but in a difffrent ways,RequestAware gives you the attributes in the servletrequestas a map( key as attribute name and value is the object added),But ServletRequestAware gives you the HttpServletRequest object itslef giving you more flexibility, with a price that ServletRequestAware makes your Action class too much tied to the Servlet environment making it dificult to unit test. So whenever a need to access only the attributes use the RequestAware interface. 22. What is the difference between EL and OGNL ? OGNL is much like EL in JSPs,a language to traverse or manupulate objects like request , session or application in web context.OGNL stands for Object graph navigation language,which is used internally by Struts2, however we are not bound to use OGNL in our JSPs, we can use EL.But OGNL provides much more facilities than plain EL.For example while El interacts with the objects by means of getters/setters , OGNL supports whatever EL does along with lambda experssion, helps create functions on fly. OGNL has more flexible ways to deal with collection of objects. 23. What are the difference between ActionContext and ServletActionContext ? ActionContext represents the context in which Action is executed, which itselfdoesn'thold any web parameters like session,requestetc. ServletActionContext, extends the ActionContext and provides the web parameters to the Action. 24. What is the life cycle of Interceptor ? 25. Who executes/Which class in Struts2 executes the interceptors ? 26. In what order the interceptors execute in an interceptor stack ? 27. What is action scope and how is it different from request scope ? 28. What happens if you don't call the invoke() method in any interceptors' intercept() method ? 29. How can two interceptors in a stack communicate or If you were to pass some value from one interceptor to another, by using this value the next interceptor executes some specific statements, how would you do it ? 30. What is dynamic method invocation ? 31. What is the DispatchAction (Struts1) equivalent in Strtus2 ? Struts1 provided the facility of having related action methods in a Single Action class,depending on the method parameter,the mapped methods were executed.To achieve this we have to extend the DispatchAction class in Struts1.But this comes as default in Struts2, We need to provide the qualified methods in the action class( no need to inherit any class), and provide the mapping of action path/name to the method attribute in action tag(struts.xml) and proper code in view layer. 32. What is the difference between DispatchAction and dynamic method invocation in Struts2 ? 33. How many different ways can you retrive the request parameters from within interceptor ? Two ways. In the first way retrieve the HttpServletRequest from the ActionContext object and retrieve the parameters the usual way. Code ?
  • 5. 1 2 3 ActionContext context=(ActionContext)invocation.getInvocationContext(); HttpServletRequest request=(HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST); String username=(String)request.getParameter("user"); The second way is pretty much the Struts2, by invoking the getParameters method on context object. Code ? 1 2 3 ActionContext context=(ActionContext)invocation.getInvocationContext(); Map requestParameters=context.getParameters(); String usernames=((String[])m.get("user"))[0]; As you can see the map doesn't return the parameter as String unlike the Servlet specification, but an array of String (can be convinient for multivalued UI controls check box,single value UI controls data can be retrived as in above code ). 34. What is abstract package in Struts2, and what is its use ? An abstract package usually defines inheritable components such as intercetpor,different interceptor stacks,resulttypes etc.But doesn'tcontain any actions.The way we declare a package as abstractis through the package elements attribute as abstract and setting the value to "true". By default ( if abstract attribute is not mentioned) it is false.Struts-default.xml is an example of abstract package. 35. Does Struts2 mandates of implementing the Action interface in action classes to have the default Action method (execute)? Struts2 doesn't mind if the action classes doesn't implement the Action interface, to have the execute method executed on default action method selection.Even though it appears that Action interfaces has the execute method declaration and one must implement it to have the execute method overriden in the action classes,Struts2 takes it as an informal contract with the developer by letting the developer to have an e xecute method conforming to the signature of execute method.Whenever Struts2 finds any voilation to the declaration of the method in unimplemented action class it throws the exeception. Feature Struts 1 Struts 2 Action classes Struts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces. An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object. Threading Struts 1 Actions are singletons and must Struts 2 Action objects are instantiated for
  • 6. Model be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized. each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.) Servlet Dependency Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the executemethod when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly. Testability A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1. Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler. Harvesting Input Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans. Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglb references to POJO input objects. Expression Language Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL). Binding values into views Struts 1 uses the standard JSP mechanism for binding objects into the page context for access. Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types
  • 7. which may have the same property name but different property types. Type Conversion Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons- Beanutils for type conversion. Converters are per-class, and not configurable per instance. Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives. Validation Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects. Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context. Control Of Action Execution Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle. Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed. Walkme throughthe 10 stepstruts 2 request flow. Pneumonic: 1. Request- Container- Filtersincl ActionContextCleanup(optional) and/elseFilterDispatcher 2. FilterDispatcherconsultsActionMapper 3. FilterDispatchercallsActionProxy 4. ActionInvocationcreatedbyActionProxy 5. Interceptorsbefore 6. Actionexecute 7. ResultandJSP 8. Interceptorsafter
  • 8. 9. Response returnedthroughFilters 10. FilterDispatchercleanuporActionContextCleanup 1. Requestgoestothe Servletcontainerandispassedthrougha standardfilterchainwiththe addition of ActionContextCleanup(optional)andFilterDispatcher. 2. FilterDispatcherconsultsActionMappertosee if anActionis to be invoked. 3. If yes,FilterDispatcherdelegatescontrol toActionProxy. 4. ActionProxyconsultsconfigurationandcreatesanActionInvocationandinitiatesthe Interceptor stack. 5. The before clause of eachInterceptoriscalleduntil the executemethodiscalledatthe bottomof stack. 6. When the Action'sexecute methodcompletes,the ActionInvocationreferencesand executesthe properresultaccording to configuration. 7. If appropriate,atemplate technologysuchasJSPis renderedincludingtags and urlsforadditional requests. 8. Afterclause of each interceptoriscalled(Reverseordersince the callsare nested) 9. Response isreturnedthroughthe Servletfilters. 10. FilterDispatcherwillnotcleanupThreadLocal if ActionContextCleanupispresentbutdoes otherwise. How doesone create an ActioninStruts2? Struts2 usesreflectiontofindanappropriate method whichbydefaultisthe execute method.Bestpractice howevershouldbe toimplementthe Action interface orextendActionSupport. What kindof MVC is Struts2? Struts2 is a frontcontrollerMVCwhichisto say that the userinteracts withthe controllerbefore the UI.Yousenda requestanda controllerorActionrespondswiththe mappedUI components.Whenexaminedfromthe push/pull perspective,Struts2isa Pull-MVCbased architecture,inwhichall datais storedinValue Stackandretrievedbyview layerforrendering. In struts.xml,whatdoesthe attribute "method"standsforinthe "action"tag? The methodattribute tellsthe name of the methodinvokedaftersettingthe propertiesof the action.Thisattribute can hold the name of the methodor the index of the resultmapping. For example:
  • 9. <action class="com.company.app.Login"method="login"name="login"> <resultname="success">/success.jsp</result> </action> <action class="com.company.app.Login"method="{1}"name="login"> <resultname="login">/success.jsp</result> </action> In both,the methodsignature is publicStringlogin() Are Interceptorsthreadsafe? No,and theyare supposedtobe statelessaccordingtothe documentation. Are Actionsthreadsafe? Struts2 actionsare but oldStruts1 actionswere not. New struts actionsare createdpereach requestinStruts2. How are InterceptorsandServletFiltersdifferent? 1. Filtersare part of the ServletAPI, Interceptorsare Struts2. 2. The Interceptorstackfiresonrequestsina configuredpackage while filtersonlyapplytotheir mappedURLs. 3. Interceptorscanbe configuredtoexecute ornotdependingonspecifictargetactionmethodsvia excludeMethodsandincludeMethodswhile Filterslackthisfeature. 4. Filtersare an implementationof the InterceptingFilterpatternwhile Interceptorsare of the Interceptorpattern. What isstruts.devMode andwhyitisused? struts.devMode isakeyusedinstruts.propertiesfile or a constant configuredinstruts.xml file.Itdeterminesif the frameworkisrunningindevelopmentor productionmode &is boolean.Devmode givesthe followingbenefits: 1. Resource bundle reloadoneveryrequest;i.e.all localizationpropertiesfile canbe modifiedandthe change will be reflectedwithoutrestartingthe server. 2. struts.xml orany configurationfilescanbe modifiedwithoutrestartingorredeployingthe application.
  • 10. 3. When errorsoccur in the applicationtheywill be displayedasstacktraces, as oppose toproduction mode. struts.devMode shouldbe markedasfalse inproductionenvironmenttoreduce impactof performance. By defaultitis"false" How can duplicate formsubmissionbe handledinStruts2? The problemof duplicate form submissionariseswhenauserclicksthe Submitbuttonmore thanonce before the response issent back. Thismay resultininconsistenttransactionsandmustbe avoided.InStrutsthisproblemcanbe handledbyusingthe saveToken() andisTokenValid()methodsof Actionclass.saveToken() method createsa token(a unique string) andsavesthatinthe user’scurrentsession,while isTokenValid() checks if the tokenstoredinthe user’scurrentsessionisthe same asthat waspassedas the request parameter. Whats the difference betweenthe defaultnamespaceandthe rootnamespace?The defaultnamespace is"" - an emptystring.The defaultnamespace isusedasa "catch-all"namespace.If anaction configurationisnotfoundina specifiednamespace,the defaultnamespace isalsosearched.Root Namespace:A rootnamespace ("/") isalsosupported.The rootisthe namespace whenarequest directlyunderthe contextpathisreceived.Aswithothernamespaces,itwill fall backtothe default("") namespace if a local actionisnot found. What are Pull andPushMVC architecture andwhicharchitecture doesStruts2follow? In Push-MVC the model datais giventothe viewlayerbyputtingitinscopedvariableslike requestorsession.Typical example isSpringMVCandStruts1. Pull-MVCsupposedlyputsthe model dataina commonplace i.e.inactions,whichthengetsrendered by viewlayer.Struts2issupposedlyaPull-MVCbasedarchitecture,inwhichall dataisstoredinthe Value Stackand retrievedbythe view layerforrendering.Idon'tagree withthisviewpointsince by definitionof "view",itmustbe composedof pure HTML and/orJavaScript.Thusniethertagsnorthe Value Stackcountsas "viewlayer"asbothof these are Java or handledbyJavabefore. Q What is web work ? Ans. Web work is open source web development framework struts 2 use this framework. Q. What is Struts 2 ?
  • 11. Ans. Struts 2 is open source java base web development framework . Q . Difference between Struts1.2 and struts 2 ? Ans. # Struts 1.2 Struts 2.0 1. Follow MVC Architecture/ Model Follow MVC Architecture/ Model 2. Has Action and FormBean classes Has only Action class 3. Has Action for execute method andFormBean for data Data and execute() are defined in Action class 4. Action class is singleton and thread- safe and has only one instanceFormBean has instance per request Action has instance per request so do not need to be thread-safe 5. Single validation.xml file created for all FormBean validation. Separate actionname-validation.xml files are created for each action 6. Programmatic validation is done by overriding FormBean.validate() method Programmatic validation is done by overriding Action.validate() method 8. Configuration file isStruts-config.xml Configuration file is struts.xml 9. Frond controller is ActionServlet Front controller is interceptors 11. Container dependent Container independent Q. Who populate the data from jsp to action in struts 2 ? Ans. Interceptor are populate the data from jsp to action class in struts2. Q. Who dose validation in struts 2.0 ? Ans. Struts 2.0 provide the validation framework handle the validation in struts 2.0. Q. What is validation framework ? Ans. Validation framework is provide by struts 2 done the input validation . Q. Which design pattern follow by struts 2.0? Ans. Struts 2 use the Action Class as a Model and Action class follow by commend design pattern so struts 2 follow command design pattern its also use Interceptor that are use front control design pattern . Q. What are the different result types in struts 2.0 ? Ans. Struts 2 follow many result types  Chain  Dispatcher  Redirect  Redirect Action
  • 12.  Tiles  Stream  Plain Text  Json By Default it’s result type is Dispatcher . Q. What is difference between Redirect and Redirect Action result type in struts 2 ? Ans. Main difference between redirect and redirect action is redirect use when we send redirect our control one url to another url we use redirect. And when we redirect our control one action to another action at this time we are use redirectaction result type. Q. What is Action Context in struts 2 ? Ans. Action Context is memory area where struts 2 tags are read and write the object’s. It content value-Stack and Ognl . Q. What is Value-Stack in struts 2.0 ? Ans. Value Stack is the default memory area where struts2 tags are read and write the object (data ) with the help of OGNL(object graph Navigation language) . Q. What is OGNL ? Ans. OGNL stands for Object graph Navigation language . It’s expression language Struts 2 tags are use OGNL to read and write the data and object for Action Context and Value-stack . Q. Why struts 1.2 are container dependent and Struts 2 not container Dependent ? Ans. In Struts 1.2 we are use Action Servlet that why its Container dependent . But Struts 2 Action class Dose not use any container dependent object like HttpSession,HttpRequest,HttpResponse etc. that are container dependent object that is the resin the struts 2 are not container dependent . Q . What is Aware interfaces in struts 2 ? Ans . Aware Interfaces are use to make a struts 2 container dependent if Your Application need any Container Dependent object like Sssion ,Application, Request etc. You can use there Respective aware interface to implement your Action class. Aware Interface are also use to achieve the IOC in Struts 2. Q. How many Types validation Support by Struts validation framework ? Ans. Struts 2 Support two types validation  Server side Validation  Client side validation Q. What is Business validation and Input Validation ? Ans. Business Validation are those validation they are need to communicate with our data base like “Your Login Failed ”etc. And Input Validation don’t need to communicate the database like null value insert in any filed . Q. How to achieve the localization and internalization in struts 2 ? Ans. Struts 2 support the Localization and Internalization with the help of .properties file.
  • 13. In this post i share some frequently asked interview question in struts2 . I hope this post is help you to crack the interview. Q. What is the work of ActionInvocation calss ? Ans. Function of ActionInvocation class its invock the interceptor and action class. Q. How many Action class in Struts 2 ? Ans. Action Class object are create a every time when request is come . Q. What is the function of Interceptor ? Can we create a our custom Interceptor ? Ans. Interceptor in struts 2 work like Filter its check each and every request and perform the filtering task in our application . Yes we can Create Our Own interceptor AbstractInterceptor . Q. What is struts.devMode in struts.xml ? Ans. Struts.devMode it’s use to represent your application is ether Development Mode Or Production Mode by Setting True or false . If It’s true than Your Application is Development Mode and it’s false Than your Application is Production Mode. - See more at: http://www.javaaster.com/struts-2-interview-question-and- answers/#sthash.RaLN5GeI.dpuf Struts 2 Interview Questions 1) How to create an action with Struts2? Creating an action in Struts2 is very different from Struts1 in the sense that there is no mandatory requirement to extend a class from the struts library. A Java bean/POJO which has the private member variables and public getters and setters is sufficient to become a struts action class. As far as execute() method of Struts1 is concerned, a method with return type of String is sufficient. The method name is to be specified in the struts.xml. This change is done so that the testing of struts based application can be done easily. 2) In struts.xml, what does the attribute "method" stands for in the "action" tag? The method attribute tells the name of method to be invoked after setting the properties of the action class. This attribute can either hold the actual name of the method or the index of the result mapping. For example: <action method="login" name="login"> <result name="success">/success.jsp</result> </action> <action method="{1}" name="login">
  • 14. <result name="login">/success.jsp</result> </action> In both the examples, the method being invoked by Struts will be login with the signature as public String login() 3) If I have an ArrayList of say Employees class in the struts action (which may be fetched from the database), how can I iterate and display the Employee Id and Employee Name on the next JSP being shown? Assume the name of ArrayList to be employee. We can iterate such a collection as: <s:iterator value="employee"> <s:property value="name"></s:property> <s:property value="id"></s:property> </s:iterator> 4) What is the advantage of having a POJO class as an action? POJO class is light weight and easy to test with frameworks like Junit. Moreover, there is no need to create separate ActionForms to hold the values from the source web page. 5) What is the advantage of extending the action class from ActionSupport class? The use of ActionSupport class provides the features like validation, locale support and serialization to an action, 6) How can one integrate Spring IoC with Struts 2? Struts 2 comes with support for Spring and Spring can be used to inject beans to various classes. It can also be used to inject properties to the action class of struts 2. For configuring Spring, contextLoaderListener can be configured. 7) What tool/IDE/frameworks do you use to write code in a Struts 2 web application? Mostly it is MyEclipse 9 which has excellent support for struts 2. Netbeans 7 has support for Struts 1 but not Struts 2. Other that the IDE one can also mention tools like DreamWeaver, Spring, Hibernate, XMLSpy etc. 8) What are the steps to migrate a web application written with Struts 1 to Struts 2? This involves moving ActionForms of Struts1 to POJO properties of Struts 2. Converting Struts1 struts-config.xml to struts.xml of Struts2. Rewriting the Struts action classes for Struts 2.