Struts – part 1

Struts is a widely used open framework for developing Jave EE web applications •Combines Java Servlets, JSP’s, 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

In this session -we’ll look on
Model-View-Controller (MVC) Architecture •How struts implements MVC architecture •Discuss different components of struts •A Sample Struts Application •Advantage of using Struts Model – View – Controller

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 controller components
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. •

jsp” scope=”request” type=”come.xml <struts-config> … <action path=“\login” type=”com. Struts view components The components user for view in Struts are •HTML . ActionForm form.AccountAction” scope=”request” parameter=”method” name=”loginForm”> <forward name=”success” path=“/homepage.InvalidLoginException”/> </action> class AccountAction extends DispatchAction{ public ActionForward viewAccount(ActionMapping mapping.struts.struts.invalidlogin” path=”/login.struts. HttpServletRequest request. •Data Transfer objects •EJBs •Business Object.jsp”> <forward name=”success” path=“/homepage.InvalidLoginException”/> </action> … <struts-config> Dispatch Action •Allows multiple operations normally scattered across multiple action classes to a single class.findForward(“nameOfNextView”) } } Struts-config. logging and session validation before invoking the business operation.jsp”/> <forward name=”failure” path=”/login. ActionForm form.action. HttpServletResponse response){ //take request parameters from the form and process them // return the next view return mapping. The following are the commonly used models.jsp”/> <exception key=”error. • Related functionality can be kept in a DispatchAction subclass <action path=“\login” type=”com. HttpServletRequest request.jsp”/> <exception key=”error.Struts Action Classes •Acts as a bridge between client side user action and business operation •Can perform other functions like authorization.exception.sample. •We usually extend the Action class and override the execute method Class LoginAction extends Action{ public ActionForward execute(ActionMapping mapping.exception.findForward(“nameOfNextView”) } } Struts model components Does not directly provide components for model since this is a web framework. HttpServletResponse response){ //take request parameters from the form and process them // return the next view return mapping.invalidlogin” path=”/login.action.sample.jsp”/> <forward name=”failure” path=”/login.struts.LoginAction” scope=”request” name=”loginForm” validate=”true” input=”/login.jsp” scope=”request” type=”come.sample.sample.

so that changes to the user interface do not impact the data handling and vice versa. and may invoke changes on the model./struts-html.action.struts. i.jar in /WEB-INF/lib/ <web-app> <servlet> <servlet-name>action</servlet-name> <servlet-class>org. • Framework collects the input(parameters) from request and populates the action forms using form beans. typically a user interface element.tld” prefix=“html”%> <html> … <html:form action=“login.xml</param-value> </init-param> </servlet> .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. Model • The domain-specific representation of the information on which the application operates.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value> /WEB-INF/struts-config.. • The model has no direct knowledge of the view. Model – View – Controller Model-view-controller (MVC) is a design pattern used to separate data (model) and user interface (view). • View • Renders the model into a form suitable for interaction. Configuring Struts •struts.apache.•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=“.e the data and the business logic. HTML pages in case of web applications • Controller • Processes and responds to user actions (request in web apps).

sample.jsp”> <forward name=”success” path=“/homepage.struts.xml <struts-config> … <action path=“\login” type=”com.<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.struts..jsp”/> <forward name=”failure” path=”/login.do</url-pattern> </servlet-mapping> <taglib> <!. ActionForm form. •We usually extend the Action class and override the execute method Class LoginAction extends Action{ public ActionForward execute(ActionMapping mapping.jsp”/> <exception key=”error.jsp”/> <forward name=”failure” path=”/login. ActionForm form. HttpServletResponse response){ //take request parameters from the form and process them // return the next view return mapping.struts.sample.sample.exception.jsp” scope=”request” type=”come.taglibs used in the applications –> </taglib> </web-app> Struts controller components ActionServlet •Extends HttpServlet •Configured in web.AccountAction” scope=”request” parameter=”method” name=”loginForm”> <forward name=”success” path=“/homepage.findForward(“nameOfNextView”) } } Struts model components .invalidlogin” path=”/login.invalidlogin” path=”/login.xml. • Related functionality can be kept in a DispatchAction subclass <action path=“\login” type=”com.sample. Struts Action Classes •Acts as a bridge between client side user action and business operation •Can perform other functions like authorization. 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.InvalidLoginException”/> </action> … <struts-config> Dispatch Action •Allows multiple operations normally scattered across multiple action classes to a single class. HttpServletRequest request. HttpServletRequest request.LoginAction” scope=”request” name=”loginForm” validate=”true” input=”/login.InvalidLoginException”/> </action> class AccountAction extends DispatchAction{ public ActionForward viewAccount(ActionMapping mapping.exception.struts.jsp” scope=”request” type=”come.jsp”/> <exception key=”error. HttpServletResponse response){ //take request parameters from the form and process them // return the next view return mapping.action.findForward(“nameOfNextView”) } } Struts-config.action. logging and session validation before invoking the business operation.

Struts view components The components user for view in Struts are •HTML •Data Transfer Objects •Struts Action Forms •JSP •Custom Tags •Resource Bundles Custom Tags • html • Logic • bean • nested Example code using the struts html tag <%@ taglib uri=“.tld” prefix=“html”%> <html>… <html:form action=“login.Does not directly provide components for model since this is a web framework.sample. The following are the commonly used models.struts.form.LoginForm”/> ./struts-html. •Data Transfer objects •EJBs •Business Object.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.jsp”/> </global-forwards> <action-mappings> <action path=“\login” type=”com.LoginAction” scope=”request” name=”loginForm” validate=”true” input=”/login.String”/> </form-bean> </form-beans> …</struts-config> Login Page <html:form action=“login. HttpServletRequest request){ ActionErrors errors = new ActionErrors().equals(userId)){ ActionError error = new ActionError(“error.jsp” scope=”request” .lang.sample.struts.String”/> <form-property name=”password” type=”java.xml <struts-config> <form-beans> <form-bean name=”loginForm” type=”com.nodatabase” path=“/error.sample.form.lang.jsp”/> <forward name=”failure” path=”/login. errors.DynaActionForm”> <form-property name=”userId” type=”java.… </form-beans> … </struts-config> DynaActionForms <struts-config> .add(error).struts.jsp”/> <exception key=”error. //getter and setter methods for these.DatabaseException”/> </global-exceptions> <global-forwards> <forward name=“sessiontimeout” path=“/sessiontimeout.struts.login. } //other validations return errors.<form-beans> <form-bean name=”loginForm” type=”org.struts.jsp” type=“com. } } Struts-config.do”> User: <html:text property=“userId”/> Password: <html:password property=“password”/> <html:submit value=“Submit”/> </html:form> ActionForm public LoginForm extends Action Form{ private String userId.action.apache. private String password.jsp”> <forward name=”success” path=“/homepage.invalidlogin” path=”/login.userRequired”). public ActionErrors validate(ActionMapping mapping.LoginForm”/> </form-beans> <global-exceptions> <exception key=“error.action. if(userId == null || “”.

String userId = loginForm.findForward(“failure”) } } More in Struts Struts tiles Advanced templating framework.exception.getPassword. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. In XML validation requirements are defined applied to a form. HttpServletRequest request. } return mapping.type=”come. In case we need special validation rules not provided by the validator framework. -Consistent use of MVC Struts Validator Framework Struts Validator Framework Struts Framework provides the functionality to validate the form data.findForward(“success”).InvalidLoginException”/> </action> </action-mappings> <message-resources name=“application”/> </struts-config> Action Class Class LoginAction extends Action{ public ActionForward execute(ActionMapping mapping. Advantages -Centralized file based configuration -Form beans automatically populated from request parameters. ActionForm form. It can be use to validate the data on the users browser as well as on the server side. Server side validation of the form can be accomplished by sub classing your From Bean withDynaValidatorForm class. password){ return mapping.getUserId String password = loginForm. HttpServletResponse response){ LoginForm loginForm = ( LoginForm) form. we can plug in our own custom validations into Validator.struts. Using Validator Framework Validator uses the XML file to pickup the validation rules to be applied to an form. validator framework and internationalization(i18n). Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings. if(authenticate(userId. . 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. validation possible -Struts custom tags -Supports tiles. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. allows for better organization of the components in the web application.sample.

these are reusable and used in validation. Each validation routine in the validatorrules.xml file specifies an error message key as value for this attribute. You can define validation logic for any number of Form Beans in this configuration file.1. Instead of having hard-coded error messages in the framework. Structure of validator-rule. The definitions in this file use the logical names of Form Beans from the strutsconfig. · jsFunctionName: Name of the javascript function is specified here. Thevalidator-rules. Inside that definition. . Date Validation. you specify the validations you want to apply to the Form Bean’s fields. Maximum length. Contains the code of the javascript function used for client-side validation. just as in struts 1.xml defines the standard validation routines.xml is provided with the Validator Framework and it declares and assigns the logical names to the validation routines. The validation. the value here is specified as ‘required’ for this attribute. are global and are accessed by all forms.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. Minimum Length.The Validator Framework uses two XML configuration files validator-rules.xml) is supplied with a predefined set of commonly used validation rules such as Required. · depends: If validation is required. Following table contains the details of the elements in this file: Element formvalidation global validator Attributes and Description This is the root node. It also contains the client-side javascript code for each validation routine. Structure of validation.xml file along with the logical names of validation routines from the validator-rules. This basic set of rules can also be extended with custom validators if required.xml.properties file that should be returned if a validation fails.2. Validator allows you to specify a key to a message in the ApplicationResources.xml configuration file defines which validation routines that is used to validate Form Beans.xml.xml The validation-rules.xml and validation. It contains nested elements for all of the other configuration settings. 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.xml defines the validations applied to a form bean. The validator details specified within this.xml This validation.xml file to tie the two together. The validator element defines what validators objects can be used with the fields referenced by the formset elements. The validation routines are java methods plugged into the system to perform specific validations. Starting in Struts 1. Email Address validation and more. javascript The Validator plug-in (validator-rules. to define the form specific validations.

Element Attributes and Description .

Validator uses this logical name to map the validations to a Form Bean defined in the struts-config. 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 Example of form in the validation.formvalidation global constant constantname constantvalue formset form This is the root node.username”/> </field> <field property=”password” depends=”required. and it defines the validations to apply to specified Form Bean fields. It contains nested elements for all of the other configuration settings The constant details are specified in <constant> element within this element.password”/> <var> <var-name>mask</var-name> <var-value>^[0-9a-zA-Z]*$</var-value> . field arg var var-name var-value A key for the error message to be thrown incase the validation fails.xml file that should be applied to the field. Name of the constant property is specified here Value of the constant property is specified here.xml file This element is inside the form element. Constant properties are specified within this element for pattern matching.mask”> <arg key=”logonForm. 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. This element contains multiple <form> elements This element contains the form details. is specified here Contains the variable names and their values as nested elements within this element. The attributes are: name:Contains the form name.xml file: <!– An example form –> <form name=”logonForm”> <field property=”username” depends=”required”> <arg key=”logonForm.

</var> </field> </form> .