Вы находитесь на странице: 1из 16

1.

Which design pattern the Interceptors in Struts2 is based on? a. Interceptors in Struts2 are based on Intercepting Filters.

2.

What is Pull-MVC and push-MVC based architecture? Which architecture does Struts2 follow?? a. 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.

3.

Are Interceptors in Struts2 thread safe? a. No, Unlike Struts2 action, Interceptors are shared between requests, so thread issues will come if not taken care of.

4.

Are Interceptors and Filters different? , If yes then how? a. Apart from the fact that both Interceptors and filters are based on intercepting filter, there are few differences when it comes to Struts2. i. 1. 2. 3. ii. 1. Filters: Based on Servlet Specification Executes on the pattern matches on the request. Not configurable method calls Interceptors: 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 exclude methods or include Methods. ( see tutorial on this Controlling Interceptor Behaviour)

5. 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? a. There are two possibilities why filter is designated as front controller in Struts 2

i. Servlet made as front controller needs developer to provide a right value in which lets the framework to initialize many important aspects (viz. struts configuration file) as the container starts. In absence 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-start-up tag. ii. The second but important one 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 move 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. iii. The front controller being a filter also helps towards the new feature of Struts i.e. UI Themes. All the static resources in the Themes now served through the filter

6.

Which class is the front-controller in Struts 2? a. The class "org.apache.struts2.dispatcher.FilterDispatcher is the front controller in Struts2. In recent time Struts 2.1.3 this class is deprecated and new classes are introduced to do the job. Refer: http://struts.apache.org/2.1.8/struts2core/apidocs/org/apache/struts2/dispatcher/FilterDispatcher.html

7.

What is the role of Action/ Model? a. 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

8.

How does Interceptors help achieve Struts2 a better framework than Struts1? a. Most of the trivial works 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 pluggable, Integrate other technologies like Spring, Hibernate etc. at ease. Ready for next generation RESTFUL services

9.

What is the relation between Value-Stack and OGNL? a. Value-Stack 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 Value-Stack is manipulated.

10. Can annotation-based and XML based configuration of actions coexists? a. Yes

11. What is struts.devMode and why it is used? a. struts.devMode is a key used in struts.properties file (Can also be configured in struts.xml file as) , to represent whether 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 : i. 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. ii. struts.xml or any configuration files can be modified without restarting or redeploying the application iii. 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".

12. What is the difference between empty default namespace and root name space? a. 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. Its 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.

13. Which interceptor is responsible for setting action's JavaBean properties? a. com.opensymphony.xwork2.interceptor.ParametersInterceptor is the interceptor class who sets the action's JavaBean properties from request.

14. What is the difference between Action and ActionSupport? a. 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.

15. How do you get the HttpServletRequest object in an interceptor? a. Here is the intercept method

01.public String intercept(ActionInvocation invoke) throws Exception { 02. 03.ActionContext action=invoke.getInvocationContext(); 04. 05.HttpServletRequest req=(HttpServletRequest)action.get(StrutsStatics.HTTP_REQUEST); 06. 07.return null; 08. 09.} In the similar way you can get the response, by using StrutsStatics.HTTP_RESPONSE in get() method as above.

16. What is execute and wait interceptor? a. The ExecuteAndWaitInterceptor is great interceptor 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 display a nice running progress bar instead of leaving 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.

17. Does the order in which interceptors execute matters? If yes then why? a. 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 (occurred 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't matter where this interceptors is placed( It is a different fact that you would like to keep it in the top ).

18. Who loads the struts.xml file? Which Struts2 API loads the struts.xml file? a. 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-start-up tag to load the front controller, a filter doesn't need to have load on start-up tag to be loaded as the application is deployed. As with servlet specification a filter is loaded/ executed as the application starts up.

19. What is the Dispatch Action (Struts1) equivalent in Strtus2? a. 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.

20. How many different ways can you retrieve the request parameters from within interceptor? a. Two ways.

In the first way retrieve the HttpServletRequest from the ActionContext object and retrieve the parameters the usual way. Code 1.ActionContext context=(ActionContext)invocation.getInvocationContext();

2. 3.HttpServletRequest request=(HttpServletRequest)context.get(StrutsStatics.HTTP_REQUEST); 4. 5.String username=(String)request.getParameter("user");

The second way is pretty much the Struts2, by invoking the getParameters method on context object. Code

1.ActionContext context=(ActionContext)invocation.getInvocationContext(); 2. 3.Map requestParameters=context.getParameters(); 4. 5.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 convenient for multivalued UI controls check box, single value UI controls data can be retrieved as in above code).

21. What is abstract package in Struts2, and what is its use? a. An abstract package usually defines inheritable components such as interceptor, different interceptor stacks, result types etc. But doesn't contain any actions. The way we declare a package as abstract is 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.

22. Does Struts2 mandates of implementing the Action interface in action classes to have the default Action method (execute)? a. 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 overridden in the action classes, Struts2 takes it as an informal contract with the developer by letting the developer to have an execute method conforming to the signature of execute method. Whenever Struts2 finds any violation to the declaration of the method in unimplemented action class it throws the exception.

23. Comparing Struts 1 and 2 Feature Struts 1 Struts 2 Action classes Struts 1 require Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces. Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provide 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 Struts 2 Action object. Threading Model Struts 1 Actions are singletons and must 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. Struts 2 Action objects are instantiated for 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 execute method 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 thirdparty 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 use as an alternative to creating conventional ActionForm classes, but, here too, developers may be re-describing 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 support 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 taglib references to POJO input objects. Expression Language Struts 1 integrate 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 "Value-Stack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The Value-Stack 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. 24. How to create an action with Struts2? a. 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.

25. In struts.xml, what does the attribute "method" stands for in the "action" tag? a. 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: /success.jsp /success.jsp In both the examples, the method being invoked by Struts will be login with the signature as public String login()

26. What is the advantage of having a POJO class as an action? a. As mentioned in the first question, the 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.

27. What is the advantage of extending the action class from ActionSupport class? a. The use of ActionSupport class provides the features like validation, locale support and serialization to an action

28. How can one integrate Spring IoC with Struts 2? a. Struts 2 come 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.

29. Describe the flow of a request in a Struts 2 web application? a. It can be best understood by using a diagram. Please refer the following URL for understanding the same. http://struts.apache.org/2.0.14/docs/the-struts-2-request-flow.html

30. What tool/IDE/frameworks do you use to write code in a Struts 2 web application? a. 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. 31. What are the steps to migrate a web application written with Struts 1 to Struts 2? a. 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

32. Change Struts URL extension suffix .do .action a. If you notice, many web applications deployed over the web have *.do or *.action at the end of URLs. One can deliberately use these kinds of urls. But usually it is the default behaviour of the framework/tool being used then a deliberate attempt by the developer. Struts based web applications are the widest of them to have .do or .action suffixes with URLs.

That is because of the numerous tutorials and books have adopted .do as a convention for Struts 1 based applications. The same applied to Struts 2. The good news is that one can easily change or get rid of extension suffixes in Struts 1 and Struts2. A question then arises as to how come the suffixed come into the URLs.

Struts 1 if we look at a form being written using Struts 1 tag libraries; it doesnt have any .do or .action. Here is a sample form in a JSP page of a Struts based application. action="/main">property="text">

As we can see that we are using the form tag of the struts-html tag library. So let us dig more into that tag by having a look at the struts-taglib.jar. Inside this library, look for org.apache.struts.taglib.html.FormTag.java

In the FormTag.java we can see the code for the attribute action: After analysing the code for FormTag.java, the URL pattern being used for mapping ActionServlet, is being used as the URL suffix by the custom tags. In the web.xml we generally have something like this:

1 2 3 4 actionServlet *.do

TO make all the URL to have suffix of .who instead of .do, change the mapping to:

1 2 3 4 actionServlet *.who

Struts 2

But if we look at the web.xml for struts 2 based application, we have 1 2 3 4 5 6 7 8 struts2D org.apache.struts2.dispatcher.FilterDispatcher

struts2D /*

So from where .action does come from? In case of Struts 2, the extension suffix comes from the property struts.action.extension.

The value for this property can be changed to any suitable value by setting this property in the struts.xml An example for changing the URL's in case of Struts 2 to .do is given below: 1 2 3 4 5 6 7 8 9 10 11

<> name="struts.action.extension"value="do">

<> extends="struts-default" name="default"namespace="/"> <action< span=""></action<> name="struts2"> login.jsp

With the above structure in the struts.xml, all the URL's will have .do as the extension suffix. Similarly, to get rid of the extension suffix at all, use the following xml code in struts.xml 1 2 3 4 5 6 7 8 9 10 11 <constant< span=""></constant<> name="struts.action.extension"value="">

<package< span=""></package<> extends="struts-default" name="default"namespace="/"> <action< span=""></action<> name="struts2"> login.jsp

33. The interceptors has the following life cycle. a. i. ii. iii. iv. Interceptor Object creation Initialization Intercept Destroy

34. How To Force The Action Mappings To Reload a. There can be situation in your project, when you might want to reload the struts.xml without even restarting the server or hot deploying the application. Remind you, that struts has the feature to reload the configuration and the properties file upon change and the first request hit if struts. devmode is set to true or more specifically "struts.configuration.xml.reload=true".

But hey , wait a minute, how do you reload this if the devmode is false or the struts.configuration.xml. reload is false, typically in a production environment ? Here is a small tutorial which can lets you do so. I used struts 2.0.6 , however later versions will have all most the same way to achieve this. Create an action class named "ReloadConfig.java" and have a method as follows 01.public String reload(){ 02. 03.ConfigurationManager configMan=Dispatcher.getInstance().getConfigurationManager(); 04. 05.configMan.reload(); 06. 07.return SUCCESS; 08. 09.} In struts.xml add the following code

1.<action< span=""></action<> name="reload" class="ReloadConfig"method="reload"> 2. 3.<result< span=""></result<> name="success"> ReloadConfirmation.jsp 4. 5. This will display the page ReloadConfirmation.jsp which displays message about the reload, whenever reload action is called executing the reload() method in ReloadConfig class.Create or a link in any jsp/html page which points to the reload action. 35. The filter chain includes: a. i. Action ContextCleanUp filter: The ActionContextCleanUp filter is optional and it is useful when integration has to be done with other technologies like SiteMash Plugin. ii. FilterDispatcher: Next the FilterDispatch is called, which in turn uses the ActionMapper to determine weather to invoke an Action. If the action is required to be invoked, the FilterDispatcher delegates the control to the ActionProxy. iii. ActionProxy: The ActionProxy takes the help from Configuration Files manager, which is initialized from the struts.xml. Then the ActionProxy creates an ActionInvocation, which implements the command pattern. The ActionInvocation process invokes the Interceptors (if configured) and then invokes the action. The ActionInvocation looks for proper result. Then the result is executed, which involves the rendering of JSP or templates.

Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file. If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.

Вам также может понравиться