Interview Questions On Java,Java EE


Enter your email address:



Add to Technorati Favorites
Google PageRank Checker
Showing posts with label Struts. Show all posts
Showing posts with label Struts. Show all posts

Sunday, February 10, 2008

How to handle duplicate submits in Struts?

The duplicate form submission occurs

-When a user clicks the Submit button more than once before the response is sent back or
- When a client accesses a view by returning to a previously bookmarked page.

It may result in inconsistent transactions and must be avoided.In Struts this problem can be handled by using the saveToken() and isTokenValid() methods of Action class. saveToken() method creates a token (a unique string) and saves that in the user's current session, while isTokenValid() checks if the token stored in the user's current session is the same as that was passed as the request parameter.

It can be done by loading JSP through an Action and before loading the JSP call saveToken() to save the token in the user session. When the form is submitted, check the token against that in the session by calling isTokenValid().

public ActionForward submitOrder(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response) throws Exception

{

try

{

// check the token. Proceed only if token is valid

if(isTokenValid(request,true)) {

//implement order submit functionality here

} else {

return mapping.findForward("failure");

}

}

catch(Exception ex){//exception}

}
Continue reading...

Wednesday, November 28, 2007

What are Tag Libraries provided with Struts?

Struts supports following tag libraries:

a).Bean Tags: All tags which correspond to struts-bean.tld  provide capability of accessing beans related activities.

b).HTML Tags: All tags which correspond to struts-html.tld used for HTML UI/Forms creation.

c).Logic Tags: All tags which correspond to struts-logic.tld  manages condition based logic,iterate over a statement based on some logic and application flow  management.

d).Nested Tags: All tags which correspond to struts-nested.tld make it easy to manage nested beans.

e).Template Tags:
All tags which correspond to struts-template.tld used for template creation while providing better maintenance of such websites.

f). Tiles Tags:
All tags which correspond to struts-tiles.tld

Java Standard Tag Library (or JSTL as it's known), provides a specification for four separate areas of concern:

    * Core
    * XML Processing
    * Internationalization
    * Database

The specification also describes an expression language (EL) that is designed to simplify page development.Struts 1.1 even includes a version of the JSTL Tags based on the new Expression Language.

Some JSTLs:

c.tld 
c-rt.tld 
fmt.tld 
fmt-rt.tld 
sql.tld 
sql-rt.tld 
x.tld 
x-rt.tld
Continue reading...

Sunday, November 25, 2007

What are the differences between ActionErrors and ActionMessage?/What are the differences between Action.saveErrors(...) and Action.saveMessages(...)?

To summarize, the difference between the classes ActionErrors/ActionError/ActionMessages/ActionMessage has absolutely nothing to do with the difference in behavior in Action.saveErrors(...) and Action.saveMessages(...)

The difference between the classes is zero -- all behavior in ActionErrors was pushed up into ActionMessages and all behavior in ActionError was pushed up into ActionMessage. 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 -- 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.

The difference between html:errors and html:messages is purely in syntax and model -- both tags *default* to look for an ActionMessages object under  Globals.ERROR_KEY despite the difference in names.html:messages provides more flexibility at the cost of more typing.

Courtsey:http://wiki.apache.org/struts/
Continue reading...

Sunday, June 10, 2007

Interview Questions on Struts Framework

Continue reading...

What is DispatchAction?

org.apache.struts.actions.DispatchAction is responsible for

-Dispatches to a public method named on a request parameter
-Method name corresponds to the 'parameter' property of corresponding ActionMapping
-useful when multiple similar actions are to be clubbed within a singe Action class in order to simplify the design.

If you want to to insert,update and delete all actions on a database from a JSP with the same Action class in such case it will come quite handy.
Here is how this JSP looks like:
<html:form action="/saveSubscription">
<html:submit>
<bean:message key="insert"/>
</html:submit>
<html:submit>
<bean:message key="update"/>
</html:submit>
<html:submit>
<bean:message key="delete"/>
</html:submit>
</html:form>
To configure the use of this action in your struts-config.xml file, create an entry like this:

<action path="/saveSubscription" type="org.apache.struts.actions.DispatchAction" name="subscriptionForm" scope="request" input="/subscription.jsp" parameter="submit"/>

It will use the value of the request parameter named "submit" to pick the appropriate "execute" method, which must have the same signature (other than method name) of the standard Action.execute method. For example, you might have the following three methods in the same action:

* public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
* public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
* public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception

In our JSP, we can refer to the buttons in the usual way.Later, when the user selects a button, the form will pass the submit parameter, along with whatever message is Struts finds for "insert" or "delete" in the resource bundle.
Using the conventional DispatchAction, this approach would be problematic, not necessarily each message will map to a valid Java identifier. This is where the magic of the LookupDispatchAction comes into play.

When you create your LookupDispatchAction subclass, along with the methods for the dispatch operations you must also implement a getKeyMethodMap method. This is a "hotspot" that the LookupDispatchAction will call.

Here's an example of the methods you might declare in your subclass:

protected Map getKeyMethodMap(ActionMapping mapping,
ActionForm form,
HttpServletRequest request) {
Map map = new HashMap();
map.put("button.add", "add");
map.put("button.delete", "delete");
return map;
}

Internally, the base action will lookup the messages for 'insert' and 'delete', and match those against the submit parameter. When it finds a match, it will then use either "insert" or "delete" to call the corresponding methods.

So while the LookupDispatchAction means adding an extra method to your Action, it lets you skip putting a JavaScript in your form.

Both the DispatchAction and LookupDispatchAction are an excellent way to streamline your Struts action classes, and group several related operations into a single umbrella action. So, how many dispatch actions do you need? Can you use a dispatch action to collect everything into a single action?

In practice, you can easily use one dispatch action for any forms that share a common validation. It is not advisable to have sharing of dispatch action between different form beans, or form beans that are validated differently,as it can start to make things harder rather than simpler. But the use of a dispatch action can easily half or quarter the number of action classes in most Struts application.
Continue reading...

How does Validator framework work in Struts ?

The Validator framework is an open source project and is part of the Jakarta Commons subproject. The Commons project was created for the purpose of providing reusable components like the Validator. Other well-known Commons components include BeanUtils, Digester, and the Logging framework.It was first released in November 2002.
Validator framework consists of the following components:-


-Validators
-Configuration Files
-Resource Bundle
-JSP Custom Tags
-Validator Form Classes

Validators
are Java classes which execute validation rule.The framework knows how to invoke a Validator class based on its method signature, as defined in a configuration file. Typically, each Validator provides a single validation rule, and these rules can be chained together to form a more complex set of rules.

Configuration Files
:
There are two configuration files
-validator.xml
and
-validator-rules.xml

validator-rules.xml contains all possible validations available to an application. These validations are present as definitions in this file. The controlling document of Validator-rules.xml is Validator-rules_1_1.dtd.All the elements defined in this file are defined according to the above DTD.

The required validation is applied to mandatory fields, such as employee id(one example).The has many attributes. These attributes are,Name,Classname,MethodMethodparams,Msg

A simple validator-rule.xml file.click here.

Another configuration file is
validation.xml file.It is where you couple the individual Validators defined in the validator-rules.xml to components within your application. Since we are talking about using the Validator with Struts, the coupling occurs between the Validators and Struts ActionForm classes.ActionForm also provide a convenient spot to validate the user input before passing it to the business layer. Here is a simple validation.xml file.

Resource Bundle: Resource Bundle forms the base of localization. The error messages created when a rule fails come from the resource bundles. For the common Validators provided by the Validator framework, the default messages can be placed in the Struts application's message resources. Some of these messages are:
#Error messages used by the Validator
errors.required={0} is required.
errors.minlength={0} can not be less than {1} characters.
errors.maxlength={0} can not be greater than {1} characters.
errors.invalid={0}  is invalid.

The parameter in place of {0} and {1} is inserted automatically by the framework when the rules fail. These values are corresponding to the parameters comes from the Validator-rules.xml and validation.xml files.

JSP Custom Tags
Like errors and javascript Struts HTML tags required in case of validations. The former is for server-side validation while the latter is for client side validation.

Validator Form Class
In Struts data is passed from the JSP page (view layer) to Action class (controller layer) by means of ActionForm objects. The standard Struts ActionForm won't suffice to impose validation framework.The specially designed classes for this purpose come quite handy. It comes in two varieties- ValidatorForm and DynaValidatorForm. The former is used in place of ActionForm while the latter is used with the DynaActionForm. Whatever the variety being used, two methods used for performing validation which are present in both of them are- reset() and validate().

Integrating validator to Struts is done by introducing the following piece of data inside strust-config.xml:
The Validator framework is easily extensible and the effort required is minimal.
-Create your own validation classes.
-Hook it up inside
validation-rules.xml file

Apart from using in Struts application,the Validator framework can be used as a separate unit for validation of applications.
Continue reading...

How you will handle errors and exceptions in Struts?

An efficient error and exception handling makes an application behave gracefully under abnormal conditions.Struts has errors and exception handling done in different ways.The form validations using Struts require a proper mechanism.For handling errors in Struts,it has two objects ActionError and ActionErrors.Whenever a form is submitted then cotroller receives request and then create ActionForm object which calls reset() method and stores ActionForm object to required scope and then it loads ActionForm object from request and calls validate() method.If validate method fails then errors are displayed on the form itself through  <html:errors> tags.

Exception Handling can be done in following ways:

-try-catch block within

-Using declarative exception handling.In struts-config.xml we can declare on which type of exception, a request should be redirected to.

Use Global Exceptions tag in struts-config.xml

<global-exceptions>

<exception key="errors.MyException" type="java.lang.MyException"  path="/myExcption.jsp"/>

 So whenever MyException occurs then Struts framework will display 'myException.jsp' page.

The interpretation of this is that if MyException is caught by Struts' ActionServlet then it should redirect to myExcption.jsp. The key is as usual a pointer to the message resource file. 
Continue reading...

What are the methods in Action class?

An Action class in the struts application extends Struts 'org.apache.struts.action.Action" class. Action class acts as wrapper around the business logic and provides an interface to the application's Model layer. Action class mediates between the View and Model layer in both directions it means it transfers data to and fro from the view layer and the specific business process layer.

If you look at the sequence diagram, it gives you a correct picture how an Action class instance is invoked.When it is invoked then overridden execute() method is invoked.It is advisable not to put the business process logic inside execute method which should ideally have navigational logic details, instead move the database and business process logic to DAO layer.

Struts Sequence Diagram

The return type of the execute() method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object,mapping of which is provided in struts-config.xml file.

package dpun.action;


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 MyAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("myAction");
}
}
Action class has two execute methods ,one HTTP specific and the other protocol independent.The HTTP based execute method has following parameters:
ActionMapping mapping:This object is used to refer this instance.
ActionForm actionForm:It refers ActionForm bean class associated with this request. HttpServletRequest request:It represents HTTP request.
HttpServletResponse response:It represents HTTP response.

While protocol independent execute has ServletRequest and ServletResponse instead of HttpServletRequest and HttpServletResponse parameters.
Continue reading...

Explain Struts1.x in a nutshell?

Struts is consisted of technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages, like BeanUtils and Chain of Responsibility. It helps one create an extensible development environment for one's application, based on published standards and proven design patterns.


Struts Flow

Whenever a request comes from web browser then application's controller handles this request.When request is received then Controller invokes an Action class.This Action class object then communicates with Model class(which actually is a set of JavaBeans representation) to examine or update the application's state..The Struts ActionForm class helps in data exchange between Model and View layers.
A web application uses 'web.xml', a deployment descriptor to initialize resources like servlets and taglibs. Similarly, Struts uses a configuration file( struts-config.xml) to initialize its own resources. These resources include ActionForms to collect input from users, ActionMappings to direct input to server-side Actions, and ActionForwards to select output pages.Moreover,one can specify validations for the ActionForms in an XML descriptor, using the Struts Validator. A standard extension, Tiles, helps you build pages from smaller fragments.

Struts may not be a useful option for each type of web development application.If the application is huge and complex then Struts fits the bill in best way but if you are developing a web application which requires very little of web pages and business logic then MVC-1 based approach will be best rather MVC-2 based like Struts.
Continue reading...

What is Struts and how it helps in web development?

Apache Struts is a free open-source framework for creating Java web applications.Struts helps in providing dynamism to a web based application in contrast with many websites that deliver only static pages.A web application interacts with databases and business logic engines to customize a response.
Struts is based on MVC(Model-View-Controller) architecture based and it clearly segregate business logic from presentation which is somehow difficult to achieve with JavaServer Pages that sometimes mingle database code, page design code, and control flow code. Unless these components are not separated then it becomes quite difficult to maintain in large web based applications. The Model represents the business or database code, the View represents the page design code, and the Controller represents the business logic or navigational code.

The framework provides three key components:

  • A "request" handler provided by the application developer.It maps to a standard URI.
  • A "response" handler that transfers control to another resource which completes the response.
  • A tag library that helps developers create interactive form-based applications with server pages.
Struts works well with conventional REST applications and with new technologies like SOAP and AJAX.

By the time posting of this article,the latest version of Apache Struts is 'Struts 2.0.6', according to Apache it is an elegant, extensible framework for creating enterprise-ready Java web applications.,was originally known as WebWork 2.You can find out more information about Struts2 here.


Continue reading...
 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker