In This Session - We'll Look On
In This Session - We'll Look On
Struts is a widely used open framework for developing Jave EE web applications Combines Java Servlets, JSPs, custom tags and manages resources into a reusable framework Based on the Model-View-Controller Design pattern. Originally created by Craig McClanahan and donated to the Apache Foundation
Model-view-controller (MVC) is a design pattern used to separate data (model) and user interface (view), so that changes to the user interface do not impact the data handling and vice versa.
Model The domain-specific representation of the information on which the application operates. i.e the data and the business logic. View Renders the model into a form suitable for interaction, typically a user interface element. HTML pages in case of web applications Controller Processes and responds to user actions (request in web apps), and may invoke changes on the model. The model has no direct knowledge of the view. Configuring Struts struts.jar in /WEB-INF/lib/ <web-app> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value> /WEB-INF/struts-config.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <taglib> <!- - taglibs used in the applications > </taglib> </web-app>
Struts Action Classes Acts as a bridge between client side user action and business operation Can perform other functions like authorization, logging and session validation before invoking the business operation. We usually extend the Action class and override the execute method Class LoginAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ //take request parameters from the form and process them // return the next view return mapping.findForward(nameOfNextView) } } Struts-config.xml <struts-config> <action path=\login type=com.sample.struts.action.LoginAction scope=request name=loginForm validate=true input=/login.jsp> <forward name=success path=/homepage.jsp/> <forward name=failure path=/login.jsp/> <exception key=error.invalidlogin path=/login.jsp scope=request type=come.sample.struts.exception.InvalidLoginException/> </action> <struts-config> Dispatch Action Allows multiple operations normally scattered across multiple action classes to a single class. Related functionality can be kept in a DispatchAction subclass <action path=\login type=com.sample.struts.action.AccountAction scope=request parameter=method name=loginForm> <forward name=success path=/homepage.jsp/> <forward name=failure path=/login.jsp/> <exception key=error.invalidlogin path=/login.jsp scope=request type=come.sample.struts.exception.InvalidLoginException/> </action> class AccountAction extends DispatchAction{ public ActionForward viewAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ //take request parameters from the form and process them // return the next view return mapping.findForward(nameOfNextView) } }
Data Transfer Objects Struts Action Forms JSP Custom Tags Resource Bundles Struts view components Custom Tags html Logic bean nested Example code using the struts html tag <%@ taglib uri=../struts-html.tld prefix=html%> <html> <html:form action=login.do> User: <html:text property=userId/> Password: <html:password property=password/> <html:submit value=Submit/> </html:form> </html>
ActionForm Used to pass client data between the user and business layer.
Framework collects the input(parameters) from request and populates the action forms using form beans.
Configuring Struts
struts.jar in /WEB-INF/lib/ <web-app> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value> /WEB-INF/struts-config.xml</param-value> </init-param> </servlet>
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <taglib> <!- - taglibs used in the applications > </taglib> </web-app>
ActionServlet Extends HttpServlet Configured in web.xml, all requests reach the ActionServlet Instantiates and passes the request to the RequestProcessor RequestProcessor Delegates the handling of the request to a helper class(Action Class) based on the struts configuration file. Struts Action Classes Acts as a bridge between client side user action and business operation Can perform other functions like authorization, logging and session validation before invoking the business operation. We usually extend the Action class and override the execute method Class LoginAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ //take request parameters from the form and process them // return the next view return mapping.findForward(nameOfNextView) } } Struts-config.xml <struts-config> <action path=\login type=com.sample.struts.action.LoginAction scope=request name=loginForm validate=true input=/login.jsp> <forward name=success path=/homepage.jsp/> <forward name=failure path=/login.jsp/> <exception key=error.invalidlogin path=/login.jsp scope=request type=come.sample.struts.exception.InvalidLoginException/> </action> <struts-config> Dispatch Action Allows multiple operations normally scattered across multiple action classes to a single class. Related functionality can be kept in a DispatchAction subclass <action path=\login type=com.sample.struts.action.AccountAction scope=request parameter=method name=loginForm> <forward name=success path=/homepage.jsp/> <forward name=failure path=/login.jsp/> <exception key=error.invalidlogin path=/login.jsp scope=request type=come.sample.struts.exception.InvalidLoginException/> </action> class AccountAction extends DispatchAction{ public ActionForward viewAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ //take request parameters from the form and process them // return the next view return mapping.findForward(nameOfNextView) } }
Does not directly provide components for model since this is a web framework. The following are the commonly used models. Data Transfer objects EJBs Business Object.
Custom Tags
html Logic bean nested Example code using the struts html tag <%@ taglib uri=../struts-html.tld prefix=html%> <html> <html:form action=login.do> User: <html:text property=userId/> Password: <html:password property=password/> <html:submit value=Submit/> </html:form> </html>
Struts Configuration File <struts-config> <form-beans> <form-bean name=loginForm type=com.sample.struts.form.LoginForm/>
type=come.sample.struts.exception.InvalidLoginException/> </action> </action-mappings> <message-resources name=application/> </struts-config> Action Class Class LoginAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ LoginForm loginForm = ( LoginForm) form; String userId = loginForm.getUserId String password = loginForm.getPassword; if(authenticate(userId, password){ return mapping.findForward(success); } return mapping.findForward(failure) } }
More in Struts
Struts tiles Advanced templating framework, that separates content from the layout Struts validator framework Declaratively configure validation routines without having to program validation logic Multiple module support Separate configuration files for different modules, allows for better organization of the components in the web application. Advantages -Centralized file based configuration -Form beans automatically populated from request parameters, validation possible -Struts custom tags -Supports tiles, validator framework and internationalization(i18n). -Consistent use of MVC
The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. Thevalidator-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. Structure of validator-rule.xml The validation-rules.xml is provided with the Validator Framework and it declares and assigns the logical names to the validation routines. It also contains the client-side javascript code for each validation routine. The validation routines are java methods plugged into the system to perform specific validations. Following table contains the details of the elements in this file:
Attributes and Description This is the root node. It contains nested elements for all of the other configuration settings. The validator details specified within this, are global and are accessed by all forms. The validator element defines what validators objects can be used with the fields referenced by the formset elements. The attributes are: name: Contains a logical name for the validation routine classname: Name of the Form Bean class that extends the subclass of ActionForm class method: Name of the method of the Form Bean class methodParams: parameters passed to the method msg:Validator uses Struts Resource Bundle mechanism for externalizing error messages. Instead of having hard-coded error messages in the framework, Validator allows you to specify a key to a message in the ApplicationResources.properties file that should be returned if a validation fails. Each validation routine in the validatorrules.xml file specifies an error message key as value for this attribute. depends: If validation is required, the value here is specified as required for this attribute. jsFunctionName: Name of the javascript function is specified here. Contains the code of the javascript function used for client-side validation. Starting in Struts 1.2.0 the default javascript definitions have been consolidated to commons-validator. The default can be overridden by supplying a <javascript> element with a CDATA section, just as in struts 1.1.
javascript
The Validator plug-in (validator-rules.xml) is supplied with a predefined set of commonly used validation rules such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. This basic set of rules can also be extended with custom validators if required. Structure of validation.xml This validation.xml configuration file defines which validation routines that is used to validate Form Beans. You can define validation logic for any number of Form Beans in this configuration file. Inside that definition, you specify the validations you want to apply to the Form Beans fields. The definitions in this file use the logical names of Form Beans from the strutsconfig.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.
Element
This is the root node. It contains nested elements for all of the other configuration settings The constant details are specified in <constant> element within this element. Constant properties are specified within this element for pattern matching. Name of the constant property is specified here Value of the constant property is specified here. This element contains multiple <form> elements This element contains the form details. The attributes are: name:Contains the form name. Validator uses this logical name to map the validations to a Form Bean defined in the struts-config.xml file This element is inside the form element, and it defines the validations to apply to specified Form Bean fields. The attributes are: property: Contains the name of a field in the specified Form Bean depends: Specifies the logical names of validation routines from the validator-rules.xml file that should be applied to the field.
field
A key for the error message to be thrown incase the validation fails, is specified here Contains the variable names and their values as nested elements within this element. The name of the criteria against which a field is validated is specified here as a variable The value of the field is specified here
<! An example form > <form name=logonForm> <field property=username depends=required> <arg key=logonForm.username/> </field> <field property=password depends=required,mask> <arg key=logonForm.password/> <var> <var-name>mask</var-name> <var-value>^[0-9a-zA-Z]*$</var-value>