0% found this document useful (0 votes)
77 views11 pages

In This Session - We'll Look On

The document discusses the Struts framework, which implements the Model-View-Controller (MVC) architecture for developing Java web applications. It describes the key components of Struts, including ActionServlet as the controller, Action classes as the bridge between user actions and business logic, views rendered through JSPs and tags, and various configuration files. It also provides examples of forms, actions, and forwarding in Struts applications.

Uploaded by

sourabhkarn6262
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views11 pages

In This Session - We'll Look On

The document discusses the Struts framework, which implements the Model-View-Controller (MVC) architecture for developing Java web applications. It describes the key components of Struts, including ActionServlet as the controller, Action classes as the bridge between user actions and business logic, views rendered through JSPs and tags, and various configuration files. It also provides examples of forms, actions, and forwarding in Struts applications.

Uploaded by

sourabhkarn6262
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

Struts part 1

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

In this session -well 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.

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) } }

Struts model components


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.

Struts view components


The components user for view in Struts are HTML

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.

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. 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) } }

Struts model components

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.

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=../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/>

</form-beans> </struts-config> DynaActionForms <struts-config> .<form-beans>

<form-bean name=loginForm type=org.apache.struts.action.DynaActionForm> <form-property name=userId type=java.lang.String/> <form-property name=password type=java.lang.String/>


</form-bean> </form-beans> </struts-config> Login Page <html:form action=login.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; //getter and setter methods for these. private String password; public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){ ActionErrors errors = new ActionErrors(); if(userId == null || .equals(userId)){ ActionError error = new ActionError(error.login.userRequired); errors.add(error); } //other validations return errors; } } Struts-config.xml <struts-config> <form-beans> <form-bean name=loginForm type=com.sample.struts.form.LoginForm/> </form-beans> <global-exceptions> <exception key=error.nodatabase path=/error.jsp type=com.sample.struts.DatabaseException/> </global-exceptions> <global-forwards> <forward name=sessiontimeout path=/sessiontimeout.jsp/> </global-forwards> <action-mappings> <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> </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

Struts Validator Framework


Struts Validator Framework Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used to validate the form data on the client browser. Server side validation of the form can be accomplished by sub classing your From Bean withDynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. 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. Using Validator Framework Validator uses the XML file to pickup the validation rules to be applied to an form. In XML validation requirements are defined applied to a form. In case we need special validation rules not provided by the validator framework, we can plug in our own custom validations into Validator.

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:

Element formvalidation global validator

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

Attributes and Description

formvalidation global constant constantname constantvalue formset form

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

arg var var-name var-value

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

Example of form in the validation.xml file:

<! 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>

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

You might also like