Structs Interview Questions and Answers

  • Upload
    beepin

  • View
    232

  • Download
    0

Embed Size (px)

Citation preview

  • 8/7/2019 Structs Interview Questions and Answers

    1/39

    Structs Interview Questions and

    Answers

    What is Struts?Struts is a web page development framework and an open source software that helpsdevelopers build web applications quickly and easily. Struts combines Java Servlets,Java Server Pages, custom tags, and message resources into a unified framework. It isa cooperative, synergistic platform, suitable for development teams, independentdevelopers, and everyone between.

    How is the MVC design pattern used in Struts framework?

    In the MVC design pattern, application flow is mediated by a central Controller. TheController delegates requests to an appropriate handler. The handlers are tied to aModel, and each handler acts as an adapter between the request and the Model. The

    Model represents, or encapsulates, an application's business logic or state. Control isusually then forwarded back through the Controller to the appropriate View. Theforwarding can be determined by consulting a set of mappings, usually loaded from adatabase or configuration file. This provides a loose coupling between the View andModel, which can make an application significantly easier to create and maintain.Controller--Servlet controller which supplied by Struts itself; View --- what you cansee on the screen, a JSP page and presentation components; Model --- System stateand a business logic JavaBeans.

    Who makes the Struts?

    Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakartaproject, like Tomcat, Ant and Velocity.

    Why it called Struts?

    Because the designers want to remind us of the invisible underpinnings that hold upour houses, buildings, bridges, and ourselves when we are on stilts. This excellentdescription of Struts reflect the role the Struts plays in developing web applications.

    Do we need to pay the Struts if being used in commercial purpose?

    No. Struts is available for commercial use at no charge under the Apache SoftwareLicense. You can also integrate the Struts components into your own framework just

    as if they were written in house without any red tape, fees, or other hassles.

    What are the core classes of Struts?

    Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classesof Structs.

    What is the design role played by Struts?

    The role played by Structs is controller in Model/View/Controller(MVC) style. TheView is played by JSP and Model is played by JDBC or generic data source classes.The Struts controller is a set of programmable components that allow developers todefine exactly how the application interacts with the user.

  • 8/7/2019 Structs Interview Questions and Answers

    2/39

    How Struts control data flow?

    Struts implements the MVC/Layers pattern through the use of ActionForwards andActionMappings to keep control-flow decisions out of presentation layer.

    What configuration files are used in Struts?

    ApplicationResources.propertiesstruts-config.xmlThese two files are used to bridge the gap between the Controller and the Model.

    What helpers in the form of JSP pages are provided in Struts framework?

    --struts-html.tld--struts-bean.tld--struts-logic.tld

    Is Struts efficient?

    The Struts is not only thread-safe but thread-dependent(instantiates each Action onceand allows other requests to be threaded through the original object.ActionForm beans minimize subclass code and shorten subclass hierarchiesThe Struts tag libraries provide general-purpose functionalityThe Struts components are reusable by the applicationThe Struts localization strategies reduce the need for redundant JSPsThe Struts is designed with an open architecture--subclass availableThe Struts is lightweight (5 core packages, 5 tag libraries)The Struts is open source and well documented (code to be examined easily)The Struts is model neutral

    How you will enable front-end validation based on the xml in validation.xml?

    The < html:javascript > tag to allow front-end validation based on the xml invalidation.xml. For example the code: < html:javascript formName=logonFormdynamicJavascript=true staticJavascript=true / > generates the client side java scriptfor the form logonForm as defined in the validation.xml file. The < html:javascript >when added in the jsp file generates the client site validation script.

    What is ActionServlet?

    The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In thethe Jakarta Struts Framework this class plays the role of controller. All the requests to

    the server goes through the controller. Controller is responsible for handling all therequests.

    How you will make available any Message Resources Definitions file to the Struts

    Framework Environment?

    Message Resources Definitions file are simple .properties files and these files containsthe messages that can be used in the struts project. Message Resources Definitionsfiles can be added to the struts-config.xml file through < message-resources / > tag.Example: < message-resources parameter= MessageResources / >

    What is Action Class?The Action Class is part of the Model and is a wrapper around the business logic. The

  • 8/7/2019 Structs Interview Questions and Answers

    3/39

    purpose of Action Class is to translate the HttpServletRequest to the business logic.To use the Action, we need to Subclass and overwrite the execute() method. In theAction Class all the database/business processing are done. It is advisable to performall the database related stuffs in the Action Class. The ActionServlet (commad) passesthe parameterized class to Action Form using the execute() method. The return type of

    the execute method is ActionForward which is used by the Struts Framework toforward the request to the file as per the value of the returned ActionForward object.

    Write code of any Action Class?

    Here is the code of Action Class that returns the ActionForward object.import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;

    public class TestAction extends Action{public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{return mapping.findForward(\"testAction\");}}

    What is ActionForm?

    An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.ActionForm maintains the session state for web application and the ActionFormobject is automatically populated on the server side with data entered from a form onthe client side.

    What is Struts Validator Framework?

    Struts Framework provides the functionality to validate the form data. It can be use to

    validate the data on the users browser as well as on the server side. Struts Frameworkemits the java scripts and it can be used validate the form data on the client browser.Server side validation of form can be accomplished by sub classing your From Beanwith DynaValidatorForm class. The Validator framework was developed by DavidWinterfeldt as third-party add-on to Struts. Now the Validator framework is a part ofJakarta Commons project and it can be used with or without Struts. The Validatorframework comes integrated with the Struts Framework and can be used withoutdoing any extra settings.

    Give the Details of XML files used in Validator Framework?

    The Validator Framework uses two XML configuration files validator-rules.xml and

    validation.xml. The validator-rules.xml defines the standard validation routines, theseare reusable and used in validation.xml. to define the form specific validations. The

  • 8/7/2019 Structs Interview Questions and Answers

    4/39

    validation.xml defines the validations applied to a form bean. How you will displayvalidation fail errors on jsp page? - The following tag displays all the errors:

    Why do we need Struts?

    Java technologies give developers a serious boost when creating and maintainingapplications to meet the demands of today's public Web sites and enterprise intranets.Struts combines Java Servlets, Java ServerPages, custom tags, and message resourcesinto a unified framework. The end result is a cooperative, synergistic platform,suitable for development teams, independent developers, and everyone in between.

    How does Struts work?

    Java Servlets are designed to handle requests made by Web browsers. JavaServerPages are designed to create dynamic Web pages that can turn billboard sitesinto live applications. Struts uses a special Servlet as a switchboard to route requestsfrom Web browsers to the appropriate ServerPage. This makes Web applications

    much easier to design, create, and maintain.

    Is Struts compatible with other Java technologies?

    Yes. Struts is committed to supporting industry standards. Struts acts as an integratorof Java technologies so that they can be used in the "real world".

    Who wrote Struts?

    There are several active committers to the Struts project, working cooperatively fromaround the globe. Dozens of individual developers and committers contributed to theStruts 1.x codebase. All interested Java developers are invited to contribute to theproject. Struts is a Apache Software Foundation project, with the mission to "providesecure, enterprise-grade server solutions based on the Java Platform that aredeveloped in an open and cooperative fashion".Struts was created by Craig R. McClanahan and donated to The Apache SoftwareFoundation in May 2000. Craig was the primary developer of both Struts 1.x andTomcat 4. Tomcat 4 was the basis for the official reference implementation for aservlet 2.3 and JSP 1.2 container.Craig's current focus is as architect of the Sun Java Studio Creator (formerly ProjectRave). Craig also serves as the Specification Lead for JavaServer Faces (JSR-127),and is the Web Layer Architect for the Java2 Enterprise Edition (J2EE) platform as awhole.

    Why is it called Struts?

    It's a reference to struts in the architectural sense, a reminder of the nearly invisiblepieces that hold up buildings, houses, and bridges.

    Do I have to credit Struts on my own website?

    You need to credit Struts if you redistribute your own framework based on Struts forother people to use. (See the Apache License for details.) But you do not need tocredit Struts just because your web application utilizes the framework. It's the samesituation as using the Apache HTTPD server or Tomcat. Not required if its justrunning your web site.

  • 8/7/2019 Structs Interview Questions and Answers

    5/39

    Where can I get a copy of Struts?

    The best place to download Struts is at struts.apache.org. The nightly builds are verystable, and recommended as the best place to start today.

    How do I install Struts?

    To develop applications with Struts, you can usually just add the Struts JAR file toyour Java development environment. You can then start using the Struts classes aspart of your own application. A blank Struts application (in the webapps directory,open struts-blank.war) is provided, which you can just copy to get a quick-start onyour own brainchild.Since the full source code for Struts is available, we also provide completeinstructions for compiling your own Struts JAR from scratch. (This is actually easierthan it looks!)Your Struts application can usually be deployed using a standard WAR file. In mostcases, you simply deposit the WAR file on your application server, and it is installedautomatically. If not, step-by-step installation instructions for various servlet

    containers are available.

    When do I need "struts.jar" on my classpath?

    When you are compiling an application that uses the Struts classes, you must have the"struts.jar" on the classpath your compiler sees -- it does not have to be on yourCLASSPATH environment variable.Why is that an important distinction? Because if you are using a servlet container onyour development machine to test your application, the "struts.jar" must not be onyour CLASSPATH environment variable when running the container. (This isbecause each Web application must also have their own copy of the Struts classes,and the container will become confused if it is on the environment path as well.)There are several general approaches to this issue:* Use ANT for building your projects -- it can easily assemble classpaths for thecompiler. (This is how Struts itself is built, along with Tomcat and most other Java-based projects).* Use an IDE where you can configure the "class path" used for compilationindependent of the CLASSPATH environment variable.* Use a shell script that temporarily adds struts.jar to the classpath just forcompilation, for example javac -classpath /path/to/struts.jar:$CLASSPATH $@

    Does Struts include its own unit tests?

    Struts currently has two testing environments, to reflect the fact that some things canbe tested statically, and some really need to be done in the environment of a runningservlet container.For static unit tests, we use the JUnit framework. The sources for these tests are in the"src/test" hierarchy in the source repository, and are executed via the "test.junit" targetin the top-level build.xml file. Such tests are focused on the low-level functionality ofindividual methods, are particularly suitable for the static methods in theorg.apache.struts.util utility classes. In the test hierarchy, there are also some "mockobject" classes (in the org.apache.struts.mock package) so that you can package upthings that look like servlet API and Struts API objects to pass in as arguments tosuch tests.

    Another valuable tool is Struts TestCase which provides a useful harness for Actionclasses that can be used with JUnit or Cactus.

  • 8/7/2019 Structs Interview Questions and Answers

    6/39

    If the framework doesn't do what I want, can I request that a feature be added?

    First, it's important to remember that Struts is an all-volunteer project. We don'tcharge anyone anything to use Struts. Committers and other developers work onStruts because they need to use it with their own applications. If others can use it too,that's "icing on the cake". If you submit a patch for a feature that a Committer finds

    useful, then that Committer may choose to volunteer his or her time to apply thepatch. If you just submit an idea without a patch, it is much less likely to be added(since first someone else has to volunteer their time to write the patch).We are grateful for any patches, and we welcome new ideas, but the best way to seethat something gets added to the framework is to do as much of the work as you can,rather than rely on the "kindness of strangers". Worst case, you can apply the patch toyour copy of Struts and still use the feature in your own application. (Which is whatopen source is ~really~ all about.)

    Where can I get help with Struts?

    The Struts package comes complete with a Users Guide to introduce people to the

    framework and its underlying technologies. Various components also have their ownin-depth Developers Guide, to cover more advanced topics. Comprehensive Javadocsare included along with the full source code. For your convenience, these are bundledtogether as a self-installing application. The struts-documentation.war is the samebundle that is deployed as the Struts Web site.The Strut's mailing list is also very active, and welcomes posts from new users.Before posting a new question, be sure to consult the MAILING LIST ARCHIVE andthe very excellent How To Ask Questions The Smart Way by Eric Raymond. Pleasedo be sure to turn off HTML in your email client before posting.

    What's the difference between Struts and Turbine? What's the difference

    between Struts and Espresso?

    If you are starting from scratch, packages like Turbine and Espresso can be veryhelpful since they try to provide all of the basic services that your team is likely toneed. Such services include things like data persistence and logging.If you are not starting from scratch, and need to hook up your web application to anexisting infrastructure, then "plain vanilla" Struts can be a better choice. The coreStruts framework does not presuppose that you are using a given set of datapersistence, presentation, or logging tools. Anything goes =:0)Compared to other offerings, Struts endeavors to be a minimalist framework. We tryleverage existing technologies whenever we can and provide only the missing pieces

    you need to combine disparate technologies into a coherent application. This is greatwhen you want to select your own tools to use with Struts. But, if you prefer a moreintegrated infrastructure, then packages like Turbine or Espresso (which uses Struts)are perfectly good ways to go.See also* < http://www.mail-archive.com/[email protected]/msg03206.html >* < http://www.mail-archive.com/[email protected]/msg00495.html >* < http://jakarta.apache.org/velocity/ymtd/ymtd.html >

    Why aren't the Struts tags maintained as part of the Jakarta Taglibs project ?

    Development of both products began about the same time. Leading up to the release

    of 1.0, it was thought better to continue to develop the taglibs alongside the controller.Now that 1.0 is out, the JavaServer Pages Standard Taglib is in active development.

  • 8/7/2019 Structs Interview Questions and Answers

    7/39

    Once work on JSTL stabilizes, the Struts taglibs will be revisited. Tags which are notlinked directly to the framework may be hosted at Jakarta Taglibs instead.

    Are the Struts tags XHTML compliant ?

    If you use an

  • 8/7/2019 Structs Interview Questions and Answers

    8/39

    container supported it).Meanwhile, as Struts 1.1 was being developed, work progressed on things likeTomcat's reload command via the Manager webapp. This feature allows you toquickly reload-on-demand, complete with saving and restoring your session). Itstarted to make even less sense for Struts to half-implement a feature that containers

    are implementing fully.A more minor point is that freezing the configuration information at applicationstartup time allows Struts to safely access the mapping information without botheringwith synchronization. The "startup-only" strategy creates a modest but realimprovement in performance for all users.So, ReloadAction is not supported since Struts 1.1 for two reasons:* It never did let you reload everything that you would really want to -- particularlychanged classes -- so many people ended up having to reload the webapp anyway.* Containers are starting to offer reload-on-demand features which does the samething as the Struts ReloadAction, only better.* Not supporting ReloadAction lets Struts avoid doing synchronization locks around

    all the lookups (like figuring out which action to use, or the destination of anActionForward) so applications can run a little faster.Of course, if someone came up with an implementation that solved these problemswithout creating any others, we would not be opposed to including a newReloadAction.

    What is a modular application? What does module-relative mean?

    Since Struts 1.1, the framework supports multiple application modules. Allapplications have at least one root, or default, module. Like the root directory in a filesystem, the default application has no name. (Or is named with an empty string,depending your viewpoint.) Developing an application with only a default module isno different from how applications were developed under Struts 1.0. Since Struts 1.1,you can add additional modules to your application, each of which can have their ownconfiguration files, messages resources, and so forth. Each module is developed in thesame way as the default module. Applications that were developed as a single modulecan added to a multiple module application, and modules can promoted to astandalone application without change. For more about configuring your applicationto support multiple modules, see Configuring Applications in the User Guide.But to answer the question =:0), a modular application is a Struts application that usesmore than one module. Module-relative means that the URI starts at the module level,rather than at the context level, or the absolute-URL level.

    * Absolute URL: http://localhost/myApplication/myModule/myAction.do* context-relative: /myModule/myAction.do* module-relative: /myAction.doThe Struts Examples application is a modular application that was assembled fromseveral applications that were created independently.

    Why are some of the class and element names counter-intuitive?

    The framework grew in the telling and, as it evolved, some of the names drifted.The good thing about a nightly build, is that everything becomes available to thecommunity as soon as it is written. The bad thing about a nightly build is that thingslike class names get locked down early and then become difficult to change.

  • 8/7/2019 Structs Interview Questions and Answers

    9/39

    Why is ActionForm a base class rather than an interface?

    The MVC design pattern is very simple to understand but much more difficult to livewith. You just need this little bit of Business Logic in the View logic or you need justthat little bit of View logic in the Business tier and pretty soon you have a real mess.Making ActionForm a class takes advantage of the single inheritance restriction of

    Java to it makes it more difficult for people to do things that they should not do.ActionForms implemented as interfaces encourage making the property types matchthe underlying business tier instead of Strings, which violates one of the primarypurposes for ActionForms in the first place (the ability to reproduce invalid input,which is a fundamental user expectation). ActionForms as an interface would alsoencourage using existing DAO objects as ActionForms by adding implementsActionForm to the class. This violates the MVC design pattern goal of separationof the view and business logic.Since the goal of struts is to enforce this separation, it just makes more sense forStruts to own the ActionForm.DynaActionForms relieve developers of maintaining simple ActionForms. For near

    zero maintenance, try Niall Pemberton's LazyActionForm

    Do ActionForms have to be true JavaBeans?

    The utilities that Struts uses (Commons-BeanUtils since 1.1) require that ActionFormproperties follow the JavaBean patterns for mutators and accessors (get*,set*,is*).Since Struts uses the Introspection API with the ActionForms, some containers mayrequire that all the JavaBean patterns be followed, including declaring "implementsSerializable" for each subclass. The safest thing is to review the JavaBeanspecification and follow all the prescribed patterns.Since Struts 1.1, you can also use DynaActionForms and mapped-backed forms,which are not true JavaBeans. For more see ActionForm classes in the User Guideand Using Hashmaps with ActionForms in this FAQ.

    Can I use multiple HTML form elements with the same name?

    Yes. Define the element as an array and Struts will autopopulate it like any other.private String[] id= {};public String[] getId() { return this.id; }public void setItem(String id[]) {this.id = id;}And so forth

    Can I use multiple HTML form elements with the same name?

    Yes. The issue is that only one action class can be associated with a single form. Sothe real issue is how do I decode multiple submit types to a single Action class. Thereis more than one way to achieve this functionality.The way that is suggested by struts is right out of the javadoc forLookupDispatchAction . Basically, LookupDispatchAction is using the keys fromApplicationProperties.resources as keys to a map of actions available to your Actionclass. It uses reflection to decode the request and invoke the proper action. It alsotakes advantage of the struts tags and is straight forward to implement.

    You can roll your own with JavaScript events and javascript:void(document.forms["myform"].submit) on any html element. This gives you control of

    how you want your page to look. Again you will have to decode the expected actionin the execute method of your action form if you choose this route.

  • 8/7/2019 Structs Interview Questions and Answers

    10/39

    Why doesn't the focus feature on the tag work in every

    circumstance?

    Unfortunately, there is some disagreement between the various browsers, anddifferent versions of the same browser, as to how the focus can be set. The tag provides a quick and easy JavaScript that will set the focus on a form

    for most versions of most browsers. If this feature doesn't work for you, then youshould set the focus using your own JavaScript. The focus feature is a convenient"value-add" -- not a core requirement of the tag. If you do come up with a JavaScriptthat provides the final solution to this project, please post your patch to this Bugzillaticket.

    Why are my checkboxes not being set from ON to OFF?

    A problem with a checkbox is that the browser will only include it in the request whenit is checked. If it is not checked, the HTML specification suggests that it not be sent(i.e. omitted from the request). If the value of the checkbox is being persisted, eitherin a session bean or in the model, a checked box can never unchecked by a HTML

    form -- because the form can never send a signal to uncheck the box. The applicationmust somehow ascertain that since the element was not sent that the correspondingvalue is unchecked.The recommended approach for Struts applications is to use the reset method in theActionForm to set all properties represented by checkboxes to null or false. Thechecked boxes submitted by the form will then set those properties to true. Theomitted properties will remain false. Another solution is to use radio buttons instead,which always submit a value.It is important to note that the HTML specification recommends this same behaviorwhenever a control is not "successful". Any blank element in a HTML form is notguaranteed to submitted. It is therefor very important to set the default values for anActionForm correctly, and to implement the reset method when the ActionFormmight kept in session scope.

    Can't I just create some of my JavaBeans in the JSP using a scriptlet?

    Struts is designed to encourage a Model 2/MVC architecture. But there is nothing thatprevents you from using Model 1 techniques in your JavaServer Pages, so the answerto the question is "Yes, you can".Though, using Model 1 techniques in a Struts application does go against the grain.The approach recommended by most Struts developers is to create and populatewhatever objects the view may need in the Action, and then forward these through the

    request. Some objects may also be created and stored in the session or context,depending on how they are used.Likewise, there is nothing to prevent you from using scriptlets along with JSP tags inyour pages. Though, many Struts developers report writing very complex scriplet-freeapplications and recommend the JSP tag approach to others.For help with Model 1 techniques and scriptlets, you might consider joining theJavasoft JSP-interest mailing list, where there are more people still using theseapproaches.

    Can I use JavaScript to submit a form?

    You can submit a form with a link as below. BTW, the examples below assume you

    are in an block and 'myForm' is picked up from the struts-config.xml name field of theaction.

  • 8/7/2019 Structs Interview Questions and Answers

    11/39

  • 8/7/2019 Structs Interview Questions and Answers

    12/39

    checked, there is no way to turn it back off without the reset method. Resetting theproperties for other controls, or for a request scope form, is pointless. If the form is inrequest scope, everything already just started at the initial value.

    Can I use other beans or hashmaps with ActionForms?

    Yes. There are several ways that you can use other beans or hashmaps withActionForms.* ActionForms can have other beansor hashmaps as properties* "Value Beans" or "Data Transfer Objects" (DTOs) can be used independently ofActionForms to transfer data to the view* ActionForms can use Maps to support "dynamic" properties (since Struts 1.1)ActionForms (a.k.a. "form beans") are really just Java beans (with a few specialmethods) that Struts creates and puts into session or request scope for you. There isnothing preventing you from using other beans, or including them in your form beans.Here are some examples:Collections as properties Suppose that you need to display a pulldown list of available

    colors on an input form in your application. You can include a string-valuedcolorSelected property in your ActionForm to represent the user's selection and acolorOptions property implemented as a Collection (of strings) to store the availablecolor choices. Assuming that you have defined the getters and setters for thecolorSelected and colorOptions properties in your orderEntryForm form bean, youcan render the pulldown list using:The list will be populated using the strings in the colorOptions collection of theorderEntryForm and the value that the user selects will go into the colorSelectedproperty that gets posted to the subsequent Action. Note that we are assuming herethat the colorOptions property of the orderEntryForm has already been set.See How can I prepopulate a form? for instructions on how to set form beanproperties before rendering edit forms that expect properties to be pre-set.Independent DTO An Action that retrieves a list of open orders (as an ArrayList ofOrder objects) can use a DTO independently of any form bean to transfer searchresults to the view. First, the Action's execute method performs the search and putsthe DTO into the request:ArrayList results = businessObject.executeSearch(searchParameters);request.setAttribute("searchResults",results);

    Then the view can iterate through the results using the "searchResults" request key toreference the DTO:` ..other properties...

    How can I scroll through list of pages like the search results in google?

    Many Struts developers use the Pager from the JSPTags site.http://jsptags.com/tags/navigation/pager/

    Why do the Struts tags provide for so little formatting?The Struts tags seem to provide only the most rudimentary functionality. Why is there

  • 8/7/2019 Structs Interview Questions and Answers

    13/39

    not better support for date formatting and advanced string handling?Three reasons:First, work started on the JSTL and we didn't want to duplicate the effort.Second, work started on Java Server Faces, and we didn't want to duplicate that efforteither.

    Third, in a Model 2 application, most of the formatting can be handled in theActionForms (or in the business tier), so all the tag has to do is spit out a string. Thisleads to better reuse since the same "how to format" code does not need to be repeatedin every instance. You can "say it once" in a JavaBean and be done with it. Why don'tthe Struts taglibs offer more layout options?Since the Struts tags are open source, you can extend them to provide whateveradditional formatting you may need. If you are interested in a pre-written taglib thatoffers more layout options, see the struts-layout taglib.In the same arena, there is a well regarded contributor taglib that can help you createMenus for your Struts applications.

    Why does the tag URL-encode javascript and mailto links?The tag is not intended for use with client-side references like those usedto launch Javascripts or email clients. The purpose of link tag is to interject thecontext (or module) path into the URI so that your server-side links are not dependenton your context (or module) name. It also encodes the link, as needed, to maintain theclient's session on the server. Neither feature applies to client-side links, so there is noreason to use the tag. Simply markup the client-side links using thestandard tag.

    Why does the option tag render selected=selected instead of just selected?

    Attribute minimization (that is, specifying an attribute with no value) is a place whereHTML violates standard XML syntax rules. This matters a lot for people writing tobrowsers that support XHTML, where doing so makes the page invalid. It's muchbetter for Struts to use the expanded syntax, which works the same on existingbrowsers interpreting HTML, and newer browsers that expect XHTML-compliantsyntax. Struts is following the behavior recommended by the XHTML specification

    Do I have to use JSPs with my application?

    The short answer to this question is: No, you are not limited to JavaServer Pages.The longer answer is that you can use any type of presentation technology which canbe returned by a web server or Java container. The list includes but is not limited to:

    * JavaServer Pages,* HTML pages,* WML files,* Java servlets,* Velocity templates, and* XML/XLSTSome people even mix and match apparently unrelated technologies, like PHP, intothe same web application.

    Do ActionForms have to be true JavaBeans?

    ActionForms are added to a servlet scope (session or request) as beans. What this

    means is that, for certain functionality to be available, your ActionForms will have tofollow a few simple rules.

  • 8/7/2019 Structs Interview Questions and Answers

    14/39

    First, your ActionForm bean must have a zero-arguments constructor. This is requiredbecause Struts must be able to dynamically create new instances of your form beanclass, while knowing only the class name. This is not an onerous restriction, however,because Struts will also populate your form bean's properties (from the requestparameters) for you.

    Second, the fields of your form bean are made available to the framework bysupplying public getter and setter methods that follow the naming design patternsdescribed in the JavaBeans Specification. For most users, that means using thefollowing idiom for each of your form bean's properties:private {type} fieldName;public {type} getFieldName() {return (this.fieldName);}

    public void setFieldName({type} fieldName) {this.fieldName = fieldName;

    }NOTE - you MUST obey the capitalization conventions shown above for yourActionForm properties to be recognized. The property name in this example is"fieldName", and that must also be the name of the input field that corresponds to thisproperty. A bean property may have a "getter" method and a "setter" method (in aform bean, it is typical to have both) whose name starts with "get" or "set", followedby the property name with the first character capitalized. (For boolean properties, it isalso legal to use "is" instead of "get" as the prefix for the getter method.)Advanced JavaBeans users will know that you can tell the system you want to usedifferent names for the getter and setter methods, by using a java.beans.BeanInfoclass associated with your form bean. Normally, however, it is much more convenientto follow the standard conventions.WARNING - developers might be tempted to use one of the following techniques, butany of them will cause your property not to be recognized by the JavaBeansintrospection facilities, and therefore cause your applications to misbehave:* Using getter and setter method names that do not match - if you have a getFoo()method for your getter, but a setBar() method for your setter, Java will not recognizethese methods as referring to the same property. Instead, the language will think youhave a read-only property named "foo" and a write-only property named "bar".* Using more than one setter method with the same name - The Java language letsyou "overload" methods, as long as the argument types are different. For example,

    you could have a setStartDate(java.util.Date date) method and a setStartDate(Stringdate) method in the same class, and the compiled code would know which method tocall based on the parameter type being passed. However, doing this for form beanproperties will prevent Java from recognizing that you have a "startDate" property atall.There are other rules to follow if you want other features of your form beans to beexposed. These include indexed attributes and mapped attributes. They are covered indetail in other areas of the Struts documentation, in particular: indexedprops.html

    Do I have to have a separate ActionForm bean for every HTML form?

    This is an interesting question. As a newbie, it is a good practice to create a new

    ActionForm for each action sequence. You can use DynaActionForms to help reducethe effort required, or use the code generation facilities of your IDE.

  • 8/7/2019 Structs Interview Questions and Answers

    15/39

  • 8/7/2019 Structs Interview Questions and Answers

    16/39

    name="registrationForm"input="registration"scope="request"/>...

    Note the following features of this approach:* Both the /editRegistration and /saveRegistration actions use the same form bean.* When the /editRegistration action is entered, Struts will have pre-created an emptyform bean instance, and passed it to the execute() method. The setup action is free topreconfigure the values that will be displayed when the form is rendered, simply bysetting the corresponding form bean properties.* When the setup action completes configuring the properties of the form bean, itshould return an ActionForm that points at the page which will display this form. Ifyou are using the Struts JSP tag library, the action attribute on your tag

    will be set to /saveRegistration in order for the form to be submitted to the processingaction.* Note that the setup action (/editRegistration) turns off validation on the form that isbeing set up. You will normally want to include this attribute in the configuration ofyour setup actions, because you are not planning to actually process the results -- yousimply want to take advantage of the fact that Struts will precreate a form beaninstance of the correct class for you.* The processing action (/saveRegistration), on the other hand, leaves out the validateattribute, which defaults to true. This tells Struts to perform the validations associatedwith this form bean before invoking the processing action at all. If any validationerrors have occurred, Struts will forward back to your input page (technically, itforwards back to an ActionForward named "registration" in this case, because theexample webapp uses the inputForward attribute in the element -- see thedocumentation describing struts-config.xml for more information) instead of callingyour processing action.

    Can I have an Action without a form?

    Yes. If your Action does not need any data and it doesnot need to make any data available to the view orcontroller component that it forwards to, it doesn't needa form. A good example of an Action with no ActionForm is

    the LogoffAction in the struts example application:

    This action needs no data other than the user's session, whichit can get from the Request, and it doesn't need to prepare anyview elements for display, so it does not need a form.

  • 8/7/2019 Structs Interview Questions and Answers

    17/39

    However, you cannot use the tag withoutan ActionForm. Even if you want to use the tag with a simple Action that does not require input,the tag will expect you to use some type of ActionForm,even if it is an empty subclass without any properties.

    Can you give me a simple example of using the requiredif Validator rule?

    First off, there's an even newer Validator rule calledvalidwhen, which is almost certainly what you want to use,since it is much easier and more powerful.It will be available in the first release after 1.1 ships.The example shown below could be coded with validwhen as:

    test((((sex == 'm') OR (sex == 'M'))AND (*this* == null)) OR (*this* != null))

    Let's assume you have a medical information formwith three fields,sex, pregnancyTest, and testResult. If sex is 'f' or 'F',pregnancyTest is required. If pregnancyTest is not blank,testResult is required. The entry in your validation.xmlfile would look like this:

    field[0]sexfieldTest[0]EQUALfieldValue[0]F

  • 8/7/2019 Structs Interview Questions and Answers

    18/39

    field[1]sexfieldTest[1]

    EQUALfieldValue[1]ffieldJoinOR

    field[0]pregnancyTestfieldTest[0]NOTNULL

    When is the best time to validate input?This is an excellent question. Let's step back a second and think about a typical mid tolarge size application. If we start from the back end and work toward the view wehave:1) Database: Most modern databases are going to validate for required fields,duplicate records, security constraints, etc.

    2) Business Logic: Here you are going to check for valid data relationships and thingsthat make sense for the particular problem you are triing to solve.... This is where struts comes into the picture, by now the system should be pretty wellbulletproof. What we are going to do is make validation friendlier and informative.Rember it is OK to have duplicate validations...3) ActionErrors validate(ActionMapping map, HttpServletRequest req) is where youcan do your validation and feed back to the view, information required to correct anyerrors. validate is run after the form has been reset and after the ActionFormproperties have been set from corresponding view based input. Also remember youcan turn validation off with validate="false" in the action mapping in the struts-config.xml. This is done by returning an ActionErrors collection with messages from

    your ApplicationResources.properties file.Here you have access to the request so you can see what kinds of action is being

  • 8/7/2019 Structs Interview Questions and Answers

    19/39

    requested to fine tune your validations. The tag allows you to dump allerrors on your page or a particular error associated with a particular property. Theinput attribute of the struts-config.xml action allows you to send validation errors to aparticular jsp / html / tile page.4) You can have the system perform low level validations and client side feedback

    using a ValidatorForm or its derivatives. This will generate javascript and give instantfeedback to the user for simple data entry errors. You code your validations in thevalidator-rules.xml file. A working knowledge of regular expressions is necessary touse this feature effectively.

    How can I avoid validating a form before data is entered?

    The simplest way is to have two actions. The first one has the job of setting the formdata, i.e. a blank registration screen. The second action in our writes the registrationdata to the database. Struts would take care of invoking the validation and returningthe user to the correct screen if validation was not complete.The EditRegistration action in the struts example application illustrates this:

    < action path="/editRegistration">type="org.apache.struts.webapp.example.EditRegistrationAction"attribute="registrationForm"scope="request"validate="false">

  • 8/7/2019 Structs Interview Questions and Answers

    20/39

    The pieces of the wizard are as follows:forms.MyWizard.java - the form bean holding the information requiredactions.MyWizard.java - the actions of the wizard, note the use ofLookupDispatchAction allows for one action class with several methods. All the realwork will be done in the 'finish' method.mywizard[x].jsp - the data collection jsp'smywizarddone.jsp - the 'success' pagemywizardcancel.jsp - the 'cancel' page

    What's the best way to deal with migrating a large application from Struts to

    JSF? Is there any tool support that can help?Answer: This is a complicated task depending on your Struts application. Because the

  • 8/7/2019 Structs Interview Questions and Answers

    21/39

    two frameworks have different goals, there are some challenges. Migrate yourresponse pages first. Keep the Struts controller and place and forward to JSF pages.Then you can configure Struts forwards to go through the Faces servlet. Considerlooking at the Struts-Faces framework from Apache. See the framework chapter inJSF in Action.

    How can I 'chain' Actions?

    Chaining actions can be done by simply using theproper mapping in your forward entries in the struts-config.xml file.Assume you had the following two classes:

    /* com/AAction.java */...

    public class AAction extends Action

    {public ActionForwardexecute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throwsException{// Do something

    return mapping.findForward("success");}}

    /* com/BAction.java */...

    public class BAction extends Action{

    public ActionForwardexecute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throwsException{// Do something else

    return mapping.findForward("success");}

    }

  • 8/7/2019 Structs Interview Questions and Answers

    22/39

    Then you can chain together these two actions withthe Struts configuration as shown in the following excerpt:

    ...

    ...

    Here we are assuming you are using a suffix-based (.do) servlet mapping, which isrecommended since module support requires it. When you send your browser to theweb application and name the action A.do (i.e. http://localhost:8080/app/A.do) it willexecute AAction.execute(), which will then forward to the "success" mapping.This causes the execution of BAction.execute() since the entry for "success" in theconfiguration file uses the .do suffix.Of course it is also possible to chain actions programmatically, but the power and easeof being able to "reroute" your web application's structure using the XMLconfiguration file is much easier to maintain.As a rule, chaining Actions is not recommended. If your business classes are properlyfactored, you should be able to call whatever methods you need from any Action,without splicing them together into a cybernetic Rube Goldberg device.If you must chain Actions, be aware of the following: calling the second Action fromthe first Action has the same effect as calling the second Action from scratch. If bothof your Actions change the properties of a formbean, the changes made by the first

    Action will be lost because Struts calls the reset() method on the formbean when thesecond Action is called.

    Declarative Exception Handling

    If you have developed web applications long enough, you will realize a recurringpattern emerges: when the backend (e.g. the EJB tier) throws you an exception, younearly always need to display an error page corresponding to the type of thatexception. Sooner or later, you will come up with a mechanism to use a lookup table(e.g. an HashMap) to lookup an error page from the exception class.Struts 1.1 now provides a similar but more powerful mechanism to declare exceptionhandling. In Struts 1.1, you can declare in the struts-config.xml the associations

    between an exception class and an exception handler. Using the default exceptionhandler included in Struts, you can also specify the path of the error pages. With this

  • 8/7/2019 Structs Interview Questions and Answers

    23/39

    information, Struts will automatically forward to the specified pages when anuncaught exception is thrown from an Action.Like other facilities in Struts, the exception handlers are pluggable. You can write anddefine your own handler classes if needed.

    Struts GenericDataSource Just a general question - I'm building an applicationthat will run stand-alone, not in an application server. I need to manage some

    database connections. Is the struts GenericDataSource a good candidate to do

    this for me? I basicly just need a connection pool from where I can get

    connections and then return them to optimize performance.

    If this struts class is not a good candidate, can someone recommend a similar

    pool-manager that is lean and mean and easy to use?

    Answer 1The Struts 1.0 GenericDataSource is not a good candidate for a production server. InStruts 1.1, the Commons DBCP is used istead, which is a good candidate for aproduction server. (You can also use the DBCP in Struts 1.0 by specifying the type

    and including the Commons JARs.)Another popular choice is Poolman. It's not under active development, but I believeyou can still download it from SourceForge. Poolman is also very easy to use outsideof Struts.Many containers also offer support for connection pools. The one that ships withResin is quite good. The later versions of Tomcat bundle the Commons DBCP.Regardless of what pool you use, a good practice is to hide it behind some type ofadaptor class of your own (often a singleton), to make it easy to change later. So yourclasses call your adaptor, and your adaptor calls whichever pool you are using.A neat and often-overlooked aspect of the Struts DataSource manager is that itsupports loading multiple connection pools and giving each a name. So you mighthave one pool for internal use and another for public use. This way, the publicconnections can't swap your administrative access to the application. Each pool couldalso have its own login, and therefore different rights to the underlying database.Answer 2

    int i=1;

    with Struts 1.0 and jdbc i'am use GenericDataSourcenot in struts-xml, but in Client.properties

    my Client.propertiesinstanceBd=oraIDuserPasswd=xxx/yyyymaxCount=20minCount=19port=1521driver=oracle.jdbc.driver.OracleDriverurl=jdbc:oracle:thin:@serverName:port:instanceBd

    then, on my code i have init (struts 1.0 or struts 1.1):

    GenericDataSource ng = new GenericDataSource ();

  • 8/7/2019 Structs Interview Questions and Answers

    24/39

    ng.setUser (mprop.getUserBd());ng.setPassword (mprop.getPasswdBd());ng.setUrl (mprop.getUrl());ng.setDriverClass(mprop.getDriverClass());

    ng.setMaxCount(mprop.getMaxCount());ng.setMinCount (mprop.getMinCount());ng.setDescription("jdbc OracleDriver");ng.setAutoCommit(true);try { ng.open(); } catch (java.sql.SQLException e) {}

    in business logic (or pool) :Connect cn = ng.getConnection();

    it's work.

    with struts 1.1 , struts-legacy.jar is necessy for this codes.

    it's work.

    Dynamic pages using struts

    Is it possible to create the elements of a page(jsp) dynamically based on the

    results of a data base query, when using struts framework?

    If you are talking about rendering a report, then sure. The Action iteracts with thebusiness layer/data access objects to acquire the data, and then passes it to thepresentation page bundled up as a JavaBean or a collection of JavaBeans. The JSPtags (and other systems) all use reflection, so you can use whatever JavaBean youlike.If you are talking about creating a dynamic data-entry form, then "not so much".Struts 1.1 supports map-backed ActionForms, but the page still needs to know whatinput fields are going to be needed. For a truly dynamic input form, I guess the keywould be some type of tag that took a map and then generated a column of inputfields. (Wouldn't work for everyone, since a lot of forms must be designed just so.)For extra credit, the entry names could (optionally) be resource keys that were used tofind the label text.

    Text fields would be easy. Others would need some type of JavaBean with propertiesto tell the tag what to output. A bit of work, but obviously doable.Of course, you'd probably want to validate the form before passing it back to thedatabase. I imagine it's possible to use the validator in a non-declarative way, but Idon't know anyone whose doing that. If you can do a db query to get the informationabout the form, I imagine you could also do a query to get the information aboutvalidations for the form. It would probably be easier to write your own engine thanadopt the validator. (It's not really that complicated to do.)People often ask about "dynamic input forms", but most of us just can't get our headaround the use case. It's hard to understand what you do with the dynamic data whenit comes back. Most application don't allow you to input or update an arbitrary (e.g.

    dynamic) set of fields.

  • 8/7/2019 Structs Interview Questions and Answers

    25/39

    Both JSF and Struts will continue to exist for a while. The Struts community is

    aware of JSF and is positioning itself to have strong support for JSF. See What

    about JSTL and JavaServer faces?

    From a tools perspective, if you look at the support for JSF versus Struts inWebSphere Studio, the Struts tools are focused around the controller aspects. The

    Web Diagram editor helps build your Struts configuration and the wizards/editorsbuild Struts artifacts. The JSF tools are geared towards building pages, and in essence,hide the JSF framework from you. Expect WebSphere Studio to support bothframeworks for a while. As JSF matures, expect to see some of the controller aspectsin JSF to become toolable.

    Can you compare the advantages and disadvantages of JSF vs. Struts. Both now,

    and from what you may know of futures, how and if JSF will evolve into a

    superior technology vs. Struts? Include how WSAD plays into the comparison if

    it will help differentiate the two.

    This is a very popular question these days. In general, JSF is still fairly new and will

    take time to fully mature. However, I see JSF being able to accomplish everythingStruts can, plus more. Struts evolved out of necessity. It was created by developerswho were tired of coding the same logic again and again. JSF emerged both fromnecessity and competition.Struts has several benefits:* Struts is a mature and proven framework. It has been around for a few years anddeployed successfully on many projects. The WebSphere Application Server adminconsole is a Struts application.* Struts uses the Front Controller and Command patterns and can handle sophisticatedcontroller logic.* In addition to the core controller function, it has many add-on benefits such aslayouts with Tiles, declarative exception handling, and internationalization.

    There are disadvantages:

    * Struts is very JSP-centric and takes other frameworks to adapt to other viewtechnologies.* Although Struts has a rich tag library, it is still geared towards helping the controlleraspect of development and does not give a sense that you are dealing withcomponents on a page. Therefore, it is not as toolable from a view perspective.* Struts requires knowledge of Java. Its goal was to aid Java developers, but not to

    hide Java. It does not hide details of the Java language to Web developers that well.* ActionForms are linked programmatically to the Struts framework. Therefore, todecouple the model, you need to write transfer code or use utilities to move data fromAction Forms to the Model on input.

    JSF is an evolution of a few frameworks, including Struts. The creator of Struts, CraigMcClanahan, is one of the JSF specification leads. Therefore, it is not by accident tosee some overlap between Struts and JSF. However, one of JSF's major goals is tohelp J2EE Web applications to be easily developed using RAD tools. As such, itintroduces a rich component model. JSF has several advantages:* JSF is a specification from Sun and will be included in future versions of the J2EE

    specification. All major vendors are pledging strong support for JSF.* JSF uses the Page Controller Pattern and therefore aids in Page rich applications.

  • 8/7/2019 Structs Interview Questions and Answers

    26/39

    Components can respond to event from components on a page.* JSF has a well-defined request lifecycle allowing for plugability at different levels.* One powerful example of plugability is building your own render toolkit. Theability to separate the rendering portion from the controller portion of the frameworkallows for wonderful opportunities of extensibility. Component providers can write

    their own toolkits to render different markup languages, such as XML or WML. Inaddition, the render toolkit is not tied to JSP.* Because JSF has a rich component model, it favors a RAD style of development. Ican now build my Web pages using drag and drop technology. In addition, JSF givesme a way to link visual components to back model components without breaking thelayering.JSF has disadvantages:* JSF is still quite new and evolving. It will take some time to see successfuldeployments and wide usage. In addition, as vendors write components, they may notdo everything you want them to.* JSF by hand is not easier than Struts. Its goal was more oriented to RAD. Those

    who prefer to do things by hand (for example, the vi type guy who does not likeIDEs) may find Struts easier to develop.* Struts navigation may be a bit more flexible and adhere to more complex controllerlogic.

    Multiple Sub-applications

    One of the shortcomings in Struts 1.0 is manageability of the configuration file(commonly known as struts-config.xml) when the development of the applicationinvolves a sizable team. This problem arises because a Struts-based application mustrun under one controller servlet, the ActionServlet, and the ActionServlet can use onlyone struts-config.xml. It is not an issue when the project is relatively small and theteam consists of a couple of developers; however, when the project size becomessignificant and the project involves a large number of developers, maintaining all themapping information in a single file becomes increasingly problematic.Struts 1.1 solves this problem nicely by introducing multiple sub-applications. InStruts 1.1, each sub-application has its own struts-config.xml file. A large Struts-based application can thus be easily partitioned into largely independent modules, i.e.sub-applications, and each sub-team can maintain their struts-config.xmlindependently.The sub-application scheme is a natural extension of the servlet context mappingscheme of the URI paths used by servlet containers. According to the Servlet

    standard, when the servlet container receives a request with a URL, the servletcontainer will try to match the prefix of the URI path to a deployed web-application inthe container. What Struts 1.1 does is it maps the second prefix of the path to a sub-application. In effect, this prefix mapping scheme creates another level of namespacefor each sub-application. For example, for the URI,http://some-host.com/myApp/module2/editSubscription.do/myApp is the context path for a web-application called "myApp" and /module2 is thesub-app prefix for a Struts sub-application called "module2".

    DynaBean and BeanUtils

    Another major complaint usually heard amongst Struts 1.0 users is the extensive

    effort involved in writing the FormBean (a.k.a. ActionForm) classes.Struts provides two-way automatic population between HTML forms and Java

  • 8/7/2019 Structs Interview Questions and Answers

    27/39

    objects, the FormBeans. To take advantage of this however, you have to write oneFormBean per HTML form. (In some use cases, a FormBean can actually be sharedbetween multiple HTML forms. But those are specific cases.) Struts' FormBeanstandard follows faithfully the verbose JavaBean standard to define and accessproperties. Besides, to encourage a maintainable architecture, Struts enforces a pattern

    such that it is very difficult to 'reuse' a model-layer object (e.g. a ValueObject fromthe EJB tier) as a FormBean. Combining all these factors, a developer has to spend asignificant amount of time to write tedious getters/setters for all the FormBeanclasses.Struts 1.1 offers an alternative, Dynamic ActionForms, which are based onDynaBeans. Simply put, DynaBeans are type-safe name-value pairs (thinkHashMaps) but behave like normal JavaBeans with the help of the BeanUtils library.(Both the DynaBeans and the BeanUtils library were found to be useful and genericenough that they have been 'promoted' into Jakarta's Commons project.) WithDynamic ActionForms, instead of coding the tedious setters/getters, developers candeclare the required properties in the struts-config.xml files. Struts will instantiate and

    initialize Dynamic ActionForm objects with the appropriate metadata. From thenonwards, The Dynamic ActionForm instance is treated as if it is an ordinary JavaBeanby Struts and the BeanUtils library.

    Validator

    The Validator is not exactly a new feature. The Validator has been in the contribpackage in the distribution since Struts 1.0.1. Since then, part of it has now beenrefactored and moved into the Jakarta-Commons subproject and renamed theCommons-Validator and the Struts specific portion is now called the Struts-Validator.However, since it is in the contrib package, people may overlook it and it isworthwhile to mention it here.The Validator provides an extensible framework to define validation rules to validateuser inputs in forms. What is appealing in the Validator is that it generates both theserver-side validation code and the client-side validation code (i.e. Javascript) fromthe same set of validation rules defined in an XML configuration file. The Validatorperforms the validation based on regular-expression pattern matching. While ahandful of commonly used validators are shipped with the framework (e.g. datevalidator, range validator), you can always define your own ones to suit your need.

    Default Sub-application

    To maintain backward compatibility, Struts 1.1 allows one default sub-application perapplication. The URI of the resources (i.e. JSPs, HTMLs, etc) in the default sub-application will have an empty sub-app prefix. This means when an existing 1.0application is "dropped" into Struts 1.1, theoretically, it will automatically become thedefault sub-application.

    Direct Requests to JSPs

    To take the full advantage of sub-application support, Struts 1.1 stipulates therequirement that all requests must flow through the controller servlet, i.e. theActionServlet. Effectively, this means all JSPs must be fronted by Actions. Instead of

    allowing direct requests to any of the JSPs, all requests must go through an Actionand let the Action forward to the appropriate JSP.

  • 8/7/2019 Structs Interview Questions and Answers

    28/39

    This is perhaps the biggest impact of migration to Struts 1.1 if you have not followedthis idiom in your applications. This restriction is required because without goingthrough the ActionServlet, Struts navigation taglibs (e.g. and) used in the JSPs will not have the correct sub-app context to work with.

    ActionServlet ConfigurationsWith the introduction of sub-applications, a more flexible way is introduced toconfigure each sub-application independently. Many of the configuration entries (e.g.resource bundle location, maximum upload file size, etc) that used to be defined inweb.xml have now been moved to struts-config.xml. The original entries in web.xmlare deprecated but will still be effective.

    Action.execute() and Action.getResources()

    In Struts 1.0, request handling logic is coded in Action.perform(); however,Action.perform() throws only IOException and SevletException. To facilitate the new

    declarative exception handling , the request handling method needs to throwException, the superclass of all the checked exceptions. Therefore, to both maintainbackward compatibility and facilitate declarative exception handling,Action.perform() is now deprecated in favour of Action.execute().You also have to be careful if you use DispatchAction in your existing applications.At the time of writing, the DispatchAction in Struts 1.1 beta has not yet been updatedto use execute(). (A bug report has been filed in Struts' bug database.) Therefore,without modifying the DispatchAction class yourself, declarative exception handlingwill not work with DispatchAction subclasses.In addition, Action.getResources() is now deprecated. Instead, you should callAction.getResources(HttpServletRequest) instead. This allows Struts to return to youthe sub-application specific message resources. Otherwise, the message resources forthe default sub-app will be used.

    Library Dependency

    Struts 1.1 now depends on a handful of libraries from other Jakarta subprojects (e.g.Commons-Logging, Commons-Collections, etc.). Some of these libraries may causeclassloading conflicts in some servlet containers. So far, people have reported in themailing list the classloading problem of commons-digester/jaxp1.1, and commons-logging causing deployment difficulties in Struts 1.1 applications running on

    Weblogic 6.0. (The problems have been corrected in Weblogic 6.1 and 7.0.)

    Resources under WEB-INF

    According to the Servlet specification, resources (e.g. JSP files) stored under WEB-INF are protected and cannot be accessed directly by the browsers. One design idiomfor Struts 1.0 is to put all the JSP files under WEB-INF and front them by Actions sothat clients cannot illegally access the JSPs. With the introduction of sub-applicationprefixes in Struts 1.1, mapping resources under WEB-INF gets complicated. Extraconfiguration steps utilizing the pagePattern and forwardPattern attributes of theelement in struts-config.xml is required to inform Struts to construct the paths

    correctly. More specifically, you need to set these attributes to the pattern "/WEB-INF/$A$P".

  • 8/7/2019 Structs Interview Questions and Answers

    29/39

    What is the Jakarta Struts Framework?

    Jakarta Struts is an open source implementation of MVC(Model-View-Controller) pattern for the development of web based applications.Jakarta Struts is a robust architecture and can be used for the development ofapplications of any size.

    The Struts framework makes it easier to design scalable, reliable Web applications.

    What is an ActionServlet?

    The class org.apache.struts.action.ActionServlet is called the ActionServlet.In the Jakarta Struts Framework this class plays the role of controller.All the requests to the server go through the Controller.The Controller is responsible for handling all the requests.

    How can one make any Message Resources definitions file available to the

    Struts Framework environment?

    Answer: Message Resources definitions file are simple .properties files and

    these files contain the messages that can be used in the struts project.Message Resources definition files can be added to the struts-config.xml filethrough tag. Example:

    What is an Action Class?

    The Action Class is part of the Model and is a wrapper around the business logic.

    The purpose of the Action Class is to translate the HttpServletRequest to thebusiness logic.

    To use the Action, we need to subclass and overwrite the execute() method.

    All the database and business processing is done in the Action class.

    It is advisable to perform all the database related work in the Action class.

    The ActionServlet (command) passes the parameterized class to ActionForm usingthe execute() method.

    The return type of the execute method is ActionForward which is used by the Struts

    Framework to forward the request to the file according to the value of the returnedActionForward object.

    Write code of any Action Class?

    Here is the code of Action Class that returns the ActionForward object.

    package j2eeonline.jdj.com;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;

    import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;

  • 8/7/2019 Structs Interview Questions and Answers

    30/39

    public class TestAction extends Action{

    public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception{

    return mapping.findForward("testAction");}}

    What is an ActionForm?

    An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.ActionForm maintains the session state for web application and the ActionFormobject is automatically populated on the server side with data entered from a form onthe client side.

    What is Struts Validator Framework?

    The Struts Framework provides the functionality to validate the form data.It can be used to validate the data in the users browser as well as on the server side.Struts Framework checks the JavaScript code and it can be used to validate the formdata on the client browser.

    Server side validation of form data can be accomplished by subclassing your formBean with DynaValidatorForm class.

    The Validator framework was developed by David Winterfeldt as a third-partyadd-on to Struts.Now the Validator framework is part of the Jakarta Commons project and it can beused with or without Struts.

    The Validator framework comes integrated with the Struts Framework andcan be used without any making any additional settings.

    Describe the details of XML files used in the Validator Framework?

    The Validator Framework uses two XML configuration files

    1) validator-rules.xml and

    2) validation.xml.

    The validator-rules.xml defines the standard validation routines.

    These are reusable and used in validation.xml to define the form specific validations.

    The validation.xml defines the validations applied to a form bean.

    How would you display validation fail errors on a JSP page?

    Following tag displays all the errors:

  • 8/7/2019 Structs Interview Questions and Answers

    31/39

    How can one enable front-end validation based on the xml in validation.xml?

    Thetag allows front-end validation based on the xml in validation.xml.

    For example the code:

    generates the client side JavaScript for the form "logonForm" as defined in thevalidation.xml file.The when added in the JSP file generates the client side validationscript.

    Servlet Interview Questions andAnswers

    What is Servlet?

    A servlet is a Java technology-based Web component, managed by a container calledservlet container or servlet engine, that generates dynamic content and interacts withweb clients via a request\/response paradigm.

    Why is Servlet so popular?

    Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.

    What is servlet container?The servlet container is a part of a Web server or application server that provides thenetwork services over which requests and responses are sent, decodes MIME-basedrequests, and formats MIME-based responses. A servlet container also contains andmanages servlets through their lifecycle.

    When a client request is sent to the servlet container, how does the container

    choose which servlet to invoke?The servlet container determines which servlet to invoke based on the configurationof its servlets, and calls it with objects representing the request and response.

    If a servlet is not properly initialized, what exception may be thrown?

    During initialization or service of a request, the servlet instance can throw anUnavailableException or a ServletException.

    Given the request path below, which are context path, servlet path and path

    info?

    /bookstore/education/index.html

    context path: /bookstore

  • 8/7/2019 Structs Interview Questions and Answers

    32/39

    servlet path: /educationpath info: /index.html

    What is filter? Can filter be used as request or response?

    A filter is a reusable piece of code that can transform the content of HTTP

    requests,responses, and header information. Filters do not generally create a responseor respond to a request as servlets do, rather they modify or adapt the requests for aresource, and modify or adapt responses from a resource.

    When using servlets to build the HTML, you build a DOCTYPE line, why do

    you do that?

    I know all major browsers ignore it even though the HTML 3.2 and 4.0 specificationsrequire it. But building a DOCTYPE line tells HTML validators which version ofHTML you are using so they know which specification to check your documentagainst. These validators are valuable debugging services, helping you catch HTML

    syntax errors.

    What is new in ServletRequest interface ? (Servlet 2.4)

    The following methods have been added to ServletRequest 2.4 version:public int getRemotePort()public java.lang.String getLocalName()public java.lang.String getLocalAddr()public int getLocalPort()

    Request parameter How to find whether a parameter exists in the request

    object?

    1.boolean hasFoo = !(request.getParameter("foo") == null ||request.getParameter("foo").equals(""));2. boolean hasParameter = request.getParameterMap().contains(theParameter);(which works in Servlet 2.3+)

    How can I send user authentication information while making URL Connection?

    You'll want to use HttpURLConnection.setRequestProperty and set all the appropriateheaders to HTTP authorization.

    Can we use the constructor, instead of init(), to initialize servlet?Yes , of course you can use the constructor instead of init(). There's nothing to stopyou. But you shouldn't. The original reason for init() was that ancient versions of Javacouldn't dynamically invoke constructors with arguments, so there was no way to givethe constructur a ServletConfig. That no longer applies, but servlet containers still willonly call your no-arg constructor. So you won't have access to a ServletConfig orServletContext.

    How can a servlet refresh automatically if some new data has entered the

    database?

    You can use a client-side Refresh or Server Push

  • 8/7/2019 Structs Interview Questions and Answers

    33/39

    The code in a finally clause will never fail to execute, right?

    Using System.exit(1); in try block will not allow finally code to execute.

    Servlet Interview Questions and

    Answers

    What mechanisms are used by a Servlet Container to maintain session

    information?

    Cookies, URL rewriting, and HTTPS protocol information are used to maintainsession information

    Difference between GET and POST

    In GET your entire form submission can be encapsulated in one URL, like ahyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.

    In POST Your name/value pairs inside the body of the HTTP request, which makesfor a cleaner URL and imposes no size limitations on the form's output. It is used tosend a chunk of data to the server to be processed, more versatile, most secure.

    What is session?

    The session is an object used by a servlet to track a user's interaction with a Webapplication across multiple HTTP requests.

    What is servlet mapping?

    The servlet mapping defines an association between a URL pattern and a servlet. Themapping is used to map requests to servlets.

    What is servlet context ?

    The servlet context is an object that contains a servlet's view of the Web applicationwithin which the servlet is running. Using the context, a servlet can log events, obtainURL references to resources, and set and store attributes that other servlets in thecontext can use. (answer supplied by Sun's tutorial).

    Which interface must be implemented by all servlets?

    Servlet interface.

    Explain the life cycle of Servlet.

    Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..),destroy(destroy()) and unloaded.

    When is the servlet instance created in the life cycle of servlet? What is the

    importance of configuring a servlet?

    An instance of servlet is created when the servlet is loaded for the first time in thecontainer. Init() method is used to configure this servlet instance. This method is

    called only once in the life time of a servlet, hence it makes sense to write all those

  • 8/7/2019 Structs Interview Questions and Answers

    34/39

    configuration details about a servlet which are required for the whole life of a servletin this method.

    Why don't we write a constructor in a servlet?

    Container writes a no argument constructor for our servlet.

    When we don't write any constructor for the servlet, how does container create

    an instance of servlet?

    Container creates instance of servlet by callingClass.forName(className).newInstance().

    Once the destroy() method is called by the container, will the servlet be

    immediately destroyed? What happens to the tasks(threads) that the servlet

    might be executing at that time?

    Yes, but Before calling the destroy() method, the servlet container waits for theremaining threads that are executing the servlets service() method to finish.

    What is the difference between callling a RequestDispatcher using

    ServletRequest and ServletContext?

    We can give relative URL when we use ServletRequest and not while usingServletContext.

    Why is it that we can't give relative URL's when using

    ServletContext.getRequestDispatcher() when we can use the same while calling

    ServletRequest.getRequestDispatcher()?

    Since ServletRequest has the current request path to evaluae the relative path whileServletContext does not.

    Hibernate Interview Questions

    By Ramakrishnaon Jul 12, 2008 in hibernate interview questions

    Q) What are the most common methods of Hibernate configuration?

    A) The most common methods of Hibernate configuration are:* Programmatic configuration* XML configuration (hibernate.cfg.xml)

    Q) What are the important tags of hibernate.cfg.xml?

    A) An Action Class is an adapter between the contents of an incoming HTTP rest andthe corresponding business logic that should be executed to process this rest.

    Q) What are the Core interfaces are of Hibernate framework?A) People who read this also read:

    http://www.bestjavainterviewquestions.com/hibernate-interview-questions-2/http://www.bestjavainterviewquestions.com/author/Ramakrishna/http://www.bestjavainterviewquestions.com/author/Ramakrishna/http://www.bestjavainterviewquestions.com/category/hibernate-interview-questions/http://www.bestjavainterviewquestions.com/hibernate-interview-questions-2/http://www.bestjavainterviewquestions.com/author/Ramakrishna/http://www.bestjavainterviewquestions.com/category/hibernate-interview-questions/
  • 8/7/2019 Structs Interview Questions and Answers

    35/39

    The five core interfaces are used in just about every Hibernate application. Usingthese interfaces, you can store and retrieve persistent objects and control transactions.* Session interface* SessionFactory interface* Configuration interface

    * Transaction interface* Query and Criteria interfaces

    Q) What role does the Session interface play in Hibernate?

    A) The Session interface is the primary interface used by Hibernate applications. It isa single-threaded, short-lived object representing a conversation between theapplication and the persistent store. It allows you to create query objects to retrievepersistent objects.

    Session session = sessionFactory.openSession();Session interface role:

    * Wraps a JDBC connection* Factory for Transaction* Holds a mandatory (first-level) cache of persistent objects, used when navigatingthe object graph or looking up objects by identifier

    Q) What role does the SessionFactory interface play in Hibernate?

    A) The application obtains Session instances from a SessionFactory. There istypically a single SessionFactory for the whole applicationcreated duringapplication initialization. The SessionFactory caches generate SQL statements andother mapping metadata that Hibernate uses at runtime. It also holds cached data thathas been read in one unit of work and may be reused in a future unit of work

    SessionFactory sessionFactory = configuration.buildSessionFactory();

    Q) What is the general flow of Hibernate communication with RDBMS?

    A) The general flow of Hibernate communication with RDBMS is :* Load the Hibernate configuration file and create configuration object. It willautomatically load all hbm mapping files* Create session factory from configuration object* Get one session from this session factory

    * Create HQL Query* Execute query to get list containing Java objects

    Q) What is Hibernate Query Language (HQL)?

    A) Hibernate offers a query language that embodies a very powerful and flexiblemechanism to query, store, update, and retrieve objects from a database. Thislanguage, the Hibernate query Language (HQL), is an object-oriented extension toSQL.

    Q) How do you map Java Objects with Database tables?

    A)

    * First we need to write Java domain objects (beans with setter and getter). Thevariables should be same as database columns.

  • 8/7/2019 Structs Interview Questions and Answers

    36/39

    * Write hbm.xml, where we map java class to table and database columns to Javaclass variables.

    Example :

    Q) What Does Hibernate Simplify?

    A) Hibernate simplifies:

    * Saving and retrieving your domain objects* Making database column and table name changes* Centralizing pre save and post retrieve logic* Complex joins for retrieving related items* Schema creation from object model

    Q) Whats the difference between load() and get()?

    A) load() vs. get()

    load() :-Only use the load() method if you are sure that the object exists.load() method will throw an exception if the unique id is not found in the database.

    load() just returns a proxy by default and database wont be hit until the proxy isfirst invoked.

    get():-If you are not sure that the object exists, then use one of the get() methods.get() method will return null if the unique id is not found in the database.get() will hit the database immediately.

    Q) What is the difference between and merge and update ?

    A)Use update() if you are sure that the session does not contain an already persistentinstance with the same identifier, and merge() if you want to merge yourmodifications at any time without consideration of the state of the session.

    Q) How do you define sequence generated primary key in hibernate?

    A) Using tag.Example:-SEQUENCE_NAME

  • 8/7/2019 Structs Interview Questions and Answers

    37/39

    Q) Define cascade and inverse option in one-many mapping?

    A) cascade enable operations to cascade to child entities.cascade=all|none|save-update|delete|all-delete-orphaninverse mark this collection as the inverse end of a bidirectional association.inverse=true|false

    Essentially inverse indicates which end of a relationship should be ignored, so whenpersisting a parent who has a collection of children, should you ask the parent for itslist of children, or ask the children who the parents are?

    Q) What does it mean to be inverse?

    A) It informs hibernate to ignore that end of the relationship. If the onetomany wasmarked as inverse, hibernate would create a child>parent relationship(child.getParent). If the onetomany was marked as noninverse then a child>parent relationship would be created.

    Q) What do you mean by Named SQL query?

    A) Named SQL queries are defined in the mapping xml document and calledwherever required.Example:SELECT emp.EMP_ID AS {emp.empid},emp.EMP_ADDRESS AS {emp.address},emp.EMP_NAME AS {emp.name}FROM Employee EMP WHERE emp.NAME LIKE :nameInvoke Named Query :List people = session.getNamedQuery(empdetails).setString(TomBrady, name).setMaxResults(50).list();

    Q) How do you invoke Stored Procedures?

    A)

    { ? = call selectAllEmployees() }

    Q) Explain Criteria API

    A) Criteria is a simplified API for retrieving entities by composing Criterion objects.This is a very convenient approach for functionality like search screens where thereis a variable number of conditions to be placed upon the result set.Example :List employees = session.createCriteria(Employee.class)

    .add(Restrictions.like(name, a%) )

    .add(Restrictions.like(address, Boston))

  • 8/7/2019 Structs Interview Questions and Answers

    38/39

    .addOrder(Order.asc(name) )

    .list();

    Q) Define HibernateTemplate?

    A) org.springframework.orm.hibernate.HibernateTemplate is a helper class which

    provides different methods for querying/retrieving data from the database. It alsoconverts checked HibernateExceptions into unchecked DataAccessExceptions.

    Q) What are the benefits does HibernateTemplate provide?

    A) The benefits of HibernateTemplate are :* HibernateTemplate, a Spring Template class simplifies interactions with HibernateSession.* Common functions are simplified to single method calls.* Sessions are automatically closed.* Exceptions are automatically caught and converted to runtime exceptions.

    Q) How do you switch between relational databases without code changes?A) Using Hibernate SQL Dialects , we can switch databases. Hibernate will generateappropriate hql queries based on the dialect defined.

    Q) If you want to see the Hibernate generated SQL statements on console, what

    should we do?

    A) In Hibernate configuration file set as follows:true

    Q) What are derived properties?

    A) The properties that are not mapped to a column, but calculated at runtime byevaluation of an expression are called derived properties. The expression can bedefined using the formula attribute of the element.People who read this also read:Core Java QuestionsSpring QuestionsSCJP 6.0 CertificationEJB Interview QuestionsServlets Questions

    Q) What is component mapping in Hibernate?

    A)* A component is an object saved as a value, not as a reference* A component can be saved directly without needing to declare interfaces oridentifier properties* Required to define an empty constructor* Shared references not supported

    Q) What is the difference between sorted and ordered collection in hibernate?

    A) sorted collection vs. order collectionsorted collection :-A sorted collection is sorting a collection by utilizing the sorting features provided by

    the Java collections framework. The sorting occurs in the memory of JVM which

  • 8/7/2019 Structs Interview Questions and Answers

    39/39

    running Hibernate, after the data being read from database using java comparator.If your collection is not large, it will be more efficient way to sort it.

    order collection :-Order collection is sorting a collection by specifying the order-by clause for sorting

    this collection when retrieval.If your collection is very large, it will be more efficient way to sort it .