Sun River
Topics about Java SE, Servlet/JSP, JDBC, MultiThread, UML, Design Pattern, CSS, JavaScript, Maven, JBoss, Tomcat, ...
posts - 78,comments - 0,trackbacks - 0

Question: How you will handle exceptions in Struts?
Answer: In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:

<exception 
      key="database.error.duplicate" 
      path="/UserExists.jsp" 
      type="mybank.account.DuplicateUserException"/>
b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.
Question:Explain Struts navigation flow?
Struts Navigation flow.
1) A request is made from previously displayed view.
2) The request reaches the ActionServlet which acts as the controller .The ActionServlet Looksup the requested URI in an XML file (Struts-Config.xml) and determines the name of the Action class that has to perform the requested business logic.
3)The Action Class performs its logic on the Model Components associated with the Application.
4) Once The Action has been completed its processing it returns the control to the Action Servlet.As part of its return the Action Class provides a key to determine where the results should be forwarded for presentation.
5)The request is complete when the Action Servlet responds by forwarding the request to the view, and this view represents the result of the action.
Question: What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file?
1. tiles-def.xml
  tiles-def.xml is used as a configuration file for an appliction during tiles development. You can define the layout / header / footer / body content for your View.
  Eg:
<tiles-definitions>
   <definition name="siteLayoutDef" path="/layout/thbiSiteLayout.jsp">
      <put name="title" value="Title of the page" />
      <put name="header" value="/include/thbiheader.jsp" />
      <put name="footer" value="/include/thbifooter.jsp" />
      <put name="content" type="string">
      Content goes here
   </put>
  </definition>
</tiles-definitions>

<tiles-definitions>
<definition name="userlogin" extends="siteLayoutDef">
<put name="content" value="/dir/login.jsp" />
</definition>
</tiles-definitions>

2. validation.xml
The validation.xml file is used to declare sets of validations that should be applied to Form Beans.
Each Form Bean you want to validate has its own definition in this file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields. Eg:

<form-validation>
<formset>
<form name="logonForm">
<field property="username"
depends="required">
<arg0 key=" prompt.username"/>
</field>
<field property="password"
depends="required">
<arg0 key="prompt.password"/>
</field>
</form>
</formset>
</form-validation>

3. Resourcebundle.properties

Instead of having hard-coded error messages in the framework, Struts Validator allows you to specify a key to a message in the ApplicationResources.properties (or resourcebundle.properties) file that should be returned if a validation fails. Eg:

In ApplicationResources.properties
errors.registrationForm.name={0} Is an invalid name.
In the registrationForm.jsp
<html:messages id="messages" property="name">
<font color="red">
<bean:write name="messages" />
</html:messages>

Output(in red color) : abc Is an invalid name

=================

1. Purpose of tiles-def.xml file is used to in the design face of the webpage. For example in the webpage "top or bottom or left is
fixed" center might be dynamically chaged.
It is used for the easy design of the web sites. Reusability

2. resourcebundle.properties file is used for lot of purpose. One of its purpose is internationalization. We can make our page to view on any language. It is independent of it. Just based on the browser setting it selects the language and it displayed as you mentioned in the resourcebundle.properties file.

3. Validation rule.xml is used to put all the validation of the front-end in the validationrule.xml. So it verifies. If the same rule is applied in more than one page. No need to write the code once again in each page. Use validation to chek the errors in forms.

============================

tiles-def.xml - is required if your application incorporates the tiles framework in the "View" part of MVC. Generally we used to have a traditional JSP's (Which contgains HTML & java scriplets) are used in view. But Tiles is an advanced (mode or less ) implementation of frames used in HTML. We used to define the frames in HTML to seperate the header html, footer html, menu or left tree and body.html to reuse the contents. Hence in the same way, Tiles are defined to reuse the jsp's in struts like architectures, and we can define the jsp's which all are to be display at runtime, by providing the jsp names at runtime. To incorporate this we need tile-def.xml and the Class generally which extends RequestProcessor should extend TilesRequestProcessor.

resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC.

validation.xml - This file is responsible for business validations carried at server side before processing the request actually. It reduces the complexity in writing _JavaScript validations, and in this way, we can hide the validations from the user, in View of MVC.

Question: What we will define in Struts-config.xml file. And explain their purpose?
In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins

Example :

<!– Date Sources –>
<data-sources>
<data-source autoCommit="false" description="First Database Config" driverClass=" org.gjt.mm.mysql.Driver" maxCount="4" minCount="2" password="admin" url="jdbc: mysql://localhost/ARTICLEDB" user="admin">
</<data-sources>
<!– Form Beans –>
<form-beans>
<form-bean name="registrationForm" type="com.aaa.merchant.wsp.ActionForms.RegistrationForm">
</form-bean>

<!– Global Exceptions –>
<global-exceptions>
<exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/>

</global-exceptions>

<!– A global-forward is retrieved by the ActionMapping findForward method. When the findForward method can't find a locally defined forward with the specified name, it searches the global-forwards available and return the one it finds.–>
<global-forwards>
<forward name="logoff" path="/logoff"/>
<forward name="logon" path="/logon.jsp"/>
</global-forwards>

<!– Actionn Mappings –>
<action-mappings>
<action path="/validateRegistration" type="com.dd.merchant.wsp.Actions.ValidateRegistration" validate="true" input="" name="registrationForm">
<forward name="success" path="/logon.jsp">
</forward>
</action>
</action-mappings>

<!– Message Resources –>
<message-resources parameter="wsppaymentsweb.resources.ApplicationResources"/>

<!– Plug-ins –>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>

===============================

Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is responsible for instructing the Struts what forms are available, what actions are available, and also allows a number of plug-in models to be added to the base Struts package. It can contain Data Source Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message Resources Definitions etc.

The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions.

The <form-bean/> is configured using only two attributes, name and type and doesn't contain any body. The form-bean tag is used to describe an instance of a particular Form Bean that will be later bound to action.

The attribute name specifies the name of the form bean, which is a unique identifier to this form bean & the attribute type specifies the absolute path of the class file.

<global-forwards/>: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The <forward/> specifies the mapping of a logical name to a context-relative URI path. In the above sample xml file we can see, one of the <forward/> is specified with the name as failure and its corresponding path as index.jsp. That means whenever the logical name failure is encountered the action will be forwarded to the index.jsp page.

The optional attribute redirect is set to false by default. When it is set to true it causes the ActionServlet to use HttpSevletResponse.sendRedirect() method.

<action-mappings/>: The action mapping mainly defines the mapping between the logical Action name and the physical action class. Now lets have an understanding about its attributes.

· The attribute path must be compulsorily defined and it should start with a '/' character. It specifies the context relative path of the submitted request.

· The type attribute specifies the absolute path of the fully qualified class name of the Action class.

· The attribute name must be the same as that of the form bean name for which you want to associate the action.

· The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session.

· The next attribute validate is also an optional one which by default is set to true. When set to true, the validate() method in the form bean is called which gets associated with a particular Action.

· The next attribute, input is also optional. Whenever a validation error is encountered then the control returns to the path specified in the input attribute.

<controller/>: The <controller/> can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor.

===============================
In struts-config.xml, we define all the global-forwards, action mappings, view mappings, form-bean mappings, controller mapping and finally message-resources declaration if any.
Why we need to declare means, the Controller servelet defined in struts internally looks for this xml file for its proceddings. In real scenario, that the controller servlet inplemented internally is nothing but a slave to this struts-config.xml. The information provided in this file is nothing but like the intelligence to the controller servlet to say - what to do in which situation ?
So, Controller servlet, needs this file to proceede/ run the application.

What is DispatchAction?

DispatchAction is specialized child of Struts Action class. It combines or group the methods that can further access the bussiness logic at a single place. The method can be anyone from CRUD [Create,Retrieve,Update or Delete] or it can be security check one like autheniticate user etc.
This class apart from having thread-safe execute method also can have user-defined methods.
In struts-config.xml files following changes are required for Dispatch action to work:

<action-mappings>
<action path="/login"
type ="com…..LoginAction"
name ="loginForm"
parameter ="task"
scope = "request"
validate = "false"
input = "/index.jsp">
<forward name="success" path="/jsp/common/index.jsp"/>
<forward name="loginagain" path="/index.jsp"/>
</action>
</action-mappings>

If above is your struts-config.xml file structure and LoginAction extends DispatchAction instead of normal Action class. And assuming [keep assuming] your LoginAction class have method named authenticateUser, then in your login.jsp add any hidden parameter called task with value as your method name and on submit of that page following will be the url:

http://localhost:8080/yourproject/jsp/login.jsp?login.do&task=authenticateUser

Thus if we try to combine the last part of this puzzle we get the climax at struts-config.xml file's action-mapping tag described above. The parameter property of <action> tag have the task as it's value pointing to task variable in the request having it's value as authenticateUser hence the framework search in the LoginAction a method called authenticateUser through reflection and forwards the execution flow to it. This is all folks, the briallancy of Struts framework. Note DispatchAction class is included in 1.1 version.

 

How to call ejb from Struts?

 

We can call EJB from struts by using the service locator design patteren or by Using initial context with create home object and getting return remote referenc object.

What is the difference between ActionErrors and ActionMessages?

There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message.

The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope.

 

What are the various Struts tag libraries?

The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) :
* Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their properties. Developers can also define new beans and set properties
* HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons
* Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation
* Nested tag library [ struts-nested.tld ] : allows the use of nested beans.

The libraries are designed to:

* Facilitate the separation of presentation and business logic.
* Dynamically generate Web pages.
* Implement the flow of control to and from the ActionServlet.

How you will handle errors and exceptions using Struts?

Struts exception handling can be done by two ways:
1. Declarative (using struts features via struts-config.xml)

<global-exceptions>
<exception
type="hansen.playground.MyException2"
key ="errors.exception2"
path="/error.jsp"/>
</global-exceptions>

This makes coding in the Action class very simple
Since the execute method declares throws Exception we don't need a try-catch block.
Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY to retrieve it from the request object.

2. Programmatic (using the usual try-catch exception handling in Action Class)

===============

We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts Framework. The other way around is by using the methods say saveErrors()….etc defined in Action class and can throw the error messages.

=================

Struts handles errors by providing the ActionErrors class which is
extended from org.apache.struts.action…
To install your customized exception handler, the first step is to
create a class that extends org.apache.struts.action.ExceptionHandler. There are
two methods that you can override, execute() and storeException().
For handling exceptions you have to mention in <global-exceptions> tag
of struts-config.xml which accepts attributes like exception type,key and
path.

How you will save the data across different pages for a particular client request using Struts?

One simple and general way is by using session Object.

In specific, we can pass this by using request Object as well.

======================================
Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request.

request.getSession()
session.setAttribute()

What is Action Class? What are the methods in Action class?

An Action class is some thing like an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.
The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Struts Action class is a unit of logic. It is where a call to business function is made. In short the Action class acts like a bridge between client side(user action) and business operation(on server.
Some of the impotant methods of Action class are, execute()
generateToken() resetToken() getServlet()

Explain about token feature in Struts?

 

Use the Action Token methods to prevent duplicate submits:
There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised.
 saveToken(request)
on the return trip,
 isTokenValid(request)
resetToken(request)

What is the difference between ActionForm and DynaActionForm

# The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

# The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.

# ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

# ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).

# DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

# Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application)

posted on 2006-12-04 15:46 Sun River 阅读(440) 评论(0)  编辑  收藏 所属分类: Struts