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.
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.
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.
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
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
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.
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:
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:
To configure the use of this action in your struts-config.xml file, create an entry like this:
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.
#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.
No comments:
Post a Comment