261
RoseIndia Struts 2 Tutorial and Online free training helps you learn new elegant Struts 2 Framework with examples. Struts 2 is very elegant and flexible front controller framework based on many standard technologies like Java Filters, Java Beans, ResourceBundles, XML etc. Struts 2 Training! Get Trained Now!!! 1. Struts 2 Features It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own. 2. Struts 2 History Apache Struts is an open-source framework that is used for developing Java web application. Originally developed by the programmer and author Craig R. McClanahan this was later taken over by the Apache Software Foundation in 2002. 3. Struts 2 Architecture Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant for the development of enterprise web application of any size. In this section we are going to explain you the architecture of Struts 2 Framework. 4. Why Struts 2 The new version Struts 2.0 is a combination of the Sturts action framework and Webwork. According to the Struts 2.0.1 release announcement, some key features are: 5. Struts 1.x Vs Struts 2.x In the following section, we are going to compare the various features between the two frameworks. Struts 2.x is very simple in comparison to the struts 1.x, few of its excelling features are: 6. Downloading and Installing Struts 2 In this section we will download and install the Struts 2.0 on the latest version of Tomcat container. We will first download tomcat and configure it as our development server. Struts 2 Hello World Application 7. Creating the development directory Structure In this section we will create directory structure of our Struts 2 Hello World application based on Struts 2 framework. Our Struts 2 Hello World application is your first step towards developing applications based on Struts 2 framework. 8. Writing Jsp, Java and Configuration files In this section we will write JSP, Java and required configuration files for our Struts 2 Hello World application. Now in struts 2 struts.xml is used to configure the applications. We will also deploy and test the application. 9. Struts 2 xml configuration file In this section we will introduce you with the struts.xml file. This section explains you how best you can use the struts.xml file for you big projects.

23277934-STRUTS2-ROSEINDIA

Embed Size (px)

DESCRIPTION

Struts2-RoseIndia

Citation preview

Page 1: 23277934-STRUTS2-ROSEINDIA

RoseIndia Struts 2 Tutorial and Online free training helps you learn new elegant Struts 2 Framework with examples. Struts 2 is very elegant and flexible front controller framework based on many standard technologies like Java Filters, Java Beans, ResourceBundles, XML etc.

Struts 2 Training! Get Trained Now!!!

1. Struts 2 Features It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own.

2. Struts 2 History Apache Struts is an open-source framework that is used for developing Java web application. Originally developed by the programmer and author Craig R. McClanahan this was later taken over by the Apache Software Foundation in 2002.

3. Struts 2 Architecture Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant for the development of enterprise web application of any size. In this section we are going to explain you the architecture of Struts 2 Framework.

4. Why Struts 2The new version Struts 2.0 is a combination of the Sturts action framework and Webwork. According to the Struts 2.0.1 release announcement, some key features are:

5. Struts 1.x Vs Struts 2.xIn the following section, we are going to compare the various features between the two frameworks. Struts 2.x is very simple in comparison to the struts 1.x, few of its excelling features are:

6. Downloading and Installing Struts 2In this section we will download and install the Struts 2.0 on the latest version of Tomcat container. We will first download tomcat and configure it as our development server. Struts 2 Hello World Application

7. Creating the development directory StructureIn this section we will create directory structure of our Struts 2 Hello World application based on Struts 2 framework. Our Struts 2 Hello World application is your first step towards developing applications based on Struts 2 framework.

8. Writing Jsp, Java and Configuration filesIn this section we will write JSP, Java and required configuration files for our Struts 2 Hello World application. Now in struts 2 struts.xml is used to configure the applications. We will also deploy and test the application.

9. Struts 2 xml configuration fileIn this section we will introduce you with the struts.xml file. This section explains you how best you can use the struts.xml file for you big projects.

Page 2: 23277934-STRUTS2-ROSEINDIA

Struts 2 Actions

10. Struts 2 Actions ExampleWhen a client request matches the action's name, the framework uses the mapping from struts.xml file to process the request.

11. Struts 2 Actions IntroductionWhen a client request matches the action's name, the framework uses the mapping from struts.xml file to process the request. The mapping to an action is usually generated by a Struts Tag.

12. Struts 2 Redirect ActionIn this section, you will get familiar with struts 2 Redirect action and learn to use it in the struts 2 application.

Struts 2 Login Application

13. Developing Login Application in Struts 2In this section we are going to develop login application based on Struts 2 Framework. Our current login application does not validate the user against the database.

14. Adding Validation to Struts 2 Login ApplicationIn this section we will write the code to validate the login application. After completing this section you will be able to write validations for your Struts 2 projects.

15. Running and testing applicationIn this section we will run the example on Tomcat 6.0 server and check how it works.

16. Client Side Validation in Struts 2 Login ApplicationIn this section we will see how to write code that will generate Java Script code for client side validation. In the last section we developed Login-validator.xml configuration file for defining the server side validation.

17. Validations using Struts 2 AnnotationsIn this section we are going to validate our login application using Annotations in Action class. Our current login application does not validate the user against the database. More Struts Validator ExamplesUser input validations are an integral part of any web application. With the release of Struts 2, validation are now much easy and robust. Struts 2 support Ajax based and even server side validations.

18. Login/Logout With SessionIn this section, we are going to develop a login/logout application with session. This application checks the user authentication. Whenever you run, it takes a user id and a password (Both the user id and password is "admin") it displays the welcome page, when both fields are correctly filled.

Page 3: 23277934-STRUTS2-ROSEINDIA

19. Connecting to MySQL Database in Struts 2 (Struts 2 MySQL)In this section, You will learn to connect the MySQL database with the struts 2 application.

20. Rich Editor Example In this section, you will learn how to create pagination in struts 2.

21. Validate TextAreaIn this section, you will learn how to validate your text area in struts 2. A text area contains 1 to 250 characters. It cann't support "null" value. Struts 2 Tags

22. Struts TagsIn this section we will introduce you with the tags provided along with Struts 2 framework. It is necessary to understand all the tags provided along with Struts 2 framework. Struts 2 Tags Examples

23. Struts 2 Tags Examples (Generic Tags)Struts 2 tags tutorials and examples.

24. Control Tags-If / Else If / ElseIn this section we are going to discuss the various control tags ( The Control Tags are used for flow control such as if, else and iterate.).

25. Append Tag (Control Tags) ExampleIn this section, we are going to describe the append tag. The append tag is a generic tag that is used to merge multiple iterators into one iterator.

26. Generator Tag (Control Tags) ExampleIn this section, we are going to describe the generator tag. The generator tag is a generic tag that is used to generate iterators based on different attributes passed.

27. Generator Tag (Control Tags) Using Count AttributesIn this section, we are going to describe the generator tag using the count attributes.

28. Generator Tag (Control Tags) Using an Iterator with Id AttributesIn this section, we are going to describe the generator tag using the id attributes.

29. Iterator Tag (Control Tags) ExampleIn this section, we are going to describe the Iterator tag. Iterator tag is used to iterate over a value. An iterable value can be either of: java.util.Collection or java.util.Iterator.

30. Merge Tag (Control Tags) ExampleIn this section, we are going to describe the merge tag. The merge tag is a generic tag that is used to merge iterators. The successive call to the merge iterator causes each merge iterator to have a chance to expose its elements, subsequently next call allows the next iterator to expose its element.

31. Subset Tag (Control Tags) ExampleIn this section, we are going to describe the subset tag. The subset tag is a generic tag that takes an iterator and outputs a subset of it. It delegates to org.apache.struts2.util.SubsetIteratorFilter internally to perform the subset functionality.

32. Subset Tag (Control Tags) Example Using CountIn this section, we are going to describe the subset tag using the count parameter. The count parameter indicates the number of entries to be set in the resulting subset iterator.

Page 4: 23277934-STRUTS2-ROSEINDIA

33. Subset Tag (Control Tags) Example Using StartIn this section, we are going to describe the subset tag using the start parameter. The start parameter is of integer type. It indicates the starting index (eg. first entry is 0) of entries in the source (needed to make available as the first entry in the resulting subset iterator).

34. Action Tag (Data Tag) ExampleIn this section, we are going to describe the action tag. The action tag is a generic tag that is used to call actions directly from a JSP page by specifying the action name and an optional namespace.

35. Bean Tag (Data Tag) ExampleIn this section, we are going to describe the Bean Tag. The Bean tag is a generic tag that is used to instantiates a class that confirms to the JavaBeans specification.

36. Date Tag (Data Tag) ExampleIn this section, we are going to describe the Date tag. The date tag allows to format a Date in a quick and easy way. User can specify a custom format (eg. "dd/MM/yyyy hh:mm"), can generate easy readable notations (like "in 2 hours, 14 minutes"), or can just fall back on a predefined format with key 'struts.date.format' in the properties file.

37. Include Tag (Data Tag) ExampleIn this section, we are going to describe the include tag. The include tag is a generic tag that is used to include a servlet's output (result of servlet or a JSP page) to the current page.

38. Param Tag (Data Tag) ExampleIn this section, we are going to describe the param tag. The param tag is a generic tag that is used to parameterize other tags. For example the include tag and bean tag. The parameters can be added with or without a name as a key.

39. Set Tag (Data Tag) ExampleIn this section, we are going to describe the Set tag. The set tag is a generic tag that is used to assign a value to a variable in a specified scope.

40. Text Tag (Data Tag) ExampleIn this section, we are going to describe the text tag. The text tag is a generic tag that is used to render a I18n text message.

41. Property Tag (Data Tag) ExampleIn this section, we are going to describe the property tag. The property tag is a generic tag that is used to get the property of a value, which will default to the top of the stack if none is specified.

42. Struts 2 Tags (UI Tags) Examples Form Tags Examples

43. Auto Completer ExampleIn this section, we are going to describe the autocompleter tag. The autocompleter tag always displays a dropdown list with the options that have at least a partial match with entered text in the textbox. If the user clicks on the dropdown button then all options shown in the dropdown list.

44. Checkbox Tag (Form Tag) ExampleIn this section, we are going to describe the checkbox tag. The checkbox tag is a UI tag that is used to render an HTML input element of type checkbox, populated by the specified property from the ValueStack.

Page 5: 23277934-STRUTS2-ROSEINDIA

45. Checkboxlist Tag (Form Tag) ExampleIn this section, we are going to describe the checkboxlist tag. The checkboxlist tag is a UI tag that creates a series of checkboxes from a list. Setup is like <s:select /> or <s:radio />, but creates checkbox tags.

46. Combobox Tag (Form Tag) ExampleIn this section, we are going to describe the combobox tag. The combo box is basically an HTML INPUT of type text and HTML SELECT grouped together to give you a combo box functionality.

47. Datetimepicker Tag (Form Tag) ExampleIn this section, we are going to describe the datetimepicker tag. The datetimepicker tag is a UI tag that is used to render a date/time picker in a dropdown container.

48. Doubleselect Tag (Form Tag) ExampleIn this section, we are going to describe the doubleselect tag. The doubleselect tag is a UI tag that renders two HTML select elements with second one changing displayed values depending on selected entry of first one.

49. File Tag (Form Tag) ExampleIn this section, we are going to describe the file tag. The file tag is a UI tag that renders an HTML file input element achieved through browsing.

50. Form Tag ExampleIn this section, we are going to describe the form tag. The form tag is a UI tag that renders HTML an input form.

51. Label Tag (Form Tag) ExampleIn this section, we are going to describe the label tag. The label tag is a UI tag that is used to render an HTML LABEL that allows to output label:name type of combinations that has the same format treatment as the rest of UI controls.

52. Optiontransferselect Tag (Form Tag) ExampleIn this section, we are going to describe the Optiontransferselect tag. The Optiontransferselect tag is a UI tag that creates an option transfer select component.

53. Optgroup Tag (Form Tag) ExampleIn this section, we are going to describe the optgroup tag. The optgroup tag is a UI tag that creates an optgroup component which needs to reside within a select tag <s:select>.

54. Password Tag (Form Tag) ExampleIn this section, we are going to describe the password tag. The password tag is a UI tag that renders an HTML input tag of type password.

55. Radio Tag (Form Tag) ExampleIn this section, we are going to describe the radio tag. The radio tag is a UI tag that renders a radio button input field.

56. Reset Tag (Form Tag) ExampleIn this section, we are going to describe the reset tag. The reset tag is a UI tag that is used with the form tag to provide form resetting.

57. Select Tag (Form Tag) ExampleIn this section, we are going to describe the select tag. The select tag is a UI tag that is used to render an HTML input tag of type select.

58. Submit Tag (Form Tag) ExampleIn this section, we are going to describe the submit tag. The submit tag is a UI tag that is used to render a submit button. The submit tag is used with the form tag to provide asynchronous form submissions.

Page 6: 23277934-STRUTS2-ROSEINDIA

59. Textarea Tag (Form Tag) ExampleIn this section, we are going to describe the textarea tag. The textarea tag is a UI tag that is used to render an HTML textarea.

60. Textfield Tag (Form Tag) ExampleIn this section, we are going to describe the textfield tag. The textfield tag is a UI tag that is used to render an HTML input field of type text.

61. Updownselect Tag (Form Tag) ExampleIn this section, we are going to describe the updownselect tag. The updownselect tag is a UI tag that creates a select component with buttons to move up and down the elements in the select component.

Non-Form UI Tags62. Actionerror and Actionmessage Tags (Non-Form UI Tags) Example

In this section, we are going to describe the actionerror and actionmessage tags. The actionerror tag is a UI tag that renders action errors (in the jsp pages.) if they exists while the actionmessage tag renders action messages if they exists.

63. Fielderror Tag (Non-Form UI Tags) ExampleIn this section, we are going to describe the fielderror tags. The fielderror tag is a UI tag that renders field errors if they exists.

64. TabbedPanel (Ajax Tag) ExampleIn this section, you will learn about the tabbedPanel tag. This is an Ajax component, where each tab is either a local content or a remote content (refreshed each time when user selects that tab).

65. tree and treenode (Ajax Tag) tags ExampleIn this section, you will learn about the tree and treenode tags. These both work with the Ajax support.

66. Div (Ajax Tag) tag ExampleIn this section, you will learn about the div tag. The div tag is an Ajax component that is used with Ajax that refreshes the contents of a particular section without refreshing the entire page. Struts 2 Examples

67. Struts 2 DateIn this section we will discuss the date processing functionalities available in the Struts 2 Framework.

68. Date Format ExamplesIn this tutorials you will learn about Date Format function in Struts 2. We have provided fully tested example code to illustrate the concepts.

69. Struts 2 datepicker ExampleIn this section we will show you how to develop datetimepicker in struts 2. Struts 2 uses the dojo toolkit for creating date picker.

70. Struts 2 Format ExamplesIn this section you will learn how to format Date and numbers in Struts 2 Framework.

Page 7: 23277934-STRUTS2-ROSEINDIA

Our Struts 2 Format Examples are very easy to grasp and you will learn these concepts in very small time.

71. Struts 2 File UploadIn this section you will learn how to write program in Struts 2 to upload the file on the server. In this example we are also providing the code to save the uploaded file in any directory on the server machine. Struts 2 Resources Examples

72. Struts 2 Resources ExamplesThe struts 2 resources examples

73. Static ParameterIn this section, we will develop a simple application to access the static parameters. We will use a JavaBean to set and get the static parameters. Each static parameter has a value.

74. Accessing Session ObjectIn this section, we will develop a simple application to access the framework resources like the session object, session context and the last accessed session time.

75. Access Request and Response In this section, you will learn to develop an application that accesses the request and response object in struts 2 application.

Struts 2 Tools 76. Struts 2 Eclipse Plugin

This page contains the examples and the list of plugins that are available for Struts 2 Development using Eclipse IDE.

77. Struts 2 IDEThis page contains the list of IDEs available to ease the development of Struts 2 Framework based applications. The IDE for Struts 2 will actually make the development cycle much easier.

78. Struts 2 ApplicationDeveloping user registration application based on Struts 2 Framework. This Struts 2 Application is a simple user registration application that will help you to learn how to develop real world applications using Struts 2 Framework.

79. Struts 2 AjaxIn this section we explain you Ajax based development in Struts 2. Struts 2 provides built-in support for Ajax using Dojo toolkit.

Struts 2 Features

Page 8: 23277934-STRUTS2-ROSEINDIA

The strut-2 framework is designed for the compilation of the entire development cycle including of building, developing and maintaining the whole application. It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own. The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.

Some of the general features of the current Apache Strut 2 framework are given below.

Architecture – First the web browser request a resource for which the Filter Dispatcher decides the suitable action. Then the Interceptors use the required functions and after that the Action method executes all the functions like storing and retrieving data from a database. Then the result can be seen on the output of the browser in HTML, PDF, images or any other.

Tags - Tags in Strut 2 allow creating dynamic web applications with less number of coding. Not only these tags contain output data but also provide style sheet driven markup that in turn helps in creating pages with less code. Here the tags also support validation and localization of coding that in turn offer more utilization. The less number of codes also makes it easy to read and maintain.

MVC – The Model View Controller in Strut 2 framework acts as a coordinator between application’s model and web view. Its Controller and View components can come together with other technology to develop the model. The framework has its library and markup tags to present the data dynamically.

Configuration – Provides a deployment descriptor to initialize resources in XML format. The initialization takes place simply by scanning all the classes using Java packages or you can use an application configuration file to control the entire configuration. Its general-purpose defaults allow using struts directly Out of the box.

Configuration files are re-loadable that allows changes without restarting a web container.

Other Features:

• All framework classes are based on interfaces and core interfaces are independent from HTTP.

• Check boxes do not require any kind of special application for false values.

• Any class can be used as an action class and one can input properties by using any JavaBean directly to the action class.

• Strut 2 actions are Spring friendly and so easy to Spring integration.

• AJAX theme enables to make the application more dynamic.

Page 9: 23277934-STRUTS2-ROSEINDIA

• Portal and servlet deployment are easy due to automatic portlet support without altering code.

• The request handling in every action makes it easy to customize, when required.

Struts 2 - History of Struts 2 Apache Struts is an open-source framework that is used for developing Java web application. Originally developed by the programmer and author Craig R. McClanahan, this was later taken over by the Apache Software Foundation in 2002. Struts have provided an excellent framework for developing application easily by organizing JSP and Servlet based on HTML formats and Java code. Strut1 with all standard Java technologies and packages of Jakarta assists to create an extensible development environment. However, with the growing demand of web application, Strut 1 does not stand firm and needs to be changed with demand. This leads to the creation of Strut2, which is more developer friendly with features like Ajax, rapid development and extensibility.

Struts is a well-organized framework based on MVC architecture. In Model-View-Controller Architecture, Model stands for the business or database code, View represents the page design code and the Controller for navigational code. All these together makes Struts an essential framework for building Java applications. But with the development of new and lightweight MVC based framworks like Spring, Stripes and Tapestry, it becomes necessary to modify the Struts framework. So, the team of Apache Struts and another J2EE framework, WebWork of OpenSymphony joined hand together to develop an advanced framework with all possible developing features that will make it developer and user friendly.

Strut2 contains the combined features of Struts Ti and WebWork 2 projects that advocates higher level application by using the architecture of WebWork2 with features including a plugin framework, a new API, Ajax tags etc. So the Struts communities and the WebWork team brought together several special features in WebWork2 to make it more advance in the Open Source world. Later the name of WebWork2 has changed to Struts2. Hence, Apache Strut 2 is a dynamic, extensible framework for a complete application development from building, deploying and maintaining.

WebWork is a framework for web-application development that has been included in Struts framework 2.0 release. It has some unique concepts and constructs like its compatibility of working within existing Web APIs in Java rather than trying to replace them completely. It has been built specifically taking into account the developer’s productivity and code simplicity. Furthermore it is completely context dependent that provides a wrapper around XWork. When working on web applications the web work provides a context that helps web developer in specific implementations.

Page 10: 23277934-STRUTS2-ROSEINDIA

While, XWork provides a mechanism that is used for configuration and factory implementation management. This mechanism is dependencies inject mechanism.

Struts 2 Architecture - Detail information on Struts 2 Architecture

Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant for the development of enterprise web application of any size. In this section we are going to explain you the architecture of Struts 2 Framework.

Request Lifecycle in Struts 2 applications

1. User Sends request: User sends a request to the server for some resource.

2. FilterDispatcher determines the appropriate action: The FilterDispatcher looks at the request and then determines the appropriate Action.

3. Interceptors are applied: Interceptors configured for applying the common functionalities such as workflow, validation, file upload etc. are automatically applied to the request.

4. Execution of Action: Then the action method is executed to perform the database related operations like storing or retrieving data from the database.

5. Output rendering: Then the Result renders the output.

6. Return of Request: Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.

7. Display the result to user: Finally the control is returned to the servlet container, which sends the output to the user browser.

Image: Struts 2 high level overview of request processing:

Page 11: 23277934-STRUTS2-ROSEINDIA

Struts 2 Architecture

Struts 2 is a very elegant and flexible front controller framework based on many standard technologies like Java Filters, Java Beans, ResourceBundles, XML etc.

For the Model, the framework can use any data access technologies like JDBC, EJB, Hibernate etc and for the View, the framework can be integrated with JSP, JTL, JSF, Jakarta Velocity Engine, Templates, PDF, XSLT etc.

Exception Handling:

The Struts 2 Framework allows us to define exception handlers and inceptors.

• Exception Handlers:Exception handlers allows us to define the exception handling procedure on global and local basis. Framework catches the exception and then displays the page of our choice with appropriate message and exception details.

• Interceptors:The Interceptors are used to specify the "request-processing lifecycle" for an action. Interceptors are configured to apply the common functionalities like workflow, validation etc.. to the request.

Struts 2 Architecture

The following diagram depicts the architecture of Struts 2 Framework and also shows the the initial request goes to the servlet container such as tomcat, which is then passed through standard filer chain.

Image: Struts 2 Architecture

Page 12: 23277934-STRUTS2-ROSEINDIA

The filter chain includes:

• Action ContextCleanUp filter:The ActionContextCleanUp filter is optional and it is useful when integration has to be done with other technologies like SiteMash Plugin.

• FilterDispatcher: Next the FilterDispatch is called, which in turn uses the ActionMapper to determine whether to invoke an Action or not. If the action is required to be invoked, the FilterDispatcher delegates the control to the ActionProxy.

• ActionProxy:The ActionProxy takes help from Configuration Files manager, which is initialized from the struts.xml. Then the ActionProxy creates an ActionInvocation, which implements the command pattern. The ActionInvocation process invokes the Interceptors (if configured) and then invokes the action. The the ActionInvocation looks for proper result. Then the result is executed, which involves the rendering of JSP or templates.

Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file. If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the

Page 13: 23277934-STRUTS2-ROSEINDIA

ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.

In this section we have learnt about the Architecture of Struts 2 Framework.

Why Struts 2

The new version Struts 2.0 is a combination of the Sturts action framework and Webwork. According to the Struts 2.0.1 release announcement, some key features are:

• Simplified Design - Programming the abstract classes instead of interfaces is one of design problem of struts1 framework that has been resolved in the struts 2 framework. Most of the Struts 2 classes are based on interfaces and most of its core interfaces are HTTP independent. Struts 2 Action classes are framework independent and are simplified to look as simple POJOs. Framework components are tried to keep loosely coupled.

• Simplified Actions - Actions are simple POJOs. Any java class with execute() method can be used as an Action class. Even we don't need to implement interfaces always. Inversion of Control is introduced while developing the action classes. This make the actions to be neutral to the underlying framework .

• No more ActionForms - ActionForms feature is no more known to the struts2 framework. Simple JavaBean flavored actions are used to put properties directly. No need to use all String properties.

• Simplified testability - Struts 2 Actions are HTTP independent and framework neutral. This enables to test struts applications very easily without resorting to mock objects.

• Intelligent Defaults - Most configuration elements have a default value which can be set according to the need. Even there are xml-based default configuration files that can be overridden according to the need.

• Improved results - Unlike ActionForwards, Struts 2 Results provide flexibility to create multiple type of outputs and in actual it helps to prepare the response.

• Better Tag features - Struts 2 tags enables to add style sheet-driven markup capabilities, so that we can create consistent pages with less code. Struts 2 tags are more capable and result oriented. Struts 2 tag markup can be altered by changing an underlying stylesheet. Individual tag markup can be changed by editing a FreeMarker template. Both JSP and FreeMarker tags are fully supported.

• Annotations introduced : Applications in struts 2 can use Java 5 annotations as an alternative to XML and Java properties configuration. Annotations minimize the use of xml.

• Stateful Checkboxes - Struts 2 checkboxes do not require special handling for false values.

• QuickStart - Many changes can be made on the fly without restarting a web container.

• customizing controller - Struts 1 lets to customize the request processor per module, Struts 2 lets to customize the request handling per action, if desired.

• Easy Spring integration - Struts 2 Actions are Spring-aware. Just need to add Spring beans!

• Easy plugins - Struts 2 extensions can be added by dropping in a JAR. No manual configuration is required!

Page 14: 23277934-STRUTS2-ROSEINDIA

• AJAX support - The AJAX theme gives interactive applications a significant boost.The framework provides a set of tags to help you ajaxify your applications, even on Dojo. The AJAX features include:

•1. AJAX Client Side Validation

2. Remote form submission support (works with the submit tag as well)

3. An advanced div template that provides dynamic reloading of partial HTML

4. An advanced template that provides the ability to load and evaluate JavaScript remotely

5. An AJAX-only tabbed Panel implementation

6. A rich pub-sub event model

7. Interactive auto complete tag

Struts 1.x Vs Struts 2.x

In the following section, we are going to compare the various features between the two frameworks. Struts 2.x is very simple as compared to struts 1.x, few of its excelent features are:

1. Servlet Dependency:

Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2, Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are represented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.

2. Action classes

Programming the abstract classes instead of interfaces is one of design issues of struts1 framework that has been resolved in the struts 2 framework. Struts1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class may or may not implement interfaces to enable optional and custom services. In case of Struts 2 , Actions are not container dependent because they are made simple POJOs. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with an execute signature can be used as an Struts 2 Action object.

3. Validation

Struts1 and Struts 2 both supports the manual validation via a validate method.Struts1 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

4. Threading Model

Page 15: 23277934-STRUTS2-ROSEINDIA

In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts1 Actions and requires extra care to develop. However in case of Struts 2, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)

5. Testability

Testing Struts1 applications are a bit complex. A major hurdle to test Struts1 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent, hence testability is quite easy in struts2.

6. Harvesting Input

Struts1 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input. However Struts 2 uses Action properties (as input properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.

7. Expression Language

Struts1 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can also use JSTL, however it supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

8. Binding values into views

In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.

9. Type Conversion

Usually, Struts1 ActionForm properties are all Strings. Struts1 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.

10. Control Of Action Execution

Struts1 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions as needed.

Page 16: 23277934-STRUTS2-ROSEINDIA

Download and Installing Struts 2

In this section we will download and install the Struts 2.0 on the latest version of Tomcat container. We will first download tomcat and configure it as our development server. Then we will download Struts 2.0 and install the struts-blank application on the tomcat server to check the examples that come with the struts-blank application.

Downloading Struts 2.0

Visit the Struts download site http://struts.apache.org/download.cgi and download the Struts 2.0 for this tutorial.

Page 17: 23277934-STRUTS2-ROSEINDIA

We have downloaded the Struts 2.0.6 (struts-2.0.6-all.zip) for this tutorial.

Download the Tomcat

Download the latest version of tomcat from http://tomcat.apache.org/download-55.cgi. We have downloaded apache-tomcat-5.5.20.zip for this tutorial.

I am assuming that latest version of Java is installed on your system. Extract downloaded file and run the C:\apache-tomcat-5.5.20\bin\startup.bat to start the tomcat. Type http://localhost:8080/ in your browser, it should show the welcome page in the browser window as shown below.

Page 18: 23277934-STRUTS2-ROSEINDIA

Congratulations you have now successfully installed latest version of tomcat for learning Struts 2.0. Now we will install the struts-blank application on the tomcat container and test the application.

Extracting Struts 2.0 distribution and installing on tomcat

Extract the downloaded struts distribution struts-2.0.6-all.zip into your favorite directory. To install the struts blank application copy "struts2-blank-2.0.6" from "<extracted directory>\struts-2.0.6-all\struts-2.0.6\apps" into the webapps directory of tomcat. Tomcat will automatically deploy the application.

Feb 25, 2007 11:42:23 PM org.apache.coyote.http11.Http11BaseProtocol startINFO: Starting Coyote HTTP/1.1 on http-8080Feb 25, 2007 11:42:24 PM org.apache.jk.common.ChannelSocket initINFO: JK: ajp13 listening on /0.0.0.0:8009Feb 25, 2007 11:42:24 PM org.apache.jk.server.JkMain startINFO: Jk running ID=0 time=0/141 config=nullFeb 25, 2007 11:42:24 PM org.apache.catalina.storeconfig.StoreLoader loadINFO: Find registry server-registry.xml at classpath resourceFeb 25, 2007 11:42:24 PM org.apache.catalina.startup.Catalina startINFO: Server startup in 6672 ms

Page 19: 23277934-STRUTS2-ROSEINDIA

Feb 25, 2007 11:52:55 PM org.apache.catalina.startup.HostConfig deployWARINFO: Deploying web application archive struts2-blank-2.0.6.war

To test the struts-blank application type http://localhost:8080/struts2-blank-2.0.6 in the browser and the struts-blank application get displayed in your browser window.

Click the English link and familiarize yourself with Struts Blank sample application.

Struts 2.0 distribution also contains the following sample applications that you can try:

• struts2-mailreader-2.0.6.war

• struts2-portlet-2.0.6.war

• struts2-showcase-2.0.6.war

You can simply copy these files to the webapps directory of your tomcat server. Tomcat will automatically deploy these applications and then you can test these applications.

Struts 2 Hello World Application Example, Learn how to develop Hello World application in struts 2

In this section we will develop Hello World application based on Struts 2 Framework. Our Struts 2 Hello World application is your first step towards developing applications based on Struts 2 Framework. We are here providing step by step guide for developing Hello World application in Struts 2 framework.

Tutorial covers basic steps like creating directory structure, developing build.xml file to build the application using ant build tool. Then we explained Java, JSP and configuration files that are required in this application.

Creating directory structure for the project

Step1: Extract struts 2 download and copy struts2-blank-2.0.6.war(If you are using latest version of struts 2 then version may be different for you) to your tomcats webapps directory. Rename struts2-blank-2.0.6.war to struts2tutorial and unzip it in the tomcats webapps

Page 20: 23277934-STRUTS2-ROSEINDIA

directory. Now start the tomcat and type http://localhost:8080/struts2tutorial/ into your browser. You browser should show look like:

Congratulations you have successfully installed struts 2 blank application to start with.

Step 2: Now delete the content of struts2tutorial\WEB-INF\src and struts2tutorial\WEB-INF\classes directories, as we don't need these files that comes with struts 2 blank application.

Step 3: Create build.xml file in the struts2tutorial\WEB-INF\src and paste the following content in the build.xml file.<project name="Struts 2 Tutorial" basedir="../" default="all"> <!-- Project settings --> <property name="project.title" value="RoseIndia Struts 2 Tutorials"/>

<property name="project.jar.file" value="struts2tutorial.jar"/>

<path id="class.path">

<fileset dir="lib">

<include name="**/*.jar"/>

</fileset>

<fileset dir="libext">

<include name="**/*.jar"/>

</fileset>

</path>

Page 21: 23277934-STRUTS2-ROSEINDIA

<!-- Classpath for Project -->

<path id="compile.classpath">

<pathelement path ="lib/commons-beanutils.jar"/>

<pathelement path ="lib/commons-digester.jar"/>

<pathelement path ="lib/struts.jar"/>

<pathelement path ="libext/servlet-api.jar"/>

<pathelement path ="libext/catalina-ant.jar"/>

<pathelement path ="classes"/>

<pathelement path ="${classpath}"/>

</path>

<!-- Check timestamp on files -->

<target name="prepare">

<tstamp/><copy

file="src/struts.xml"todir="src/classes"/>

</target><!-- Copy any resource or configuration files -->

<target name="resources">

<copy todir="src/classes" includeEmptyDirs="no">

<fileset dir="src/java">

<patternset>

<include name="**/*.conf"/>

<include name="**/*.properties"/>

<include name="**/*.xml"/>

</patternset>

</fileset>

</copy>

</target>

<!-- Normal build of application -->

Page 22: 23277934-STRUTS2-ROSEINDIA

<target name="compile" depends="prepare,resources">

<javac srcdir="src" destdir="src/classes" debug="true" debuglevel="lines,vars,source">

<classpath refid="class.path"/>

</javac>

<jar

jarfile="lib/${project.jar.file}"

basedir="src/classes"/>

</target><!-- Remove classes directory for clean build -->

<target name="clean"

description="Prepare for clean build">

<delete dir="classes"/>

<mkdir dir="classes"/>

</target>

<!-- Build Javadoc documentation -->

<target name="javadoc"

description="Generate JavaDoc API docs">

<delete dir="./doc/api"/>

<mkdir dir="./doc/api"/>

<javadoc sourcepath="./src/java"

destdir="./doc/api"

classpath="${servlet.jar}:${jdbc20ext.jar}"

packagenames="*"

author="true"

private="true"

version="true"

windowtitle="${project.title} API Documentation"

doctitle="&lt;h1&gt;${project.title}

Page 23: 23277934-STRUTS2-ROSEINDIA

Documentation (Version ${project.version})&lt;/h1&gt;"

bottom="Copyright &#169; 2002">

<classpath refid="compile.classpath"/>

</javadoc>

</target>

<!-- Build entire project -->

<target name="project" depends="clean,prepare,compile"/>

<!-- Create binary distribution -->

<target name="dist"

description="Create binary distribution">

<mkdir

dir="${distpath.project}"/>

<jar

jarfile="${distpath.project}/${project.distname}.jar"

basedir="./classes"/>

<copy

file="${distpath.project}/${project.distname}.jar"

todir="${distpath.project}"/>

<war

basedir="../"

warfile="${distpath.project}/${project.distname}.war"

webxml="web.xml">

<exclude name="${distpath.project}/${project.distname}.war"/>

</war>

</target>

Page 24: 23277934-STRUTS2-ROSEINDIA

<!-- Build project and create distribution-->

<target name="all" depends="project"/>

</project>

Step 4: Create directory libext under the struts2tutorial\WEB-INF\ then you copy latest Servlets api jar (in our case servlet-api.jar) file over there. This library file will be used to compile Servlets in our application.

Step 5: Now create directories java and classes under struts2tutorial\WEB-INF\src. The directory struts2tutorial\WEB-INF\src\java will be used to put all the java sources file and directory struts2tutorial\WEB-INF\src\classes will be used by ant build utility to store compiled java files.

Now we have successfully created the directory structure and ant build file for our Struts 2 Hello World Application. In the next section we will create JSP, Java file and the configuration file and then test our Struts 2 Hello World application.

Developing JSP, Java and Configuration for Hello World Application

In this section we will write JSP, Java and required configuration files for our Struts 2 Hello World application. Now in struts 2 struts.xml is used to configure the applications.

Understanding the application

Our application is very simple application that displays Hello World message along with current date and time of the server. When user clicks on the "Run Struts 2 Hello World Application" link on the tutorial home page, a request is sent to the struts framework. Then struts framework sends the input to the action class (in our case Struts2HelloWorld.java). After action is fired the Result selects the resource "/pages/HelloWorld.jsp" to render the response.

In this example we have to develop three parts view, Action class and mapping (struts.xml) to couple action and page. By creating these three components we are separating the application in three parts View, Model and Controller.

Developing View:This page is used to display the result on the browser. The HelloWorld.jsp is view part of our application. Create "HelloWorld.jsp" in the struts2tutorial\pages directory and add the following content:

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Hello World Application!</title></head><body><h2><s:property value="message" /></h2><p>Current date and time is: <b><s:property value="currentTime" /></b></body></html>

The line <%@ taglib prefix="s" uri="/struts-tags" %> declares data tag library of struts. The struts data tag is used to display the dynamic data. The tag <s:property value="message" />

Page 25: 23277934-STRUTS2-ROSEINDIA

and <s:property value="currentTime" /> calls the methods getMessage() and getCurrentTime() respectively of the Struts2HelloWorld action class and merges the values with response.

Developing Action (to interact with Model):

Now create Struts2HelloWorld.java and saves it to the "struts2tutorial\WEB-INF\src\java\net\roseindia" directory. This action class creates the message to be displayed on the screen. Here is the code of Struts2HelloWorld.java:

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

public class Struts2HelloWorld extends ActionSupport {

public static final String MESSAGE = "Struts 2 Hello World Tutorial!";

public String execute() throws Exception { setMessage(MESSAGE); return SUCCESS; }

private String message;

public void setMessage(String message){ this.message = message; }

public String getMessage() { return message; }

public String getCurrentTime(){ return new Date().toString(); }}

Developing Controller Configuration File:

Struts 2 uses the struts.xml file for configuring the application. Create struts.xml file and save it in the "struts2tutorial\WEB-INF\src" directory with the following content.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.enable.DynamicMethodInvocation" value="false" /><constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

Page 26: 23277934-STRUTS2-ROSEINDIA

<action name="HelloWorld" class="net.roseindia.Struts2HelloWorld"><result>/pages/HelloWorld.jsp</result></action>

<!-- Add actions here --></package>

<!-- Add packages here -->

</struts>

The struts.xml file should be present in the class path of the application, you can either include it in the jar and place in the lib directory of the application or place it in the classes directory of the web application. In our application we are using ant build tool which is including it in the jar file.

Building the application

I am assuming that you have already installed ant build tool on your machine. Since we are using the ant built tool, building application by using is very easy. To build the application open command prompt and go to "struts2tutorial\WEB-INF\src" directory of the web application and issue the "ant" command. The ant build tool will compile the java file and create jar file "struts2tutorial.jar" into the lib directory of your web application. Here is the output of ant build tool:

C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src>antBuildfile: build.xml

clean:[delete] Deleting directory C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\classes[mkdir] Created dir: C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\classes

prepare:

resources:

compile:[javac] Compiling 1 source file to C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src\classes[jar] Building jar: C:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\lib\struts2tutorial.jar

project:

all:

BUILD SUCCESSFUL

Page 27: 23277934-STRUTS2-ROSEINDIA

Total time: 7 secondsC:\apache-tomcat-6.0.10\apache-tomcat-6.0.10\webapps\struts2tutorial\WEB-INF\src>

Testing Struts 2 Hello World Application

In the above section we have compiled our application and now finally we will test our application. To test the application start the tomcat server and type http://localhost:8080/struts2tutorial/ and then select "Run Struts 2 Hello World Application" from the list. Here is the screen shot of our struts 2 tutorial home page:

Select "Run Struts 2 Hello World Application" link. Our first application "Struts 2 Hello World" will look like the following:

The application will display message "Struts 2 Hello World Tutorial!" along with current date and time of the server.

How application works?

Page 28: 23277934-STRUTS2-ROSEINDIA

Here is the brief description on how Struts 2 Hello World Application works:

Your browser sends a request to the web server for the URL http://localhost:8080/tutorial/HelloWorld.action.

1. When you click on the "Run Struts 2 Hello World Application" link, the browser sends a request for the url http://localhost:8080/struts2tutorial/roseindia/HelloWorld.action. The container requests for the resource "HelloWorld.action". By default web.xml file of struts blank application is configured to route all the request for *.action through org.apache.struts2.dispatcher.FilterDispatcher. Here is the configuration from web.xml file:<filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class></filter>

<filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>

2. Then the framework looks for the mapping for the action "HelloWorld" and then framework instantiates the appropriate class and calls the execute method. In this case action class is Struts2HelloWorld. Here is the configuration file from struts.xml which defines the action mapping:<action name="HelloWorld" class="net.roseindia.Struts2HelloWorld"><result>/pages/HelloWorld.jsp</result></action>

3. Then the execute method sets the message and returns SUCCESS. public String execute() throws Exception { setMessage(MESSAGE); return SUCCESS;}

Then framework determines which page is to be loaded if SUCCESS is returned. In our case framework tells the container to load HelloWorld.jsp and render the output.

In the struts 2 framework Actions are used to process the form and user request. The execute method of the action returns SUCCESS, ERROR, or INPUT value. Then based on these values framework tells the container to load and render the appropriate result.

4. Container process the HelloWorld.jsp and generates the output.

5. Then the output in the HTML format is sent to the browser.

Page 29: 23277934-STRUTS2-ROSEINDIA

Download the application and source code:You can download the application and source code of the tutorial and to save your time and efforts spent on configuring the application. Click here to download the code.

Our goal is to provide the working skeleton of the application based on ant tool. So you can download the application and then use ant tool to compile the java classes. Application is in the exploded directory structure and can be deployed as it is on tomcat server. If any of our visitor finds and problem please discuss it. We request you to share your experiences with us.

Struts Configuration file - struts.xml

In this section we will introduce you to the struts.xml file. This section explains you how best you can use the struts.xml file for you big projects.

The struts.xml File

The Struts 2 Framework uses a configuration file (struts.xml) to initialize its own resources. These resources include:

• Interceptors that can preprocess and postprocess a request

• Action classes that can call business logic and data access code

• Results that can prepare views using JavaServer Pages, Velocity and FreeMarker templates

At runtime, there is a single configuration for an application. Prior to runtime, the configuration is defined through one or more XML documents, including the default struts.xml document. There are several elements that can be configured, including packages, namespaces, includes, actions, results, interceptors, and exceptions.

The struts.xml file is the core configuration file for the framework and it should be present in the class path of your web application. Features of struts 2 configuration file:

• The struts.xml file allows to break big struts.xml file into small files and configuration files to be included as needed. Here is the example:

<struts>...........<include file="file1.xml"/><include file="file2.xml"/>..........</struts>

• You can even place struts-plugin.xml file in the JAR, and it will be automatically plugged into the application. This helps the programmers to develop self-configured components.

Page 30: 23277934-STRUTS2-ROSEINDIA

• If you want to use the frameworks such as Freemaker and Velocity modules, then the templates can also be loaded from classpath. This enables the developer to package entire module just in single JAR file.

Structure of the struts.xml file

In the last section we developed and tested the Hello World application. Here is the sample struts.xml file from the last example.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<constant name="struts.enable.DynamicMethodInvocation" value="false" /><constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="HelloWorld" class="net.roseindia.Struts2HelloWorld"><result>/pages/HelloWorld.jsp</result></action>

<!-- Add actions here --></package>

<!-- Add packages here -->

</struts>

The struts.xml file must confirm to the Struts 2 Document Type Definition (DTD)

The DTD provides information about the structure and the elements that the struts.xml file should have.Here is the Struts 2.0 DTD :<!-- Struts configuration DTD. Use the following DOCTYPE <!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

"http://struts.apache.org/dtds/struts-2.0.dtd">-->

<!ELEMENT struts (package|include|bean|constant)*>

<!ELEMENT package (result-types?, interceptors?,

Page 31: 23277934-STRUTS2-ROSEINDIA

default-interceptor-ref?, default-action-ref?, global-results?, global-exception-mappings?, action*)><!ATTLIST package name CDATA #REQUIRED extends CDATA #IMPLIED namespace CDATA #IMPLIED abstract CDATA #IMPLIED externalReferenceResolver NMTOKEN #IMPLIED>

<!ELEMENT result-types (result-type+)>

<!ELEMENT result-type (param*)><!ATTLIST result-type name CDATA #REQUIRED class CDATA #REQUIRED default (true|false) "false">

<!ELEMENT interceptors (interceptor|interceptor-stack)+>

<!ELEMENT interceptor (param*)><!ATTLIST interceptor name CDATA #REQUIRED class CDATA #REQUIRED>

<!ELEMENT interceptor-stack (interceptor-ref+)><!ATTLIST interceptor-stack name CDATA #REQUIRED>

<!ELEMENT interceptor-ref (param*)><!ATTLIST interceptor-ref name CDATA #REQUIRED>

<!ELEMENT default-interceptor-ref (param*)><!ATTLIST default-interceptor-ref name CDATA #REQUIRED>

<!ELEMENT default-action-ref (param*)><!ATTLIST default-action-ref name CDATA #REQUIRED>

<!ELEMENT global-results (result+)>

<!ELEMENT global-exception-mappings (exception-mapping+)>

<!ELEMENT action (param|result|interceptor-ref|exception-mapping)*><!ATTLIST action name CDATA #REQUIRED class CDATA #IMPLIED

Page 32: 23277934-STRUTS2-ROSEINDIA

method CDATA #IMPLIED converter CDATA #IMPLIED>

<!ELEMENT param (#PCDATA)><!ATTLIST param name CDATA #REQUIRED>

<!ELEMENT result (#PCDATA|param)*><!ATTLIST result name CDATA #IMPLIED type CDATA #IMPLIED>

<!ELEMENT exception-mapping (#PCDATA|param)*><!ATTLIST exception-mapping name CDATA #IMPLIED exception CDATA #REQUIRED result CDATA #REQUIRED>

<!ELEMENT include (#PCDATA)><!ATTLIST include file CDATA #REQUIRED>

<!ELEMENT bean (#PCDATA)><!ATTLIST bean type CDATA #IMPLIED name CDATA #IMPLIED class CDATA #REQUIRED scope CDATA #IMPLIED static CDATA #IMPLIED optional CDATA #IMPLIED>

<!ELEMENT constant (#PCDATA)><!ATTLIST constant name CDATA #REQUIRED value CDATA #REQUIRED >

It is possible to remove the “struts.xml” file from your application completely if the functionality of your application does not depends on it. There are few configurations that can be handled alternatively such as annotations, “web.xml” startup parameters, and alternate URL mapping schemes. Still, there are few configurations that always need the “struts.xml” file like the global results, exception handling, and the custom interceptor stacks.

Exploring struts.xml

The <struts> tag is the root tag for the struts.xml. It may contain the following tags : package, include, bean and constant.

1. The Package Tag :

Packages are a way to group actions, results, result types, interceptors, and interceptor-stacks

Page 33: 23277934-STRUTS2-ROSEINDIA

into a logical configuration unit. Conceptually, packages are similar to objects in that they can be extended and have individual parts that can be overridden by "sub" packages.

The <package /> tag is used to group together configurations that share common attributes such as interceptor stacks or URL namespaces. It may also be useful to organizationally separate functions, which may be further separated into different configuration files.

The package element has one required attribute, name, which acts as the key for later reference to the package. The extends attribute is optional and allows one package to inherit the configuration of one or more previous packages - including all interceptor, interceptor-stack, and action configurations.

Note that the configuration file is processed sequentially down the document, so the package referenced by an "extends" should be defined above the package which extends it.

The optional abstract attribute creates a base package that can omit the action configuration.

Attribute Required Descriptionname yes key for other packages to referenceextends no inherits package behavior of the package it extendsnamespace no provides a mapping from the URL to the package.

abstract no declares package to be abstract (no action configurations required in package)

1. name – unique name is given for a package.2. extends – the name of a package that this package will extend; all configuration information (including action configurations) from the extended package will be available in the new package, under the new namespace.3. namespace – the namespace provides a mapping from the URL to the package. i.e. for two different packages, with namespace attributes defined as “pack1” and “pack2”, the URLs would be something like “/webApp/pack1/my.action” and “/webApp/pack2/my.action”4. abstract – if this attribute value is “true” the package is truly a configuration grouping and actions configured will not be accessible via the package name. It is important to make sure you are extending the correct parent package so that the necessary pre-configured features will be available to you.

2. The Include Tag:

The <include /> tag is used to modularize a Struts2 application that needs to include other configuration files. It contains only one attribute “file” that provides the name of the xml file to be included. This file has exactly the same structure as the “struts.xml” configuration file. For example, to break a configuration file of a finance application, you might choose to group together the invoices, admin, report configurations etc into separate files:

<struts>

<include file="invoices-config.xml" /><include file="admin-config.xml" /><include file="reports-config.xml" />

Page 34: 23277934-STRUTS2-ROSEINDIA

</struts>

While including files, order is important. The information from the included file will be available from the point that the include tag is placed in the file.

There are some files that are included implicitly. These are the “strutsdefault.xml” and the “struts-plugin.xml” files. Both contains default configurations for result types, interceptors, interceptor stacks, packages as well as configuration information for the web application execution environment (which can also configured in the “struts.properties” file). The difference is that “struts-default.xml” provides the core configuration for Struts2, where “struts-plugin.xml” provides configurations for a particular plug-in. Each plug-in JAR file should contain a “struts-plugin.xml” file, all of which are loaded during startup.

3. The Bean Tag

Most applications won't need to extend the Bean Configuration. The bean element requires the class attribute which specifies the Java class to be created or manipulated. A bean can either

1. be created by the framework's container and injected into internal framework objects, or

2. have values injected to its static methods

The first use, object injection, is generally accompanied by the type attribute, which tells the container that which interface this object implements.

The second use, value injection, is good for allowing objects not created by the container to receive framework constants. Objects using value inject must define the the static attribute.

Attribute Required Descriptionclass yes the name of the bean classtype no the primary Java interface this class implements

name nothe unique name of this bean; must be unique among other beans that specify the same type

scope nothe scope of the bean; must be either default, singleton, request, session, thread

static nowhether to inject static methods or not; shouldn't be true when the type is specified

optional no whether the bean is optional or not

Bean Example (struts.xml)

<struts>

<bean type="roseindia.net.ObjectFactory" name="factory" class="roseindi

Page 35: 23277934-STRUTS2-ROSEINDIA

a.net.MyObjectFactory" /> ...

</struts>

4. The Constant Tag

There are two key roles for constants.

1. They are used to override settings like the maximum file upload size or whether the Struts framework should be in devMode(= development mode) or not. 2. They specify which Bean should be chosen, among multiple implementations of a given type.

Constants can be declared in multiple files. By default, constants are searched for in the following order, allowing for subsequent files to override by the previous ones:

• struts-default.xml

• struts-plugin.xml

• struts.xml

• struts.properties

• web.xml

The struts.properties file is provided for backward-compatiblity with WebWork. In the struts.properties file, each entry is treated as a constant. In the web.xml file, any FilterDispatcher initialization parameters are loaded as constants.

In the various XML variants, the constant element has two required attributes : name and value.

Attribute Required Descriptionname yes the name of the constantvalue yes the value of the constant

Constant Example (struts.xml)

<struts>

<constant name="struts.devMode" value="true" />

...

</struts>

Constant Example (struts.properties)

struts.devMode = true

Struts2 Actions

Page 36: 23277934-STRUTS2-ROSEINDIA

Struts2 ActionsWhen a client's request matches the action's name, the framework uses the mapping from struts.xml file to process the request. The mapping to an action is usually generated by a Struts Tag. Struts 2 Redirect ActionIn this section, you will get familiar with struts 2 Redirect action and learn to use it in the struts 2 application

. When a client's request matches the action's name, the framework uses the mapping from struts.xml file to process the request. The mapping to an action is usually generated by a Struts Tag. The action tag (within the struts root node of struts.xml file) specifies the action by name and the framework renders the default extension and other required stuff.

The default entry method to the handler class is defined by the Action interface. Struts2 Action interface

All actions may implement this interface, which exposes the execute() method. You are free to create POJOs that maintains the same contract defined by this interface without actually implementing the interface.package com.opensymphony.xwork2;public interface Action {

//The action execution was a failure. public final static String ERROR;

//The action execution require more input in order to succeed

public final static String INPUT;

//The action could not execute, since the user most was not logged in

public final static String LOGIN;

// The action execution was successful but do not show a view.

public final static String NONE;

//The action execution was successful. public final static String SUCCESS;

//the logic of the action is implementedpublic String execute() throws Exception;

}

Implementing the Action interface is optional. If Action is not implemented, the framework will use reflection to look for an execute method. If there is no execute method and no other method is specified in the configuration, the framework will throw an exception.

The Struts2 Action have introduced a simpler implementation approach of the action classes as POJO( Plain Old Java Objects). The most basic usage of an action, is to perform work with a single result always being returned. It looks like:public class NewAction { public String execute() throws Exception { // do the work

Page 37: 23277934-STRUTS2-ROSEINDIA

return "success"; }}

Note that here the action class doesn't extend any other class or interface. The method invoked in the processing of an action is the "execute" method. The "execute" method has no parameter and it returns a String object. However with struts 2 actions you can get different return types other than the string objects, by using helper interfaces available ( Helper interface provides the common results as constants like "success", "none", "error", "input" and "login").

The Action Class usually acts as a Model and executes a particular business logic depending on the Request object and the Input Parameters. In earlier versions of Struts (before Struts 2.0), an Action class is supposed to extend the org.apache.struts.Action class and has to override the Action.execute() method which takes four parameters.

Basically, actions are meant to process various objects like HttpServletRequest, HttpServletResponse. But here, our action class is not processing any object parameter. Here one important issue arises - how do you get access to the objects that you need to work with? The answer lies in the "inversion of control" or "dependency injection" pattern.

To provide a loosely coupled system, Struts2 uses a technique called dependency injection, or inversion of control. Dependency injection can be implemented by constructor injection, interface injection and setter injection. Struts2 uses setter injection. This means that to have objects available to the action, we need only to provide a setter method. There are also objects such as the HttpServletRequest that can be obtained by asking the ActionContext or implementing ServletRequestAware. Implementing ServletRequestAware is preferred. For each of the non-business objects there is a corresponding interface (known as an “aware” interface) that the action is required to implement.

To understand the inversion of control better, let's look at an example where the processing of the action requires access to the current requests HttpServletRequest object.

The dependency injection mechanism used in this example is interface injection. As the name implies, with interface injection there is an interface that needs to be implemented. This interface contains setter methods, which in turn are used to provide data to the action. In our example we are using the ServletRequestAware interface, here it is:

public interface ServletRequestAware { public void setServletRequest(HttpServletRequest request);}

When we implement this interface, our simple action gets modified a bit but now we have a HttpServerRequest object to use.public class NewAction implements addDependency { private HttpServletRequest request; public void setServletRequest(HttpServletRequest request) { this.request = request; } public String execute() throws Exception { // do the work using the request return "SUCCESS";

Page 38: 23277934-STRUTS2-ROSEINDIA

}}

In Struts2, an action instance is created for each request. It's not shared and it's discarded after the request has been completed.

Action Mappings

The action mapping can specify a set of result types, a set of exception handlers, and an interceptor stack. But, only the name attribute is required. The other attributes can also be provided at package scope. Specified through Struts.xml file.

The configuration for this action looks like this:<action name="new"

class="NewAction" ><result>view.jsp</result></action>

The “name” attribute provides the URL information to execute the action as “/new.action”. The extension “.action” is configured in the “struts.properties” configuration file. The “class” attribute provides the full package and class name of the action to be executed.

Struts 2 processes an action class as a POJO and enables to return different results depending on the outcome of the logic. To get different results, the class needs to get modified as:class NewAction {public void String execute() throws Exception {if ( its-ok() ) {return "login";} else {return "none";}}}

Here the class provides two different results, we have to configure the action tags of struts.xml file for each case. Modify the configuration as :<action name="new" class="NewAction" ><result>login.jsp</result><result name="none">none.jsp</result></action>

Struts 2 Redirect Action

In this section, you will get familiar with struts 2 Redirect action and learn to use it in the struts 2 application.

Page 39: 23277934-STRUTS2-ROSEINDIA

Redirect After Post: This post pattern is supported by Struts 2. This is a common pattern in web application. In which an action is redirected to another action. This is a common use to redirect action to display a page.

Redirect Action Result: This redirect pattern is supported by Struts 2. The ActionMapper provided by the ActionMapperFactory is used to redirect the browser to a URL that invokes the specified action. You can see a simple implementation of this in the following struts 2 application.

Redirects Dynamic Parameters: The action-redirect result takes following parameters:

• actionName

• namespace

• method

• encode

• parse

• location

• prependServletContext

Follow the steps to develop a Redirect Action example:

Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /><include file="struts-default.xml"/> <package name="roseindia" namespace="/roseindia" extends="struts-default">

<!-- Redirect Action -->

<action name="showAjaxLoginCancelForm"> <result>/pages/ajaxloginCancel.jsp</result> </action>

<action name="ajaxloginCancel" class="net.roseindia.Login"> <result name="input">/pages/ajaxloginCancel.jsp</result> <result name="error">/pages/ajaxloginCancel.jsp</result> <result name="cancel" type="redirect">/pages/ajaxloginCancel.jsp</result> <result>/pages/ajaxloginsuccess.jsp</result> </action> <!-- Add actions here --> </package>

Page 40: 23277934-STRUTS2-ROSEINDIA

<!-- Add packages here -->

</struts>

Step 2 : Create an input form.

ajaxloginCancel.jsp

<%@ taglib prefix="s" uri="/struts-tags"%><html> <head> <s:head theme="ajax" debug="true"/> </head> <body> <s:div id="loginDiv" theme="ajax"> <div style="width: 300px;border-style: solid"> <s:form action="ajaxloginCancel" validate="true"> <tr> <td colspan="2"> Login </td> </tr> <tr> <td colspan="2"> <s:actionerror /> <s:fielderror /> </td> <s:textfield name="username" label="Login name"/> <s:password name="password" label="Password"/> <s:submit value="Submit" theme="ajax" targets="loginDiv" notifyTopics="/ajaxloginCancel"/> <s:submit action="showAjaxLoginCancelForm" value="Cancel" onclick="form.onsubmit=null"/> </s:form> </div> </s:div> </body></html>

Step 3 : Create an Action class.

Login.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

/** * <p> Validate a user login. </p> */public class Login extends ActionSupport {

public String execute() throws Exception { if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){

Page 41: 23277934-STRUTS2-ROSEINDIA

addActionError("Invalid user name or password! Please try again!"); return ERROR; } if(getUsername().equals("Admin") || getPassword().equals("Admin")){ return SUCCESS; }else{ return NONE; } }

// ---- Username property ----

/** * <p>Field to store User username.</p> * <p/> */ private String username = null;

/** * <p>Provide User username.</p> * * @return Returns the User username. */ public String getUsername() { return username; }

/** * <p>Store new User username</p> * * @param value The username to set. */ public void setUsername(String value) { username = value; }

// ---- Username property ----

/** * <p>Field to store User password.</p> * <p/> */ private String password = null;

/** * <p>Provide User password.</p> * * @return Returns the User password. */ public String getPassword() { return password; }

Page 42: 23277934-STRUTS2-ROSEINDIA

/** * <p>Store new User password</p> * * @param value The password to set. */ public void setPassword(String value) { password = value; }

}

Step 4 : Create the appropriate validator as shown:

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

Login-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>Login name is required</message> </field-validator> </field> <field name="password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>Password is required</message> </field-validator> </field></validators>

When entered the correct user name and password then the user gets the ajaxloginsuccess.jsp page displaying the entered text

ajaxloginsuccess.jsp

<html> <head> <title>Login Success</title> </head> <body> <p align="center"><font color="#000080" size="5">Login Successful !</font></p> <h1> Welcome to <%=request.getParameter("username")%> </h1> </body></html>

Output:

When this application executes you get the following:

Page 43: 23277934-STRUTS2-ROSEINDIA

When you don't fill any field and click "Submit" button, you get:

If you click the "Cancel" button then redirect action executes and provides:

Struts 2 Login Application

Developing Struts 2 Login ApplicationIn this section we are going to develop login application based on Struts 2 Framework. Our current login application does not validate the user against the database. Instead login name and password are validated against the hardcode values (User: Admin and Password: Admin) in the actions class.

Working of the application

1. Login page is displayed to take the input.

2. User enters user name and password and then clicks on the "Login" button.

Page 44: 23277934-STRUTS2-ROSEINDIA

3. User validation is done in action class and if user enters Admin/Admin in the user name/password fields, then success pages is displayed. Otherwise the error message is displayed on the screen.

Steps to develope the application

Here are simple and easy steps to develop Login page in the using Struts 2 framework.

1. Develop Login FormThe GUI of the application consists of login form (login.jsp) and success message page (loginsuccess.jsp).The login.jsp is used to display the login page to the user. In our application it is saved in "webapps\struts2tutorial\pages\" folder. Here is the code of login.jsp file:

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Login Application!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>

</head><body><s:form action="doLogin" method="POST"><tr><td colspan="2">Login</td>

</tr>

<tr> <td colspan="2"> <s:actionerror /> <s:fielderror /> </td> </tr>

<s:textfield name="username" label="Login name"/><s:password name="password" label="Password"/><s:submit value="Login" align="center"/>

</s:form>

</body>

</html>

2. The code :<s:actionerror />

Page 45: 23277934-STRUTS2-ROSEINDIA

<s:fielderror />displays action errors and field validation errors.

3. The code <s:form action="doLogin" method="POST"> generates the html form for the application.

The code :<s:textfield name="username" label="Login name"/><s:password name="password" label="Password"/>generates Login Name and Password fields.

4. The submit button is generated through <s:submit value="Login" align="center"/> code.

When application is executed it generates the following html code: <html> <head> <title>Struts 2 Login Application!</title>

<link href="/struts2tutorial/css/main.css" rel="stylesheet" type="text/css"/>

</head>

<body><form id="doLogin" name="doLogin" onsubmit="return true;" action="/struts2tutorial/roseindia/doLogin.action" method="POST"><table class="wwFormTable">

<tr> <td colspan="2"> Login </td>

</tr>

<tr> <td class="tdLabel"><label for="doLogin_username" class="label"> Login name:</label> </td> <td><input type="text" name="username" value="" id="doLogin_username"/> </td> </tr>

<tr> <td class="tdLabel"><label for="doLogin_password" class="label"> Password:</label></td> <td><input type="password" name="password" id="doLogin_password"/></td></tr>

<tr> <td colspan="2"><div align="center"><input type="submit" id="doLogin_0" value="Login"/></div></td></tr>

Page 46: 23277934-STRUTS2-ROSEINDIA

</table></form> </body>

</html>

5.On viewing the above generated html code you will find that Struts 2 automatically generates form, html table, label for the html elements. This is the another great feature of Struts as compared to Struts 1.x.

The loginsuccess.jsp page displays the Login Success message when user is authenticated successfully. Here is the code of loginsuccess.jsp file:<html>

<head>

<title>Login Success</title>

</head>

<body>

<p align="center"><font color="#000080" size="5">Login Successful</font></p>

</body>

</html>

6.

7. Developing Action ClassNow let's develop the action class to handle the login request. In Struts 2 it is not necessary to implement the Action interface, any POJO object with execute signature can be used in Struts 2. The Struts 2 framework provides a base ActionSupport class to implement commonly used interfaces. In our action class (Login.java) we have implemented ActionSupport interface. Our "Login.java" is saved in the "webapps\struts2tutorial\WEB-INF\src\java\net\roseindia" directoy. Here is the code of Login.java action class:

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

/** * <p> Validate a user login. </p> */public class Login extends ActionSupport {

public String execute() throws Exception { System.out.println("Validating login"); if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){

Page 47: 23277934-STRUTS2-ROSEINDIA

addActionError("Invalid user name or password! Please try again!"); return ERROR; }else{ return SUCCESS; } }

// ---- Username property ----

/** * <p>Field to store User username.</p> * <p/> */ private String username = null;

/** * <p>Provide User username.</p> * * @return Returns the User username. */ public String getUsername() { return username; }

/** * <p>Store new User username</p> * * @param value The username to set. */ public void setUsername(String value) { username = value; }

// ---- Username property ----

/** * <p>Field to store User password.</p> * <p/> */ private String password = null;

/** * <p>Provide User password.</p> * * @return Returns the User password. */ public String getPassword() { return password; }

/** * <p>Store new User password</p>

Page 48: 23277934-STRUTS2-ROSEINDIA

* * @param value The password to set. */ public void setPassword(String value) { password = value; }

}

8.

9. Configuring action mapping (in struts.xml)Now we will create action mapping in the struts.xml file. Here is the code to be added in the struts.xml:

<action name="showLogin"><result>/pages/login.jsp</result></action>

<action name="doLogin" class="net.roseindia.Login"><result name="input">/pages/login.jsp</result><result name="error">/pages/login.jsp</result><result>/pages/loginsuccess.jsp</result></action>

10. In the above mapping the action "showLogin" is used to display the login page and "doLogin" validates the user using action class (Login.java).

11.CSS file (main.css)This css file is used to enhance the presentation of the login form. The main.css is saved into "\webapps\struts2tutorial\css" directory.Here is the code of main.css:

@CHARSET "UTF-8";

body {font: 12px verdana, arial, helvetica, sans-serif;background-color:#FFFFFF;}

table.wwFormTable {font: 12px verdana, arial, helvetica, sans-serif;border-width: 1px;border-color: #030;border-style: solid;color: #242;background-color: #ada;width: 30%;margin-left:35%;margin-right:35%;margin-top:15%;}

Page 49: 23277934-STRUTS2-ROSEINDIA

table.wwFormTable th {}

table.wwFormTable tr td {background-color: #dfd;margin: 5px;padding: 5px;}

.tdLabel {/*border-width: 1px;border-color: #afa;border-style: solid;*/font-weight: bold;align: top;}

.label {}

.errorMessage {color: red;font-size: 0.8em;}

#headerDiv {border-style: solid;border-width: 1px 1px 0px;border-color: black;padding: 5px;background-color: #7a7;/* height: 22px; */height: 1.8em;/* margin-bottom: 12px; */}

#buttonBar {border-width: 0px 1px 1px;border-style: solid;border-color: black;color: white;margin-bottom: 12px;background-color: #7a7;height: 1.6em;padding: 5px;

Page 50: 23277934-STRUTS2-ROSEINDIA

}

#appName {color: white;font-size: 1.8em;}

#pageTitle {font-size: 1.4em;color: #dfd;clear: none;}

#appName, #pageTitle {float: right;}

#menuContainer {float: left;}

#brandingContainer {float: right:text-align: right;}

In the next section we will learn how to add validation to the login application.

Struts 2 Validation Example

Validation Login applicationIn this section we will write the code to validate the login application. After completing this section you will be able to write validations for your Struts 2 projects. The concepts defined in this section are so illustrative that a learner quickly develops his/her skills in Struts 2 framework.

Struts 2 is very elegant framework that provides a lot of functionality to develop web based applications quickly. Here you will learn to write the form validation code in Struts 2 very easily. We will add the form validation code in our login application.

For validation the login application java script can be added to the jsp page or in action class, but Struts 2 provides another very easy method to validate your fields automatically. You can even use the same configuration file to generate client side script ( in next section we will see how to generate client side validation code).

The Struts 2 validation framework uses xml based configuration file. The file name should be <Your action class> -validation.xml. In our case our action class name is Login.java, so our validation configuration file will be Login-validation.xml. The Login-validation.xml will be saved into "webapps\struts2tutorial\WEB-INF\src\java\net\roseindia" directory. Here is the content of Login-validation.xml file:<?xml version="1.0" encoding="UTF-8"?>

Page 51: 23277934-STRUTS2-ROSEINDIA

<!DOCTYPE validators PUBLIC

"-//OpenSymphony Group//XWork Validator 1.0.2//EN"

"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>

<field name="username">

<field-validator type="requiredstring">

<param name="trim">true</param>

<message>Login name is required</message>

</field-validator>

</field>

<field name="password">

<field-validator type="requiredstring">

<param name="trim">true</param>

<message>Password is required</message>

</field-validator>

</field>

</validators>

In the above configuration file the field name corresponds to the ActionForm properties. For the username and password elements the requiredstring validation is applied and the message in the <message>....</message> tag is used to display the message if validation fails.

Compiling the application

To compile the application go to "\webapps\struts2tutorial\WEB-INF\src" directory and type ant command. The ant tool will compile the application for you.

Adding the link into index.html

Finally we add the link in the index.html to access the login form.

<ul><li><a href="roseindia/showLogin.action">Login Application</a></li></ul>

In the next section we will run and test the application.

Running and Testing Struts 2 Login application

Page 52: 23277934-STRUTS2-ROSEINDIA

Running Struts 2 Login ExampleIn this section we will run the example on Tomcat 6.0 server and check how it works.

Running Tomcat

To run the Tomcat, go to its bin directory and then double click on startup.bat. The startup.bat will start the tomcat.

Testing application

To test the application type http://localhost:8080/struts2tutorial/. Your browser should show the following screen:

Now click on "Login Application" link. Then your browser will display the Login page as shown below:

Now click on the "Login" button. Application will show the following error screen:

Page 53: 23277934-STRUTS2-ROSEINDIA

Now you enter the Login name "Admin" and click on the "Login" button, application will show the following error:

Now enter any password except "Admin", application will again show the error. This error is actually generated in the Action class.

Now enter the valid password "Admin" and click on "Login" button. Now the application will show you the welcome message as shown below.

Page 54: 23277934-STRUTS2-ROSEINDIA

Congratulation! Now you have successfully developed and tested your Struts 2 Login application. In the next section we will show you how to add client side Java Script validation using Struts 2 Validation framework.

Client Side validation in Struts 2 application

In this section we will see how to write code that will generate Java Script code for client side validation. In the last section we developed Login-validator.xml configuration file for defining the server side validation. In this section we will use the same Login-validator.xml file for generating the client side java script.

Developing JSP pages

Here is the code of login jsp page (loginClientSideValidation.jsp)

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Login Application!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/>

</head><body>

<s:form action="doLoginClientSideValidation" method="POST" validate="true">

<tr><td colspan="2">Login</td>

</tr>

<s:actionerror /><s:fielderror />

<s:textfield name="username" label="Login name"/><s:password name="password" label="Password"/><s:submit value="Login" align="center"/>

</s:form>

</body>

Page 55: 23277934-STRUTS2-ROSEINDIA

</html>

Note that in the above code we have just added validate="true" in the <s:form tag...>. This is the only work we have to do and rest work is done by Struts 2 validator framework. The validator framework generates JavaScript for validating the form at client side.

Changes in the struts.xml

Add the following code into struts.xml file:

<action name="showLoginClientSideValidation"><result>/pages/loginClientSideValidation.jsp</result></action>

<action name="doLoginClientSideValidation" class="net.roseindia.Login"><result name="input">/pages/loginClientSideValidation.jsp</result><result name="error">/pages/loginClientSideValidation.jsp</result><result>/pages/loginsuccess.jsp</result></action>

The action showLoginClientSideValidation displays login form while doLoginClientSideValidation handles the validation request.

Adding the link into index.html

Finally we add the link in the index.html to access the login form for testing client side validation.

<ul><li><a href="roseindia/showLoginClientSideValidation.action">Login Application (Client Side Validation)</a></li></ul>

Testing the Client side validation

Start tomcat and type http://localhost:8080/struts2tutorial/. Your browser should show the following screen:

Page 56: 23277934-STRUTS2-ROSEINDIA

Now click on "Login Application (Client Side Validation)" link. Then your browser will display the Login page as shown below:

Click on the "Login" button without entering anything. Java Script will show the error message as shown below:

Now enter the "Login Name" and click on the "Login" button, application will show error as shown below:

Page 57: 23277934-STRUTS2-ROSEINDIA

Examining the Java Script code generated

The following html code is generated by the framework:<html>

<head>

<title>Struts 2 Login Application!</title>

<link href="/struts2tutorial/css/main.css" rel="stylesheet"

type="text/css"/></head>

<body><script src="/struts2tutorial/struts/xhtml/validation.js"></script><form namespace="/roseindia" id="doLoginClientSideValidation" name="doLoginClientSideValidation" onsubmit="return validateForm_doLoginClientSideValidation();" action="/struts2tutorial/roseindia/doLoginClientSideValidation.action" method="POST">

<table class="wwFormTable">

<tr>

<td colspan="2">

Login

</td>

</tr>

<tr>

<td class="tdLabel"><label for="doLoginClientSideValidation_username" class="label">Login name:</label></td>

<td

><input type="text" name="username" value="" id="doLoginClientSideValidation_username"/>

</td>

</tr>

<tr>

<td class="tdLabel"><label for="doLoginClientSideValidation_password" class="label">Password:</label></td>

<td

><input type="password" name="password" id="doLoginClientSideValidation_password"/>

</td>

</tr>

Page 58: 23277934-STRUTS2-ROSEINDIA

<tr>

<td colspan="2"><div align="center"><input type="submit" id="doLoginClientSideValidation_0" value="Login"/>

</div></td>

</tr>

</table></form>

<script type="text/javascript">

function validateForm_doLoginClientSideValidation() {

form = document.getElementById("doLoginClientSideValidation");

clearErrorMessages(form);

clearErrorLabels(form);

var errors = false;

// field name: username

// validator name: requiredstring

if (form.elements['username']) {

field = form.elements['username'];

var error = "Login name is required";

if (field.value != null && (field.value == "" || field.value.replace(/^\s+|\s+$/g,"").length == 0)) {

addError(field, error);

errors = true;

}

}

// field name: password

// validator name: requiredstring

if (form.elements['password']) {

field = form.elements['password'];

var error = "Password is required";

if (field.value != null && (field.value == "" || field.value.replace(/^\s+|\s+$/g,"").length == 0)) {

addError(field, error);

errors = true;

}

}

return !errors;

}

</script>

</body>

</html>

Page 59: 23277934-STRUTS2-ROSEINDIA

In the above code you can see the JavaScript code and function validateForm_doLoginClientSideValidation() which is generated for client side validation

Validating Struts 2 Login Application using AnnotationsIn this section we are going to validate our login application using Annotations in Action class. Our current login application does not validate the user against the database. Instead login name and passwords are validated against the hardcode values (User: Admin and Password: Admin) in the actions class.

Working of the application

1. Login page is displayed to take the inputs.

2. User enters user name and password and then clicks on the "Login" button.

3. User validation is done in action class and if user enters Admin/Admin in the user name/password fields, then success pages is displayed. Otherwise the error message is displayed on the screen.

Steps to develop the application

Here are simple and easy steps to develop Login page in the using Struts 2 framework.

1. Develop Login FormThe GUI of the application consists of login form (log-in.jsp) and success message page (loginsuccess.jsp) .The log-in.jsp is used to display the login page to the user. In our application it is saved in "webapps\struts2tutorial\pages\" folder. Here is the code of log-in.jsp file:

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Login Application!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>

</head><body>

<s:form action="AnnotationAction" method="POST" validate="true"><tr><td colspan="2">Login</td>

</tr>

<tr> <td colspan="2"> <s:actionerror /> <s:fielderror /> </td> </tr>

Page 60: 23277934-STRUTS2-ROSEINDIA

<s:textfield name="username" label="Login name"/><s:password name="password" label="Password"/><s:submit value="Login" align="center"/>

</s:form>

</body>

</html>

1. The code :<s:actionerror /><s:fielderror />displays action errors and field validation errors.

The code <s:form action="AnnotationAction" method="POST" validate="true"> generates the html form for the application.

The code :<s:textfield name="username" label="Login name"/><s:password name="password" label="Password"/>generates Login Name and Password fields.

The submit button is generated through <s:submit value="Login" align="center"/> code.

The loginsuccess.jsp page displays the Login Success message when user is authenticated successfully. Here is the code of loginsuccess.jsp file:

<html>

<head>

<title>Login Success</title>

</head>

<body>

<p align="center"><font color="#000080" size="5">Login Successful</font></p>

</body>

</html>

2. Developing Action class (using Annotations to validate Login forms)Now let's develop the action class to handle the login request. The Struts 2 framework provides a base ActionSupport class to implement commonly used interfaces. In our action class (AnnotationAction.java) we have extended ActionSupport class and

Page 61: 23277934-STRUTS2-ROSEINDIA

imported the com.opensymphony.xwork2.validator.annotations package . For validating the login application java script can be added to the jsp page or in action class, but Struts 2 provides another very easy method to validate your form fields using annotations in the action class. Two annotations are needed,1. The @Validation annotation tells to Struts that action in this class might need to be validated. 2. The @RequiredStringValidator annotation is used for the text input to hold a singular value. Rest of the care is taken by the framework.

Our "AnnotationAction" class is saved in the "webapps\struts2tutorial\WEB-INF\src\java\net\roseindia" directoy. Here is the code of AnnotationAction.java action class:In this class we will write the code to validate the login page.

AnnotationAction.java

package net.roseindia; import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.validator.annotations.*;

@Validation public class AnnotationAction extends ActionSupport {

private String username = null; private String password = null;

@RequiredStringValidator(message="Supply name") public String getUsername() {

return username; }

public void setUsername(String value) {

username = value; } @RequiredStringValidator(message="Supply password")

public String getPassword() {

Page 62: 23277934-STRUTS2-ROSEINDIA

return password; }

public void setPassword(String value) { password = value; }

public String execute() throws Exception { System.out.println("Validating login"); if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){ addActionError("Invalid user name or password! Please try again!"); return ERROR; }else{ return SUCCESS; } }}

1. Configuring action mapping (in struts.xml)Now we will create action mapping in the struts.xml file. Here is the code to be added in the struts.xml:

<action name="LoginAnnotation"><result>/pages/log-in.jsp</result></action>

<action name="AnnotationAction" class="net.roseindia.AnnotationAction"><result name="input">/pages/log-in.jsp</result><result name="error">/pages/log-in.jsp</result><result>/pages/loginsuccess.jsp</result></action>

2. In the above mapping the action "LoginAnnotation" is used to display the login page and "AnnotationAction" validates the user using action class (AnnotationAction.java).

3. CSS file (main.css)This css file is used to enhance the presentation of the login form. The main.css is saved into "\webapps\struts2tutorial\css" directory.Here is the code of main.css:

@CHARSET "UTF-8";

Page 63: 23277934-STRUTS2-ROSEINDIA

body {font: 12px verdana, arial, helvetica, sans-serif;background-color:#FFFFFF;}

table.wwFormTable {font: 12px verdana, arial, helvetica, sans-serif;border-width: 1px;border-color: #030;border-style: solid;color: #242;background-color: #ada;width: 30%;margin-left:35%;margin-right:35%;margin-top:15%;}

table.wwFormTable th {}

table.wwFormTable tr td {background-color: #dfd;margin: 5px;padding: 5px;}

.tdLabel {/*border-width: 1px;border-color: #afa;border-style: solid;*/font-weight: bold;align: top;}

.label {}

.errorMessage {color: red;font-size: 0.8em;}

#headerDiv {border-style: solid;

Page 64: 23277934-STRUTS2-ROSEINDIA

border-width: 1px 1px 0px;border-color: black;padding: 5px;background-color: #7a7;/* height: 22px; */height: 1.8em;/* margin-bottom: 12px; */}

#buttonBar {border-width: 0px 1px 1px;border-style: solid;border-color: black;color: white;margin-bottom: 12px;background-color: #7a7;height: 1.6em;padding: 5px;}

#appName {color: white;font-size: 1.8em;}

#pageTitle {font-size: 1.4em;color: #dfd;clear: none;}

#appName, #pageTitle {float: right;}

#menuContainer {float: left;}

#brandingContainer {float: right:text-align: right;}

Compiling the application

To compile the application go to "\webapps\struts2tutorial\WEB-INF\src" directory and type ant command. The ant tool will compile the application for you.

Adding the link into index.html

Page 65: 23277934-STRUTS2-ROSEINDIA

Finally we add the link in the index.html to access the login form.

<ul><li><a href="roseindia/LoginAnnotation.action">Action Annotation Example</a></li></ul>

Output:

If you click Login button without filling the fields, you will get the output pages as :

If you fill only the "Login name" field and click Login button without filling the next fields, you will get the output pages as :

If you fill the wrong information and click the Login button, you will get the output pages as :

Page 66: 23277934-STRUTS2-ROSEINDIA

If you fill the correct information and click the Login button, you will get the output pages as :

Struts 2 Validation

User input validations are integral part of any web application. With the release of Struts 2, validation are now much easier and robust. Struts 2 support Ajax based and even server side validations. Struts 2.0 action relies on the XWork validation framework. The XWork framework runs the validation rules before executing the action. Struts 2 also provides the facility to define validation rules in your action class using Java 5 annotations.

1. Struts 2 Validation (Int Validator ) Struts 2 Framework provides in-built validation functions to validate user inputs. These validation functions are sufficient for any normal web application.

2. Struts 2 RequiredString validator This section discusses RequiredString validator of Struts 2 framework. RequiredStringValidator checks the String field is non-null and its length is > 0. (i.e. it isn't "").

3. Struts 2 double validator The Double validator of Struts 2 Framework checks if the given input is double or not. If the input is not double, it generates the error message. Double validator can also be used to check the input range.

4. Struts 2 Date Validator The Date validator in the Struts 2 Framework checks whether the supplied date lies

Page 67: 23277934-STRUTS2-ROSEINDIA

within a specific range or not. If the value supplied does not lie in the specified range, it generates an error message.

5. Struts 2 E-mail Validator The email validator in Struts 2 Framework checks whether a given String field is empty or not and contains a valid email address or not. If the entered value does not match with the email type, then the e-mail validator generates an error message.

6. Struts 2 Url Validator The URLValidator of Struts 2 Framework checks whether the String contained within the given field is a valid URL or not. If the entered value is not a valid URL, it generates an error message.

7. Validations using Struts 2 Annotations In this section we are going to validate our login application using Annotations in Action class. Our current login application does not validate the user against the database. Instead login name and passwords are validated against the hardcode values (User: Admin and Password: Admin) in the action

Struts 2 Validation (Int Validator)

Struts 2 Framework provides in-built validation functions to validate user inputs. These validation functions are sufficient for any normal web application. In some cases these standard set of validation functions are not sufficient to validate complex business logic. To validate complex business logic, Struts 2 validation framework can be extended to develop custom validation functions.

This section discusses all the validation functions available with Struts 2 framework. Subsequent sections of the tutorials discuss these validation functions with examples.

Validation Rules

Validation rules are an integral part of Struts 2 applications, where rules to validating particular user inputs are stored. Struts 2 validation framework validates user input against the defined rules.

The validation rules can be specified:

1. Per Action class: ActionName-validation.xml

2. Per Action alias: ActionName-alias-validation.xml

3. Inheritance hierarchy and interfaces are implemented by Action class. The XWork searches up the inheritance tree of the action to find default validations for parent classes of the action and interfaces implemented.

4. Using Java 5 annotations.

Struts 2 default validation functions

Following field validators are part of Struts 2 framework:

1. Conversion Validator

2. Date Validator

Page 68: 23277934-STRUTS2-ROSEINDIA

3. Double Validator

4. Email Validator

5. Expression Validator

6. Feldexpression Validator

7. Int Validator

8. Regex Validator

9. Required Validator

10. Requiredstring Validator

11. Stringlength Validator

12. URL Validator

13. Visitor Validator

Using Struts 2 Int Validator

Following example discusses the use of Int Validator to validate integer input by user. Here are the steps to develop Int validator example:

Step 1: Create the xml file and adds the following xml snippet in the struts.xml file.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default"> <!-- Add actions here -->

<!-- int validation -->

<action name="intValidation" class="net.roseindia.NumAction"> <result name="input">/pages/intInputForm.jsp</result> <result name="error">/pages/intInputForm.jsp</result> <result>/pages/intSuccess.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Step 2 : Create the input form.

Page 69: 23277934-STRUTS2-ROSEINDIA

intInputForm.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

<head><title>Input form</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> <s:head/></head>

<body> <s:form method="POST" action="intValidation"> </td> </tr> <s:textfield label="Enter Number" name="userinput" /> <s:submit /> </s:form>

</body>

</html>

Step 3 : Create the Action class.

NumAction.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class NumAction extends ActionSupport{ private int userinput=0; public String execute() throws Exception{

/* if (getUserinput() >= 10 && getUserinput() <= 80){ return SUCCESS; } else{ return ERROR; } */

return SUCCESS; }

public void setUserinput(int userinput){ this.userinput = userinput; } public int getUserinput(){ return userinput; }}

Page 70: 23277934-STRUTS2-ROSEINDIA

Step 4 : Create the validations.

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

Write validation rule

The following validation rule file defines the rules to check the input range. The int Field Validator checks whether the given integer is within a certain range or not. If an integer is within a certain range then you jumped into the intSuccess.jsp page. Otherwise it displays the given message in the xml file (Number needs in between 10 and 80). The int validator takes the following parameters:

• fieldName - The field name which is to be validated. Required if using Plain-Validator Syntax otherwise not required

• min - This is the minimum value (if none is specified, it will not be checked).

• max - This is the maximum value (if none is specified, it will not be checked).

NumAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators>

<field name="userinput"> <field-validator type="int"> <param name="min">10</param> <param name="max">80</param> <message>Number needs to between ${min} and ${max} </message> </field-validator> </field>

</validators>

When the given number is within 10 and 80 then the intSuccess.jsp page displays the inputted number with "Correct Input Number" message.

intSuccess.jsp

<%@page language="java" %><html>

<head> <title>Correct entry</title></head>

<body><b>Correct Input Number :</b><%=request.getParameter("userinput") %></body>

</html>

Output:

Page 71: 23277934-STRUTS2-ROSEINDIA

When this application executes you get the following:

If you enter the wrong data or text then you get:

When you fill a number '50'

Page 72: 23277934-STRUTS2-ROSEINDIA

Then you get:

Struts 2 RequiredString validator

This section discusses RequiredString validator of Struts 2 framework. RequiredStringValidator checks the String field is not-null and its length is > 0. (i.e. it isn't ""). The "trim" parameter determines the String before performing the length check. If unspecified, the String will be trimmed.

If user does not enter anything in the input filed and submits the forms, required String validator will generate error message. Then the error message is displayed to user.

This example demonstrates how to use Struts 2 RequiredString validation with a simple data entry form where user is prompted to enter his/her user number. Follow the following steps to develop the example application:

Step 1: Create the xml file and add the following xml snippet in the struts.xml file.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC

Page 73: 23277934-STRUTS2-ROSEINDIA

"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default"> <!-- Add actions here -->

<!-- string validation -->

<action name="stringValidation" class="net.roseindia.StringVaLidationAction"> <result name="input">/pages/stringInputForm.jsp</result> <result name="error">/pages/stringInputForm.jsp</result> <result>/pages/stringSuccess.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Step 2 : Create the input form.

stringInputForm.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

<head><title>Input form</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> <s:head/></head>

<body> <s:form method="POST" action="stringValidation"> </td> </tr> <s:textfield label="Enter User Number" name="username" maxlength="10" /> <s:submit /> </s:form>

</body>

</html>

Page 74: 23277934-STRUTS2-ROSEINDIA

Step 3 : Create the Action class.

StringVaLidationAction.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class StringVaLidationAction extends ActionSupport{

private String username;

public String execute() throws Exception{ if (getUsername() != null){ return SUCCESS; } else{ return ERROR; } }

public void setUsername(String username){ this.username = username; } public String getUsername(){ return username; }}

Step 4 : Create the validators.

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

RequiredString validator: RequiredStringValidator checks the String field is not-null and it has a length > 0. (i.e. it isn't ""). The "trim" parameter determines the String before performing the length check. If unspecified, the String will be trimmed. If any string inputted in the text field then you jumped into the stringSuccess.jsp page. Otherwise, it displays the given message in the xml file (User Name is required). The RequiredString validator takes the following parameters:

• fieldName - This is the field name that has to validate. Required if using Plain-Validator Syntax otherwise not required.

• trim - This is the field name of value before validating (default is true).

StringVaLidationAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators>

<field name="username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>User Name is required</message> </field-validator>

Page 75: 23277934-STRUTS2-ROSEINDIA

</field>

</validators>

When any string that have to be inputted by you in the text field then you must have to jump into stringSuccess.jsp page and displays your inputted string with "Welcome to Vinod "message.

stringSuccess.jsp

<%@page language="java" %><html>

<head> <title>Correct entry</title></head>

<body><b>Welcome to </b><%=request.getParameter("username") %>!</body>

</html>

Output:

When this application executes, you get the following:

When you fill the following string as 'Vinod Kumar'

Then you get:

Struts 2 double validator

The Double validator of Struts 2 Framework checks if the given input is double or not. If the input is not double, it generates the error message. Double validator can also be used to check the input range. This example is a demonstration to use double validator check the input range.

Page 76: 23277934-STRUTS2-ROSEINDIA

Follow the steps to develop double range validator example:

Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default"> <!-- Add actions here -->

<!-- double validation -->

<action name="doubleValidation" class="net.roseindia.DoubleVaLidationAction"> <result name="input">/pages/doubleInputForm.jsp</result> <result name="error">/pages/doubleInputForm.jsp</result> <result>/pages/doubleSuccess.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Step 2 : Create the input form.

doubleInputForm.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

<head><title>Input form</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> <s:head/></head>

<body> <s:form method="POST" action="doubleValidation"> </td> </tr> <s:textfield label="Enter Total Percentage Marks" name="percentagemarks"

Page 77: 23277934-STRUTS2-ROSEINDIA

maxlength="10" /> <s:submit /> </s:form>

</body>

</html>

Step 3 : Create the Action class.

DoubleVaLidationAction.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class DoubleVaLidationAction extends ActionSupport{

private double percentagemarks;

public String execute() throws Exception{ return SUCCESS;

/*/*if (getPercentagemarks() > 20.1 && getPercentagemarks() < 50.1){ return SUCCESS; } else{ return ERROR; }

*/ }

public void setPercentagemarks(double percentagemarks){ this.percentagemarks = percentagemarks; } public double getPercentagemarks(){ return percentagemarks; }}

Step 4 : Create the validators.

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

Double validator: This Field Validator checks, if the given number is double and specified within the specified range. If your inputted text is valid or within specified range then you jump into the doubleSuccess.jsp page. Otherwise, it displays the given message in the xml file (Percentage marks need to between 20.1 and 50.1). The double validator takes the following parameters:

• fieldName - This is the field name of validator that have to validate. Required if using int-Validator Syntax otherwise not required

• minInclusive - This is the minimum inclusive value as FloatValue format specified by Java language (if none is specified, it will be checked)

Page 78: 23277934-STRUTS2-ROSEINDIA

• maxInclusive - This is the maximum inclusive value as FloatValue format specified by Java language (if none is specified, it will be checked)

• minExclusive - This is the minimum exclusive value as FloatValue format specified by Java language (if none is specified, it will be checked)

• maxExclusive - This is the maximum exclusive value as FloatValue format specified by Java language (if none is specified, it will be checked)

DoubleVaLidationAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators>

<field name="percentagemarks"> <field-validator type="double"> <param name="minInclusive">20.1</param> <param name="maxInclusive">50.1</param> <message>Percentage marks need to between ${minInclusive} and ${maxInclusive}</message> </field-validator> </field>

</validators>

When any double value is within specified range then you must jump into doubleSuccess.jsp page and it displays your inputted double value with "Aggregate Total Marks: "message.

stringSuccess.jsp

<%@page language="java" %><html>

<head> <title>Correct entry</title></head>

<body><b>Aggregate Total Marks: </b><%=request.getParameter("percentagemarks") %>%</body>

</html>

Output:

When this application executes, you get the following:

Page 79: 23277934-STRUTS2-ROSEINDIA

If you enter the wrong data or text then you get:

When you fill a number '26.105'

Then you get:

Struts 2 Date Validator

The Date validator in the Struts 2 Framework checks whether the supplied date lies within a specific range or not. If the value supplied does not lie in the specified range, it generates an error message.

The error message is supplied between the <message> </message> tag. The following example demonstrates how to use the date validator to check the input range.

Page 80: 23277934-STRUTS2-ROSEINDIA

[ NOTE: If date converter is not specified then XWorkBasicConverter will kick in to do the date conversion, which by default uses the Date.SHORT format (using a programmatically specified locale else falling back to the system default locale).]

Follow the steps to develop the date range validator :

Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default"> <!-- Add actions here -->

<!-- date validation -->

<action name="dateValidation"> <result>/pages/dateInputForm.jsp</result> </action>

<action name="dateValidation1" class="net.roseindia.DateVaLidationAction"> <result name="input">/pages/dateInputForm.jsp</result> <result name="error">/pages/dateInputForm.jsp</result> <result>/pages/dateSuccess.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Step 2 : Create the input jsp form i.e.

dateInputForm.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

<head><title>Input form</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> <s:head/></head>

<body>

Page 81: 23277934-STRUTS2-ROSEINDIA

<s:form method="POST" action="dateValidation1"> </td> </tr> <s:textfield label="Enter Joining Date of Employee" name="joiningdate"/> <s:submit /> </s:form>

</body>

</html>

Step 3 : Create an Action class.

DateVaLidationAction.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.*;import java.util.*;import java.text.*;

public class DateVaLidationAction extends ActionSupport implements Validateable {

private Date joiningdate=null; public void setJoiningdate(Date joiningdate){ this.joiningdate = joiningdate; } public Date getJoiningdate(){ return joiningdate; }}

Step 4 : Create a Date validator with in an xml file:

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

Date validator: This Field Validator checks if the date supplied is within a specific range. If it is valid and lies within the specified range then you are sent to the dateSuccess.jsp page. Otherwise, it displays the message given in the xml file (e.g. Joining date must be supplied between 01/01/1990 and 01/01/2000.). The date validator takes the following parameters:

• fieldName - This is the field name of the validator. - Required if working with Plain Validator Syntax.

• min - This is the min date range. If not specified, it will not be checked.

• max - This is the max date range. If not specified, it will not be checked.

DateVaLidationAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

Page 82: 23277934-STRUTS2-ROSEINDIA

<validators>

<field name="joiningdate"> <field-validator type="date"> <param name="min">01/01/1990</param> <param name="max">01/01/2000</param> <message>Joining date must be supplied between ${min} and ${max}</message> </field-validator> </field>

</validators>

When any date that has to be passed in the text field by the user is correct then dateSuccess.jsp page is displayed as shown below: "Employee Joining Date: 12/11/1998 " message.

dateSuccess.jsp

<%@page language="java" %><html>

<head> <title>Correct entry</title></head>

<body><b>Employee Joining Date: </b><%=request.getParameter("joiningdate") %></body>

</html>

Output:

When this application executes, the following page is recieved:

If you enter the wrong data or text then you get:

If you enter the date below the range:

Page 83: 23277934-STRUTS2-ROSEINDIA

If you enter the date out of the range, then you get the output as:

If you enter the date lying between the specified range:

Then you get the output message as shown:

Struts 2 E-mail Validator

The email validator in Struts 2 Framework checks whether a given String field is empty or not and contains a valid email address or not. If the entered value does not match with the email type then the e-mail validator generates an error message.

The error message is supplied between the <message> </message> tag. The following example demonstrates how to use an email validator to check the entered value.

Follow the steps to develop the email validator example:

Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" />

Page 84: 23277934-STRUTS2-ROSEINDIA

<constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default"> <!-- Add actions here -->

<!-- Email validation -->

<action name="emailValidation"> <result>/pages/emailInputForm.jsp</result> </action>

<action name="emailValidation1" class="net.roseindia.EmailVaLidationAction"> <result name="input">/pages/emailInputForm.jsp</result> <result name="error">/pages/emailInputForm.jsp</result> <result>/pages/emailSuccess.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Step 2 : Create an input jsp form. as shown below:

emailInputForm.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

<head>

<title>Email input form</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> <s:head/></head>

<body> <s:form method="POST" action="emailValidation1"> </td> </tr> <s:textfield label="Enter Email Address" name="myEmail" /> <s:submit /> </s:form>

</body>

</html>

Page 85: 23277934-STRUTS2-ROSEINDIA

Step 3 : Create an Action class.

EmailVaLidationAction.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class EmailVaLidationAction extends ActionSupport {

private String myEmail;

public void setMyEmail(String myEmail){ this.myEmail = myEmail; } public String getMyEmail(){ return myEmail; }}

Step 4 : Create an e-mail validator as:.

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

email validator :This Field Validator checks whether a given String field is empty or not and contains a valid email address or not. If it has valid email type then the user is sent to the emailSuccess.jsp page. Otherwise, it displays the message given in the xml file (e.g. Please enter a valid email.). The email validator takes the following parameters:

• fieldName - This is the field name of validator that validates. It is required only if the user is using Plain-Validator Syntax .

EmailVaLidationAction-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators>

<field name="myEmail"> <field-validator type="email"> <message>Please enter a valid email</message> </field-validator> </field>

</validators>

When the correct email address is entered then the user gets the emailSuccess.jsp page

emailSuccess.jsp

<%@page language="java" %><html>

<head>

Page 86: 23277934-STRUTS2-ROSEINDIA

<title>Correct entry</title></head>

<body><b>Welcome to </b><%=request.getParameter("myEmail") %>!</body>

</html>

Output:

When this application executes the user gets the following output :

If you enter the wrong email address then you get a message as shown:

Again, If you enter the wrong email address then you get:

Again, If you enter the wrong email address then you get:

If you enter the correct email address:

Page 87: 23277934-STRUTS2-ROSEINDIA

Then you get:

Struts 2 Url Validator

The URLValidator of Struts 2 Framework checks whether the String contained within the given field is a valid URL or not. If the entered value is not a valid URL, it generates an error message.

The error message is supplied between the <message> </message> tag. The following example demonstrates how to use the URL validator.

Follow the steps to develop the URL validator example:

Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default"> <!-- Add actions here -->

<!-- Url validation -->

<action name="urlValidation"> <result>/pages/urlInputForm.jsp</result> </action>

<action name="urlValidation1" class="net.roseindia.urlVaLidationAction"> <result name="input">/pages/urlInputForm.jsp</result> <result name="error">/pages/urlInputForm.jsp</result> <result>/pages/urlSuccess.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Step 2 : Create an input jsp form.

urlInputForm.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

Page 88: 23277934-STRUTS2-ROSEINDIA

<html>

<head>

<title>Url input form</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> <s:head/></head>

<body> <s:form method="POST" action="urlValidation1"> </td> </tr> <s:textfield label="Enter Url" name="url" /> <s:submit /> </s:form>

</body>

</html>

Step 3 : Create an Action class.

urlVaLidationAction.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class urlVaLidationAction extends ActionSupport {

private String url;

public void setUrl(String url){ this.url = url; } public String getUrl(){ return url; }}

Step 4 : Create an URL validator as shown:

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

URL validator: This Field Validator checks whether a given field contains a valid URL String or not. If the entered text is valid then you get the urlSuccess.jsp page. Otherwise, it displays the message given in the xml file (like "Please enter a valid URL.").

The URL validator takes the following parameters:

• fieldName - It refers to the field name, the URL validator is validating.It is required if using Plain-Validator Syntax

urlVaLidationAction-validation.xml

Page 89: 23277934-STRUTS2-ROSEINDIA

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators>

<field name="url"> <field-validator type="url"> <message>Please enter a valid url</message> </field-validator> </field>

</validators>

When the correct URL is entered the user gets the urlSuccess.jsp page displaying the entered URL.

urlSuccess.jsp

<%@page language="java" %><html>

<head> <title>Correct entry</title></head>

<body><b>URL = </b><%=request.getParameter("url") %>!</body>

</html>

Output:

When this application executes initially the user gets the following:

If the user enters the wrong URL then he gets:

Again, the user enters the wrong URL then he gets:

Page 90: 23277934-STRUTS2-ROSEINDIA

If the user enters the correct URL as

then he gets a success message as an output:

Validations using Struts 2 Annotations

Validating Struts 2 Login Application using AnnotationsIn this section we are going to validate our login application using Annotations in Action class. Our current login application does not validate the user against the database. Instead login name and passwords are validated against the hardcode values (User: Admin and Password: Admin) in the actions class.

Working of the application

1. Login page is displayed to take the input.

2. User enters user name and password and then clicks on the "Login" button.

3. User validation is done in action class and if user enters Admin/Admin in the user name/password fields, then success page is displayed, Otherwise the error message is displayed on the screen.

Steps to develop the application

Here are simple and easy steps to develop Login page in the using Struts 2 framework.

1. Develop Login FormThe GUI of the application consists of login form (log-in.jsp) and success message page (loginsuccess.jsp).The log-in.jsp is used to display the login page to the user. In our application it is saved in "webapps\struts2tutorial\pages\" folder. Here is the code of log-in.jsp file:

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Login Application!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>

Page 91: 23277934-STRUTS2-ROSEINDIA

</head><body>

<s:form action="AnnotationAction" method="POST" validate="true"><tr><td colspan="2">Login</td>

</tr>

<tr> <td colspan="2"> <s:actionerror /> <s:fielderror /> </td> </tr>

<s:textfield name="username" label="Login name"/><s:password name="password" label="Password"/><s:submit value="Login" align="center"/>

</s:form>

</body>

</html>

1. The code :<s:actionerror /><s:fielderror />displays action errors and field validation errors.

The code <s:form action="AnnotationAction" method="POST" validate="true"> generates the html form for the application.

The code :<s:textfield name="username" label="Login name"/><s:password name="password" label="Password"/>generates Login Name and Password fields.

The submit button is generated through <s:submit value="Login" align="center"/> code.

The loginsuccess.jsp page displays the Login Success message when user is authenticated successfully. Here is the code of loginsuccess.jsp file:

<html>

Page 92: 23277934-STRUTS2-ROSEINDIA

<head>

<title>Login Success</title>

</head>

<body>

<p align="center"><font color="#000080" size="5">Login Successful</font></p>

</body>

</html>

2. Developing Action class (using Annotations to validate Login forms)Now let's develop the action class to handle the login request. The Struts 2 framework provides a base ActionSupport class to implement commonly used interfaces. In our action class (AnnotationAction.java) we have extended ActionSupport class and imported the com.opensymphony.xwork2.validator.annotations package . For validating the login application java script can be added to the jsp page or in action class, but Struts 2 provides another very easy method to validate your form fields using annotations in the action class. Two annotations are needed,1. The @Validation annotation tells Struts that action in this class might need to be validated. 2. The @RequiredStringValidator annotation is used for the text input to hold a singular value. Rest of the care is taken by the framework.

Our "AnnotationAction" class is saved in the "webapps\struts2tutorial\WEB-INF\src\java\net\roseindia" directoy. Here is the code of AnnotationAction.java action class:In this class we will write the code to validate the login page.

AnnotationAction.java

package net.roseindia; import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.validator.annotations.*;

@Validation public class AnnotationAction extends ActionSupport {

private String username = null; private String password = null;

Page 93: 23277934-STRUTS2-ROSEINDIA

@RequiredStringValidator(message="Supply name") public String getUsername() {

return username; }

public void setUsername(String value) {

username = value; } @RequiredStringValidator(message="Supply password")

public String getPassword() { return password; }

public void setPassword(String value) { password = value; }

public String execute() throws Exception { System.out.println("Validating login"); if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){ addActionError("Invalid user name or password! Please try again!"); return ERROR; }else{ return SUCCESS; } }}

1. Configuring action mapping (in struts.xml)Now we will create action mapping in the struts.xml file. Here is the code to be added in the struts.xml:

Page 94: 23277934-STRUTS2-ROSEINDIA

<action name="LoginAnnotation"><result>/pages/log-in.jsp</result></action>

<action name="AnnotationAction" class="net.roseindia.AnnotationAction"><result name="input">/pages/log-in.jsp</result><result name="error">/pages/log-in.jsp</result><result>/pages/loginsuccess.jsp</result></action>

2. In the above mapping the action "LoginAnnotation" is used to display the login page and "AnnotationAction" validates the user using action class (AnnotationAction.java).

3. CSS file (main.css)This css file is used to enhance the presentation of the login form. The main.css is saved into "\webapps\struts2tutorial\css" directory.Here is the code of main.css:

@CHARSET "UTF-8";

body {font: 12px verdana, arial, helvetica, sans-serif;background-color:#FFFFFF;}

table.wwFormTable {font: 12px verdana, arial, helvetica, sans-serif;border-width: 1px;border-color: #030;border-style: solid;color: #242;background-color: #ada;width: 30%;margin-left:35%;margin-right:35%;margin-top:15%;}

table.wwFormTable th {}

table.wwFormTable tr td {background-color: #dfd;margin: 5px;padding: 5px;}

.tdLabel {

Page 95: 23277934-STRUTS2-ROSEINDIA

/*border-width: 1px;border-color: #afa;border-style: solid;*/font-weight: bold;align: top;}

.label {}

.errorMessage {color: red;font-size: 0.8em;}

#headerDiv {border-style: solid;border-width: 1px 1px 0px;border-color: black;padding: 5px;background-color: #7a7;/* height: 22px; */height: 1.8em;/* margin-bottom: 12px; */}

#buttonBar {border-width: 0px 1px 1px;border-style: solid;border-color: black;color: white;margin-bottom: 12px;background-color: #7a7;height: 1.6em;padding: 5px;}

#appName {color: white;font-size: 1.8em;}

#pageTitle {font-size: 1.4em;color: #dfd;clear: none;

Page 96: 23277934-STRUTS2-ROSEINDIA

}

#appName, #pageTitle {float: right;}

#menuContainer {float: left;}

#brandingContainer {float: right:text-align: right;}

Compiling the application

To compile the application go to "\webapps\struts2tutorial\WEB-INF\src" directory and type ant command. The ant tool will compile the application for you.

Adding the link into index.html

Finally we have to add the link in the index.html to access the login form.

<ul><li><a href="roseindia/LoginAnnotation.action">Action Annotation Example</a></li></ul>

Output:

If you click Login button without filling the fields , you will get the output page as :

If you fill only the "Login name" field and click Login button without filling the next fields, you will get the output page as :

Page 97: 23277934-STRUTS2-ROSEINDIA

If you fill the wrong information and click the Login button, you will get the output page as :

If you fill the correct information and click the Login button, you will get the output page as :

Login/Logout With Session

Page 98: 23277934-STRUTS2-ROSEINDIA

In this section, we are going to develop a login/logout application with session. This application checks the user authentication. Whenever you run, it takes a user id and a password (Both the user id and password is "admin") it displays the welcome page, when both fields are correctly filled.

Create an action mapping in the struts.xml file. Here is the code to be added in the struts.xml:

<action name="login" class="net.roseindia.loginAction" > <result name="success" type="dispatcher">/pages/uiTags/Success.jsp</result> <result name="error" type="redirect">/pages/uiTags/Login.jsp</result></action>

<action name="logout" class="net.roseindia.logoutAction" > <result name="success" type="redirect">/pages/uiTags/checkLogin.jsp</result></action>

Develop an action class that handles the login request. The Struts 2 framework provides a base ActionSupport class that implements commonly used framework interfaces. In our action class (loginAction.java) we have extended ActionSupport class.

Here is the code of "loginAction" action class:

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ActionContext;import java.util.*;

public class loginAction extends ActionSupport { private String userId; private String password; public String execute() throws Exception{

if ("admin".equals(userId) && "admin".equals(password)) { Map session = ActionContext.getContext().getSession(); session.put("logged-in","true"); return SUCCESS; } else{ return ERROR; } }

public String logout() throws Exception {

Map session = ActionContext.getContext().getSession(); session.remove("logged-in"); return SUCCESS;

Page 99: 23277934-STRUTS2-ROSEINDIA

}

public String getPassword() { return password; }

public void setPassword(String password) { this.password = password; }

public String getUserId() { return userId; }

public void setUserId(String userId) { this.userId = userId; }}

Download this code.

Again, develop an action class to handle the logout operation. An action class (logoutAction) we have extended ActionSupport class.

Here is the code of logoutAction action class:

package net.roseindia;import javax.servlet.http.HttpSession;import com.opensymphony.xwork2.ActionSupport;import com.opensymphony.xwork2.ActionContext;import java.util.*;

public class logoutAction extends ActionSupport { public String execute() throws Exception { Map session = ActionContext.getContext().getSession(); session.remove("logged-in"); return SUCCESS; }}

Download this code.

Develop Login Form: The GUI of the application consists of login form (Login.jsp). The "Login.jsp" displays the login page to the user.

Here is the code of Login.jsp file:

<%@ taglib prefix="s" uri="/struts-tags" %><%@ page language="java" contentType="text/html"%>

<html> <head> <title>Insert Data here!</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> </head> <body> <s:form action="/roseindia/login.action" method="POST">

Page 100: 23277934-STRUTS2-ROSEINDIA

<s:textfield name="userId" label="Login Id"/><br> <s:password name="password" label="Password"/><br> <s:submit value="Login" align="center"/> </s:form> </body></html>

The "Success.jsp" page displays the Login Success message (Welcome, you have logged-in.) and session (Session Time: Wed Aug 01 11:26:38 GMT+05:30 2007 and Logout ) when user gets successful authentication. If you click the "Logout" then again login page is displayed on the screen.

Here is the code of Success.jsp file:

<%@ taglib prefix="s" uri="/struts-tags" %><%@ page language="java" contentType="text/html" import="java.util.*"%><jsp:include page="/struts2tags/pages/uiTags/loginCheck.jsp" />

<html> <head> <title>Welcome, you have logined!</title> </head> <body> Welcome, you have logined. <br /> <b>Session Time: </b><%=new Date(session.getLastAccessedTime())%> <br /><br /> <a href="<%= request.getContextPath() %>/roseindia/logout.action">Logout</a> <br /> </body></html>

This page logs out the valid user. checkLogin.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><%@ page language="java" contentType="text/html" import="java.util.*"%><html> <head> <title>Check validate!</title> </head> <body> <s:if test="#session.login != 'admin'"> <jsp:forward page="/pages/uiTags/Login.jsp" /> </s:if> </body></html>

Output:

Run this application by getting the login page:

Page 101: 23277934-STRUTS2-ROSEINDIA

Enter the wrong user id and password in the login page

You get the following output:

Page 102: 23277934-STRUTS2-ROSEINDIA

Enter the correct user id and password in the login page:

You get the following output:

Page 103: 23277934-STRUTS2-ROSEINDIA

After clicking the "Logout". You get the following output:

Struts 2 MySQL

In this section, You will learn to connect the MySQL database with the struts 2 application.

Follow the following steps to connect with MySQL database:

Step 1: Create the struts.xml file and add the following xml snippet in the struts.xml file.

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

Page 104: 23277934-STRUTS2-ROSEINDIA

<struts>

<!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /><include file="struts-default.xml"/>

<!-- Add packages here -->

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<!-- inserting data into data base through JDBC -->

<action name="insert"> <result>/pages/insertData.jsp</result> </action>

<action name="insertData" class="net.roseindia.insert"> <result name="error">/pages/insertData.jsp</result> <result>/pages/insertSuccess.jsp</result> </action> </package>

</struts>

Step 2 : Create an input jsp form.

insertData.jsp<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Insert Data Application!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/>

Page 105: 23277934-STRUTS2-ROSEINDIA

</head><body>

<s:form action="insertData" method="POST" validate="true">

<tr><td colspan="2">Please enter</td>

</tr>

<s:actionerror /><s:fielderror />

<s:textfield name="username" label="User Name"/><s:password name="password" label="Password"/><s:submit value="Save" align="center"/>

</s:form>

</body>

</html>

Step 3 : Create an Action class.

First, Establish a connection with the MySQL Database with the help of MySQL driver ("org.gjt.mm.mysql.Driver"). Now, Make an account in the MySQL database to get connected with the database.

After establishing a connection, you can retrieve, insert and update data to the MySQL database table.

The following action class establishes a connection with MySQL database with the help of appropriate type of methods and API interfaces. If connection is established then the entered data is added to the MySQL database table otherwise it displays an error message.

insert.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;import java.sql.*;

/** * <p> Validate a user login. </p> */public class insert extends ActionSupport {

Page 106: 23277934-STRUTS2-ROSEINDIA

public String execute() throws Exception { String url = "jdbc:mysql://localhost:3306/"; String dbName = "taskproject"; String driverName = "org.gjt.mm.mysql.Driver"; String userName = "root"; String password = "root"; Connection con=null; Statement stmt=null; try{ Class.forName(driverName).newInstance(); con=DriverManager.getConnection(url+dbName, userName, password); stmt=con.createStatement(); } catch(Exception e){ System.out.println(e.getMessage()); } String uname=getUsername(); String pws=getPassword(); stmt = con.createStatement(); int val = stmt.executeUpdate("INSERT employee VALUES ('"+uname+"','"+pws+"')"); if(val == 0){ return ERROR; } else{ return SUCCESS; } } // ---- Username property ----

/** * <p>Field to store User username.</p> * <p/> */ private String username = null;

/** * <p>Provide User username.</p> * * @return Returns the User username. */ public String getUsername() { return username; }

Page 107: 23277934-STRUTS2-ROSEINDIA

/** * <p>Store new User username</p> * * @param value The username to set. */ public void setUsername(String value) { username = value; }

// ---- Username property ----

/** * <p>Field to store User password.</p> * <p/> */ private String password = null;

/** * <p>Provide User password.</p> * * @return Returns the User password. */ public String getPassword() { return password; }

/** * <p>Store new User password</p> * * @param value The password to set. */ public void setPassword(String value) { password = value; }

}

Description of the code:

Connection:This is an interface in java.sql package that specifies establishing connection with the specific database like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver):This method is static. It attempts to load the class dynamically and returns class instance and takes string type value (driver) when it matches with the class with given string.

Page 108: 23277934-STRUTS2-ROSEINDIA

DriverManager:It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be registered with this class.

getConnection(String url, String userName, String password):This method establishes a connection to specified database url. It takes three string types of arguments like:

url: - Database url to link with userName: - User name of database password: -Password of database

con.close():This method is used for disconnecting the connection. It frees all the resources occupied by the database.

Step 4 : Create the validator

The validation.xml format is either <ActionClassName>-validation.xml or <ActionClassName>-<ActionAliasName>-validation.xml.

insert-validation.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="username"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>User name is required</message> </field-validator> </field> <field name="password"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>Password is required</message> </field-validator> </field></validators>

When entered the correct data in the text field the user gets the insertSuccess.jsp page displaying the entered data.

insertSuccess.jsp

<html>

<head>

Page 109: 23277934-STRUTS2-ROSEINDIA

<title>Inserted Data List</title>

</head>

<body><b> Inserted Data: </b><b>User name = </b><%=request.getParameter("username") %>!<b>Password = </b><%=request.getParameter("password") %>!</body>

</html>

Output:

When this application executes the user gets the following:

Without filling fields and click "Save" button, you will get the output page as :

If you fill only the "Password" field and click "Save" button without filling the next fields, you will get the output page as :

Page 110: 23277934-STRUTS2-ROSEINDIA

If you fill only the "User Name" field and click "Save" button without filling the next fields, you will get the output page as :

If you fill both field:

Then you get:

Rich Editor Example

In this section, you will learn how to create pagination in struts 2. For creating pagination in your application follows the certain steps:

Download this code

Step 1: Create index.jsp page

Here is the code to be added in the index.jsp:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><title>RoseIndia.Net Struts 2 Tutorial</title></head>

<body><div align="center"><center><table border="0" cellpadding="0" cellspacing="0" width="400">

Page 111: 23277934-STRUTS2-ROSEINDIA

<tr><td><font color="#000080" size="5"><b>RoseIndia.net Struts 2 Tutorials</b><br>&nbsp;&nbsp;&nbsp;</font></td></tr><tr><td><font color="#000080"><b>Select the following links to test theexamples</b></font></td></tr><tr><td>

<ul><li><a href="roseindia/pagination.action">Pagination Example</a></li></ul>

</td></tr><tr><td><font color="#000080">&nbsp;<br>&nbsp;<br>&nbsp;<br>Visit <a href="http://www.roseindia.net">http://www.roseindia.net</a>for latest tutorials</font></td></tr></table></center></div><p align="center">&nbsp;</p></body></html>

Step 2: Create an action mapping in the struts.xml file.

Here is the code to be added in the struts.xml:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">

<struts><!-- Rose India Struts 2 Tutorials --><constant name="struts.enable.DynamicMethodInvocation"

Page 112: 23277934-STRUTS2-ROSEINDIA

value="false" /><constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="pagination"><result>/pages/chatQuestion/pagination.jsp</result></action>

</package>

<!-- Add packages here -->

</struts>

Step 3: Create a JSP page that contains pagination code:

Here is the code to be added in the pagination.jsp:

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

<head><title>Pagination Example</title><s:head theme="ajax" /></head>

<body><s:form><s:textarea name="text" label="Paste your text here" theme="ajax" cssStyle="background-color: #FCFCFC; border: 1px solid #A0A0A0; min-height:500px; max-height:inherit; "/></s:form>

</body></html>

Output:

Page 113: 23277934-STRUTS2-ROSEINDIA

Validate TextArea

In this section, you will learn how to validate your text area in struts 2. A text area contains 1 to 250 characters. It cann't support "null" value.

For validating your text are in your application follows the certain steps:

Step 1: Create index.jsp page

Here is the code to be added in the index.jsp:

<!DOCTYPE HTML

PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><html><head><title>RoseIndia.Net Struts 2 Tutorial</title></head>

<body><div align="center">

Page 114: 23277934-STRUTS2-ROSEINDIA

<center><table border="0" cellpadding="0" cellspacing="0" width="400"><tr><td><font color="#000080" size="5"><b>RoseIndia.net Struts 2 Tutorials</b><br>&nbsp;&nbsp;&nbsp;</font></td></tr><tr><td><font color="#000080"><b>Select the following links to test theexamples</b></font></td></tr><tr><td>

<ul><li><a href="roseindia/characterLimit.action">Characters and limiting Example</a></li></ul>

</td></tr><tr><td><font color="#000080">&nbsp;<br>&nbsp;<br>&nbsp;<br>Visit <a href="http://www.roseindia.net">http://www.roseindia.net</a>for latest tutorials</font></td></tr></table></center></div><p align="center">&nbsp;</p></body></html>

Step 2: Create an action mapping in the struts.xml file.

Here is the code to be added in the struts.xml:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

Page 115: 23277934-STRUTS2-ROSEINDIA

"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts><!-- Rose India Struts 2 Tutorials --><constant name="struts.enable.DynamicMethodInvocation" value="false" /><constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="characterLimit"><result>/pages/chatQuestion/limitedCharacter.jsp</result></action>

<action name="characterLimit1" class="net.roseindia.limitedCharacterAction"><result name="error">/pages/chatQuestion/limitedCharacter.jsp</result><result name="success">/pages/chatQuestion/limitedCharacterSuccess.jsp</result></action>

</package>

<!-- Add packages here -->

</struts>

Step 3: Create a JSP page that contains text area and submit button:

Here is the code to be added in the limitedCharacter.jsp:

<%@ taglib prefix="s" uri="/struts-tags" %>

<html><head><title>Limited Characters in Text Area</title><s:head theme="ajax" /></head><body>

Page 116: 23277934-STRUTS2-ROSEINDIA

<s:form action="characterLimit1" method="POST" validate="true"><s:textarea name="summary1" label="Brief Summary" rows="6" cols="40"/><s:submit value="Save" align="center" /></s:form>

</body></html>

Step 4: Create an action class:

Here is the code to be added in thelimitedCharacterAction.java:

package net.roseindia;

import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;import java.io.PrintStream;import java.util.List;import java.util.*;

public class limitedCharacterAction extends ActionSupport{private String summary1;

public String getSummary1() {return summary1;}

public void setSummary1(String summary1) {this.summary1 = summary1;}

public String execute() throws Exception{String summaryText = getSummary1();long countSummaryText = summaryTextcount(summaryText);System.out.println("countSummaryText:"+countSummaryText);if (countSummaryText >0 && countSummaryText < 250){return SUCCESS;}else{if(getSummary1().equals(""))addFieldError("summary1","Brief Summary is required.");if((countSummaryText > 250))addFieldError("summary1","Brief Summary must be 1 to 250 Charaters");return ERROR;}}

Page 117: 23277934-STRUTS2-ROSEINDIA

private static long summaryTextcount(String str){return str.length();}}

Step 5: Create a JSP page that contains the inputted text in the textarea:

Here is the code to be added in limitedCharacterSuccess.jsp:

<%@ taglib prefix="s" uri="/struts-tags"%>

<html><head><title>Limited Characters in Text Area</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/></head><body>

<b>Brief Summary: </b><s:property value="summary1" /><br></body>

</html>

Output:

When you click the "Save" command button with out any data then you get:

Page 118: 23277934-STRUTS2-ROSEINDIA

If you enter more than 250 characters then you get :

If you enter your text between 1 to 250 characters then you get:

Introduction to Struts 2 Tags

In this section we will introduce you with the tags provided along with Struts 2 framework. It is necessary to understand all the tags provided along with Struts 2 framework. In this page we will have listed all the Struts 2 Tags and in subsequent sections we will provide you the examples of the these tags in detail.

The Struts 2 Tags can be divided into two types:

• Struts Generic TagsThe struts generic tags are used to control the execution flow when pages are rendered. Another use of struts generic tags are data extraction.Further Generic Tags are classified into Control Tags and Data Tags.

Control Tags: The Control Tags are used for flow control, such as if, else and iterate.

Here are the list of Control Tags:

Page 119: 23277934-STRUTS2-ROSEINDIA

* if* elseIf* else* append* generator* iterator* merge* sort* subset

Data Tags: The Data Tags are used for data manipulation or creation, such as bean, push, and i18n.Here are the list of Data Tags:* a* action* bean* date* debug* i18n* include* param* push* set* text* url* property

• Struts UI tagsStruts UI Tags are mainly designed to use the data from your action/value stack or from Data Tags. These tags are used to display the data on the HTML page. The UI tags are driven by templates and themes. Struts UI Tags are of two types Form Tags and Non - Form tags.Form Tags are as follows:* autocompleter* checkbox* checkboxlist* combobox* datetimepicker* doubleselect* head* file* form* hidden* label* optiontransferselect* optgroup* password

Page 120: 23277934-STRUTS2-ROSEINDIA

* radio* reset* select* submit* textarea* textfield* token* updownselect

Non-Form UI Tags are:* actionerror* actionmessage* component* div* fielderror* table* tabbedPanel* tree* treenode

The main difference between Struts Generic Tags and Struts UI Tags are:

• The generic tags simply output some content directly from the tag while the UI tags uses templates and often group the output together with theme

Control Tags-If / Else If / Else

In this section we are going to discuss the various control tags ( The Control Tags are used for flow control such as if, else and iterate.)

'If' tag could be used by itself or with 'Else If' Tag and/or single/multiple 'Else' Tag.

Create a JSP page IfControlTag.jsp.

Set a property 'technologyName' with a value 'Java' as <s:set name="technologyName" value="%{'Java'}"/>

Among if, elseif and else tags only one tag evaluates at a time. Evaluation is based upon the conditions being processed. Evaluated conditions must be of Boolean type. This is illustrated in the following Jsp page.

[Note:

If the condition in <s:if > tag evaluates to 'true' then only this tag is evaluated and others are discarded. As illustrated in the example.

If the condition in <s:if > tag evaluates to 'false' and <s:elseif > tag evaluates to 'true' then the body of the <s:elseif > tag is processed.

If the condition in <s:if > tag and <s:elseif > tags evaluates to 'false' then only the <s:else > tag is processed. ]

IfControlTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

Page 121: 23277934-STRUTS2-ROSEINDIA

<html> <head> <title>Struts 2 Control Tag Example</title> </head> <body> <s:set name="technologyName" value="%{'Java'}"/>

<s:if test="%{#technologyName=='Java'}"> <div><s:property value="%{#technologyName}" /></div> </s:if>

<s:elseif test="%{#technologyName=='Jav'}"> <div><s:property value="%{#technologyName}" /></div> </s:elseif> <s:else> <div>Technology Value is not Java</div> </s:else>

</body></html>

struts.xml: Add the following xml snippet in the struts.xml file.

<action name="doIf" > <result>/pages/genericTags/IfControlTag.jsp</result></action>

index.jsp : Add the following jsp snippet in the index.jsp file.

<ul> <li><a href="roseindia/doIf.action">IF Control Tag Example</a></li></ul>

In the IfControlTag.jsp only <s:if> tag evaluates to true <s:if test="%{#technologyName=='Java'}"> <div><s:property value="%{#technologyName}" /></div> </s:if>

So we get the output equal to Java

JavaAppend Tag (Control Tags) Example

In this section, we are going to describe the append tag. The append tag is a generic tag that is used to merge multiple iterators into one iterator.Append Iterator Tag is used to append iterators to form an appended iterator through which the entries goes from one iterator to another after each respective iterator is exhausted of entries.

Add the following code snippet

into the struts.xml file.

Page 122: 23277934-STRUTS2-ROSEINDIA

struts.xml :

<action name="AppendTag" class="net.roseindia.AppendTag"> <result>/pages/genericTags/AppendTag.jsp</result></action>

Create two lists in the action class and populate them with various items as shown in the "AppendTag" class.

AppendTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class AppendTag extends ActionSupport{ private List myList; private List myList1;

public String execute()throws Exception{ myList = new ArrayList(); myList.add("www.Roseindia.net"); myList.add("Deepak Kumar"); myList.add("Sushil Kumar"); myList.add("Vinod Kumar"); myList.add("Amit Kumar");

myList1 = new ArrayList(); myList1.add("www.javajazzup.com"); myList1.add("Himanshu Raj"); myList1.add("Mr. khan"); myList1.add("John"); myList1.add("Ravi Ranjan"); return SUCCESS; }

public List getMyList(){ return myList; }

public List getMyList1(){ return myList1; }}

Now create a jsp page using <s:append> and <s:iterator> tags as shown in the AppendTag.jsp page. The append tag is used to merge multiple iterators into one iterator. The "id" parameter keeps the resultant appended iterator stored under the stack's context and the "value" parameter is used to get the values contained within the resultant iterator.

AppendTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

Page 123: 23277934-STRUTS2-ROSEINDIA

<html> <head> <title> Append Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc"> Append Tag Example!</span></h1> <s:append id="myAppendList"> <s:param value="%{myList}" /> <s:param value="%{myList1}" /> </s:append> <s:iterator value="%{#myAppendList}"> <s:property /><br> </s:iterator> </body></html>

Output of the Append Tag Example:

Generator Tag (Control Tags) Example

In this section, we are going to describe the generator tag. The generator tag is a generic tag that is used to generate iterators based on different attributes passed. Here we will not pass any attribute.

Add the following code snippet into the struts.xml file.

sturts.xml

Page 124: 23277934-STRUTS2-ROSEINDIA

<action name="GeneratorTag" class="net.roseindia.GeneratorTag"> <result>/pages/genericTags/GeneratorTag.jsp</result></action>

Create an action class as shown: GeneratorTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.util.IteratorGenerator.Converter;

public class GeneratorTag extends ActionSupport { public String excute() throws Exception{ return SUCCESS; }}

Create a jsp page where the generator tag <s:generator> generates a simple iterator based on the val attribute supplied and <s:iterator> tag prints

it out using the <s:property /> tag. The separator attribute is used to separate the val into entries of the iterator.

GeneratorTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title> Generator Tag Example! </title> </head> <body> <h1><span style="background-color: #FFFFcc">Generator Tag Example! </span></h1> <h3><font color="#0000FF"> Generates a Simple Iterator </font></h3> <s:generator val="%{'www.Roseindia.net,Deepak Kumar,Sushil Kumar, Vinod Kumar,Amit Kumar'}" separator=","> <s:iterator> <s:property /><br/> </s:iterator> </s:generator> </body></html>

Output of Generator Tag Example:

Page 125: 23277934-STRUTS2-ROSEINDIA

Generator Tag (Control Tags) Using Count AttributesIn this section, we are going to describe the generator tag using the count attribute.

Add the following code snippet into the struts.xml file.

struts.xml

<action name="GeneratorTagCountAttribute" class="net.roseindia.GeneratorTag"> <result>/pages/genericTags/GeneratorTagCountAttribute.jsp</result></action>

Create an action class as shown:

GeneratorTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.util.IteratorGenerator.Converter;

Page 126: 23277934-STRUTS2-ROSEINDIA

public class GeneratorTag extends ActionSupport { public String excute() throws Exception{ return SUCCESS; }}

Create a jsp page where the generator tag <s:generator> generates an iterator with "count" attribute and <s:iterator> tag prints it out using the <s:property /> tag. The separator attribute separates the val into entries of the iterator.

This generates an iterator, but only 5 entries will be available in the iterator generated, namely 'www.Roseindia.net, Deepak Kumar, Sushil Kumar, Vinod Kumar, Amit Kumar' respectively because count attribute is set to 5.

GeneratorTagCountAttribute.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title> Generator Tag Example! </title> </head> <body> <h1><span style="background-color: #FFFFcc">Generator Tag Example!</span></h1> <h3><font color="#0000FF"> Generates an Iterator With Count Arrtibute</font></h3> <s:generator val="%{'www.Roseindia.net,Deepak Kumar,Sushil Kumar,Vinod Kumar, Amit Kumar, Sanjay, Vijay '}" count="5" separator=","> <s:iterator> <s:property /><br/> </s:iterator> </s:generator> </body></html>

Output of the Generator Tag Example:

Page 127: 23277934-STRUTS2-ROSEINDIA

Generator Tag (Control Tags) Using an Iterator with Id Attributes

n this section, we are going to describe the generator tag using the id attributes.

Add the following code snippet

into the struts.xml file.

struts.xml

<action name="GeneratorTagIdAttribute" class="net.roseindia.GeneratorTag"> <result>/pages/genericTags/GeneratorTagIdAttribute.jsp</result></action>

Create an action class as shown :

GeneratorTag.java

package net.roseindia;

Page 128: 23277934-STRUTS2-ROSEINDIA

import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.util.IteratorGenerator.Converter;

public class GeneratorTag extends ActionSupport { public String excute() throws Exception{ return SUCCESS; }}

Create a jsp page where the generator tag <s:generator> generates an iterator with "id" attribute and <s:iterator> tag prints it out using the <s:property /> tag. The separator attribute separates the val into entries of the iterator.

The scriplet as shown below generates an iterator and put it in the PageContext under the key as specifiedby the id attribute. <% Iterator i = (Iterator) pageContext.getAttribute("myAtt"); while(i.hasNext()) { String s = (String) i.next(); %> <%=s%> <br/> <% } %>

GeneratorTagIdAttribute.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><%@page language="java" import="java.util.*"%>

<html> <head> <title> Generator Tag Example! </title> </head> <body> <h1><span style="background-color: #FFFFcc">Generator Tag Example!</span></h1> <h3><font color="#0000FF"> Generates an Iterator With Id Arrtibute</font></h3> <s:generator val="%{'www.Roseindia.net,Deepak Kumar,Sushil Kumar,Vinod Kumar,Amit Kumar'}" count="4" separator="," id="myAtt" /> <% Iterator i = (Iterator) pageContext.getAttribute("myAtt"); while(i.hasNext()) { String s = (String) i.next(); %> <%=s%> <br/> <% } %> </body></html>

Output of the Generator Tag Example:

Page 129: 23277934-STRUTS2-ROSEINDIA

Iterator Tag (Control Tags) Example

In this section, we are going to describe the Iterator tag. Iterator tag is used to iterate over a value. An iterable value can be either of: java.util.Collection, java.util.Iterator.

Add the following code snippet

into the struts.xml file.

struts.xml

<action name="iteratorTag" class="net.roseindia.iteratorTag"> <result>/pages/genericTags/iteratorTag.jsp</result></action>

Create an action class as shown:

iteratorTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class iteratorTag extends ActionSupport{ private List myList;

Page 130: 23277934-STRUTS2-ROSEINDIA

public String execute()throws Exception{ myList = new ArrayList(); myList.add("Fruits"); myList.add("Apple"); myList.add("Mango"); myList.add("Orange"); myList.add("Pine Apple"); return SUCCESS; }

public List getMyList(){ return myList; }}

The following example retrieves the value of the getMyList() method of the current object on the value stack and uses it to iterate over. The <s:property/> tag prints out the current value of the iterator.

iteratorTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Iterator Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Iterator Tag Example!</span></h1> <s:iterator value="myList"> <s:property /><br> </s:iterator> </body></html>

Output of An Iterator Tag Example:

Page 131: 23277934-STRUTS2-ROSEINDIA

Merge Tag (Control Tags) Example

In this section, we are going to describe the merge tag. The merge tag is a generic tag that is used to merge iterators. The successive call to the merge iterator causes each merge iterator to have a chance to expose its element, subsequently next call allows the next iterator to expose its element. Once the last iterator is done exposing its element, the first iterator is allowed to do so again (unless it is exhausted of entries).

In the current example, 2 lists being merged, each list have 5 entries, the following will be the logic.

1. Display first element of the first list.

2. Display first element of the second list.

3. Display second element of the first list.

4. Display second element of the second list.

5. Display third element of the first list.

6. Display thrid element of the second list.....and so on.

Add the following code snippet into the struts.xml file.

struts.xml

<action name="mergeTag" class="net.roseindia.mergeTag"> <result>/pages/genericTags/mergeTag.jsp</result></action>

Page 132: 23277934-STRUTS2-ROSEINDIA

Create two lists in the action class and populate them with various items as shown in the "mergeTag" class.

mergeTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class mergeTag extends ActionSupport { private List myList; private List myList1;

public String execute() throws Exception{ myList = new ArrayList(); myList.add("www.Roseindia.net"); myList.add("Deepak Kumar"); myList.add("Sushil Kumar"); myList.add("Vinod Kumar"); myList.add("Amit Kumar");

myList1 = new ArrayList(); myList1.add("www.javajazzup.com"); myList1.add("Himanshu Raj"); myList1.add("Mr. khan"); myList1.add("John"); myList1.add("Ravi Ranjan"); return SUCCESS; }

public List getMyList(){ return myList; }

public List getMyList1(){ return myList1; }}

Now create a jsp page using <s:merge> and <s:param value> tags as shown in the mergeTag.jsp page. The merge tag is used to merge iterators. The "id" parameter keeps the resultant iterator stored under in the stack's context and the "value" parameter in the <s:iterator> is used to get the values contained within the respective iterators.

mergeTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Merge Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Merge Tag Example!</span></h1> <s:merge id="mergeId">

Page 133: 23277934-STRUTS2-ROSEINDIA

<s:param value="%{myList}" /> <s:param value="%{myList1}" /> </s:merge> <s:iterator value="%{#mergeId}"> <s:property /><br> </s:iterator> </body></html>

Output of merge Tag:

Subset Tag (Control Tags) Example

In this section, we are going to describe the subset tag. The subset tag is a generic tag that takes an iterator and outputs a subset of it. It delegates to org.apache.struts2.util.SubsetIteratorFilter internally to perform the subset functionality.

Add the following code snippet into the struts.xml file.

struts.xml

<action name="subsetTag" class="net.roseindia.subsetTag"> <result>/pages/genericTags/subsetTag.jsp</result></action>

Page 134: 23277934-STRUTS2-ROSEINDIA

Create a list in the action class and populate it with various items as shown in the "subsetTag" class.

subsetTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class subsetTag extends ActionSupport { private List myList;

public String execute() throws Exception{ myList = new ArrayList(); myList.add(new Integer(50)); myList.add(new Integer(20)); myList.add(new Integer(100)); myList.add(new Integer(85)); myList.add(new Integer(500)); return SUCCESS; }

public List getMyList(){ return myList; }}

Now create a jsp page using <s:subset> and <s:iterator> tags as shown in the subsetTag.jsp page. The subset tag takes an iterator and outputs a subset of it.

subsetTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Subset Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Subset Tag Example!</span></h1> <s:subset source="myList"> <s:iterator> <s:property /><br> </s:iterator> </s:subset> </body></html>

Output of Subset Tag:

Page 135: 23277934-STRUTS2-ROSEINDIA

Subset Tag (Control Tags) Example Using Count

In this section, we are going to describe the subset tag using the count parameter. The count parameter indicates the number of entries to be set in the resulting subset iterator.

Add the following code snippet

into the struts.xml file.

struts.xml

<action name="subsetTagCount" class="net.roseindia.subsetTag"> <result>/pages/genericTags/subsetTagCount.jsp</result></action>

Create a list in the action class and populate it with various items as shown in the "subsetTag" class.

subsetTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class subsetTag extends ActionSupport { private List myList;

public String execute() throws Exception{ myList = new ArrayList();

Page 136: 23277934-STRUTS2-ROSEINDIA

myList.add(new Integer(50)); myList.add(new Integer(20)); myList.add(new Integer(100)); myList.add(new Integer(85)); myList.add(new Integer(500)); return SUCCESS; }

public List getMyList(){ return myList; }}

Now create a jsp page using <s:subset> and <s:iterator> tags as shown in the subsetTag.jsp page. The subset tag takes an iterator and outputs a subset of it. The parameter count is of integer type and it sets the number of entries to be kept in the resulting subset iterator.

subsetTagCount.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Subset Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Subset Tag Example!</span></h1> <s:subset source="myList" count="3"> <s:iterator> <s:property /><br> </s:iterator> </s:subset> </body></html>

Output of Subset Tag:

Output displays only three items because count=3.

Page 137: 23277934-STRUTS2-ROSEINDIA

Subset Tag (Control Tags) Example Using Start

In this section, we are going to describe the subset tag using the start parameter. The start parameter is of integer type. It indicates the starting index (eg. first entry is 0) of entries in the source (needed to make available as the first entry in the resulting subset iterator).

Add the following code snippet into the struts.xml file.

struts.xml

<action name="subsetTagStartWith" class="net.roseindia.subsetTag"> <result>/pages/genericTags/subsetTagStartWith.jsp</result></action>

Create a list in the action class and populate it with various items as shown in "subsetTag" class.

subsetTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class subsetTag extends ActionSupport { private List myList;

public String execute() throws Exception{ myList = new ArrayList(); myList.add(new Integer(50)); myList.add(new Integer(20)); myList.add(new Integer(100)); myList.add(new Integer(85)); myList.add(new Integer(500)); return SUCCESS;

Page 138: 23277934-STRUTS2-ROSEINDIA

}

public List getMyList(){ return myList; }}

Now create a jsp page using <s:subset> and <s:iterator> tags as shown in the subsetTag.jsp page. The subset tag takes an iterator and outputs a subset of it. The parameter start is of integer type and it indicates the starting index (eg. first entry is 0) of entries in the source (needed to make available as the first entry in the resulting subset iterator).

subsetTagStartWith.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Subset Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Subset Tag Example!</span></h1> <s:subset source="myList" count="3" start="2"> <s:iterator> <s:property /><br> </s:iterator> </s:subset> </body></html>

Output of Subset Tag:Here the items displayed are 100, 85, 500. Items displayed starts from 2nd index of the List.

Action Tag (Data Tag) Example

Page 139: 23277934-STRUTS2-ROSEINDIA

In this section, we are going to describe the action tag. The action tag is a generic tag that is used to call actions directly from a JSP page by specifying the action name and an optional namespace. The body content of the tag is used to render the results from the Action. Any result processor defined for this action in struts.xml will be ignored, unless the executeResult parameter is specified.

Add the following code snippet into the struts.xml file.

struts.xml

<action name="actionTag" class="net.roseindia.actionTag"> <result name="success">/pages/genericTags/success.jsp</result></action>

Create an action class as shown below:

actionTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class actionTag extends ActionSupport { public String execute() throws Exception{ return SUCCESS; }}

Now create a jsp page using <s:action> tag as shown in the success.jsp page. The action tag is used to call actions directly from a JSP page by specifying the action name and an optional namespace.

success.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Action Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Action Tag (Data Tags) Example!</span></h1> <s:action name="success"> <b><i>The action tag will execute the result and include it in this page.</i></b></div> </s:action> </body></html>

Output of the success.jsp

Page 140: 23277934-STRUTS2-ROSEINDIA

Bean Tag (Data Tag) Example

In this section, we are going to describe the Bean Tag. The Bean tag is a generic tag that is used to instantiates a class that confirms to the JavaBeans specification. This tag has a body which can contain a number of Param elements to set any mutator methods on that class.

If the id attribute is set on the BeanTag, it will place the instantiated bean into the stack's Context.

Add the following code snippet into the struts.xml file.

struts.xml

<action name="beanTag" class="net.roseindia.beanTag"> <result name="success">/pages/genericTags/beanTag.jsp</result></action>

Create an action class as shown below:

beanTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class beanTag extends ActionSupport { public String execute() throws Exception{ return SUCCESS; }}

create a simple java bean as shown:

companyName.java

Page 141: 23277934-STRUTS2-ROSEINDIA

package net.roseindia;

public class companyName { private String name;

public void setName(String name){ this.name =name ; }

public String getName(){ return name; }}

Now create a jsp page using <s:bean> and <s:param> tags as shown in the beanTag.jsp page. The bean tag instantiates the "net.roseindia.companyName" class, it confirms to the JavaBeans specification. The id attribute is set on the BeanTag, it places the instantiated bean into the stack's Context. The body of <s:bean> tag contains a param element

<s:param name="name">RoseIndia</s:param> which is used to set the value for the setName() method of the "companyName" class and <s:property value="%{name}" /> retrieves that value by calling the getName() method.

beanTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Bean Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Bean Tag (Data Tags) Example!</span></h1> <s:bean name="net.roseindia.companyName" id="uid"> <s:param name="name">RoseIndia</s:param> <s:property value="%{name}" /><br> </s:bean> </body></html>

Output of the beanTag.jsp

Page 142: 23277934-STRUTS2-ROSEINDIA

Date Tag (Data Tag) Example

In this section, we are going to describe the Date tag. The date tag allows to format a Date in a quick and easy way. User can specify a custom format (eg. "dd/MM/yyyy hh:mm"), can generate easy readable notations (like "in 2 hours, 14 minutes"), or can just fall back on a predefined format with key 'struts.date.format' in the properties file.

If that key is not defined, it will finally fall back to the default DateFormat.MEDIUM formatting.

Note: If the requested Date object isn't found on the stack, a blank will be returned.

Configurable attributes are :-

1. name

2. nice

3. format

Add the following code snippet into the "struts.xml" file.struts.xml

<action name="dateTag" class="net.roseindia.dateTag"> <result name="success">/pages/genericTags/dateTag.jsp</result></action>

Create an action class as shown below:dateTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class dateTag extends ActionSupport { private Date currentDate; public String execute() throws Exception{ setCurrentDate(new Date()); return SUCCESS; }

Page 143: 23277934-STRUTS2-ROSEINDIA

public void setCurrentDate(Date date){ this.currentDate = date; } public Date getCurrentDate(){ return currentDate; }}

Now create a jsp page using <s:date> tag as shown in the success.jsp page.

The <s:date name="currentDate" format="dd/MM/yyyy" /> date tag formats a Date in a quick and easy way. Here the "format" parameter specify a custom format (eg. "dd/MM/yyyy hh:mm") to follow.

The nice parameter is of Boolean type which decides whether to print out the date nicely or not. By Default it is kept false which prints out date nicely i.e. <s:date name="currentDate" nice="false" /> tag formats a date and similarly <s:date name="currentDate" nice="true" /> does not format a date, it is illustrated in our current jsp page.

dateTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Date Tag (Data Tag) Example!</title> </head> <body> <h1><font color="#000080">Current Date Format</font></h1> <table border="1" width="35%" bgcolor="ffffcc"> <tr> <td width="50%"><b><font color="#000080">Date Format</font></b></td> <td width="50%"><b><font color="#000080">Date</font></b></td> </tr> <tr> <td width="50%">Day/Month/Year</td> <td width="50%"><s:date name="currentDate" format="dd/MM/yyyy" /></td> </tr> <tr> <td width="50%">Month/Day/Year</td> <td width="50%"><s:date name="currentDate" format="MM/dd/yyyy" /></td> </tr> <tr> <td width="50%">Month/Day/Year</td> <td width="50%"><s:date name="currentDate" format="MM/dd/yy" /></td> </tr> <tr> <td width="50%">Month/Day/Year Hour<B>:</B>Minute</td> <td width="50%"><s:date name="currentDate" format="MM/dd/yy hh:mm" /></td> </tr> <tr> <td width="50%">Month/Day/Year Hour<B>:</B>Minute<B>:</B>Second</td> <td width="50%"><s:date name="currentDate" format="MM/dd/yy hh:mm:s

Page 144: 23277934-STRUTS2-ROSEINDIA

s" /></td> </tr> <tr> <td width="50%">Nice Date (Current Date & Time)</td> <td width="50%"><s:date name="currentDate" nice="false" /></td> </tr> <tr> <td width="50%">Nice Date</td> <td width="50%"><s:date name="currentDate" nice="true" /></td> </tr> </table> </body></html>

Output of the dateTag.jsp :

Include Tag (Data Tag) Example

In this section, we are going to describe the include tag. The include tag is a generic tag that is used to include a servlet's output (result of servlet or a JSP page) to the current page.

Page 145: 23277934-STRUTS2-ROSEINDIA

Add the following code snippet into the struts.xml file.struts.xml

<action name="includeTag" class="net.roseindia.includeTag"> <result name="success">/pages/genericTags/includeTag.jsp</result></action>

Create an action class as shown below: includeTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class includeTag extends ActionSupport { private Date myBirthday; public String execute() throws Exception{ setMyBirthday(new Date("Jan 12, 1984 11:21:30 AM")); return SUCCESS; } public Date getMyBirthday(){ return myBirthday; }}

Create a simple jsp (myBirthday.jsp) that we want to include in our main jsp page ie..includeTag.jsp.myBirthday.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Include Tag (Data Tag) Example!</title> </head> <body> <b><font color="#000080">My Birth Day (Date Format)</font></b> <table border="1" width="35%" bgcolor="ffffcc"> <tr> <td width="50%"><b><font color="#000080">Date Format</font></b></td> <td width="50%"><b><font color="#000080">Date</font></b></td> </tr> <tr> <td width="50%">Day/Month/Year</td> <td width="50%"><s:date name="myBirthday" format="dd/MM/yyyy" /></td> </tr> <tr> <td width="50%">Month/Day/Year</td> <td width="50%"><s:date name="myBirthday" format="MM/dd/yyyy" /></td> </tr>

Page 146: 23277934-STRUTS2-ROSEINDIA

<tr> <td width="50%">Month/Day/Year</td> <td width="50%"><s:date name="myBirthday" format="MM/dd/yy" /></td> </tr> <tr> <td width="50%">Month/Day/Year Hour<B>:</B>Minute</td> <td width="50%"><s:date name="myBirthday" format="MM/dd/yy hh:mm" /></td> </tr> <tr> <td width="50%">Month/Day/Year Hour<B>:</B>Minute<B>:</B>Second</td> <td width="50%"><s:date name="myBirthday" format="MM/dd/yy hh:mm:ss" /></td> </tr> <tr> <td width="50%">Nice Date (Current Date & Time)</td> <td width="50%"><s:date name="myBirthday" nice="false" /></td> </tr> </table> </body></html>

Now create a jsp page using <s:include> tag as shown in the includeTag.jsp page. The <s:include value="myBirthday.jsp" /> tag includes another jsp using the value parameter

includeTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Include Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Include Tag (Data Tags) Example!</span></h1> <s:include value="myBirthday.jsp" /> </body></html>

Output of the includeTag.jsp :

Page 147: 23277934-STRUTS2-ROSEINDIA

Param Tag (Data Tag) Example

In this section, we are going to describe the param tag. The param tag is a generic tag that is used to parameterize other tags. For example the include tag and bean tag. The parameters can be added with or without a name as a key.

The param tag has the following two parameters.

1. name (String) - the name of the parameter

2. value (Object) - the value of the parameter

Note: When you declare the param tag, the value can be defined in either a value attribute or as text between the start and end tag. Struts behaves a bit different according to these two situations.

Case 1. <param name="empname">Amit</param> Here the value would be evaluated to the stack as a java.lang.String object. Case 2. <param name="empname" value="Vinod"/> Here the value would be evaluated to the stack as a java.lang.Object object.

Add the following code snippet into the struts.xml file.

struts.xml

<action name="paramTag">

Page 148: 23277934-STRUTS2-ROSEINDIA

<result>/pages/genericTags/paramTag.jsp</result></action>

Now create a jsp page to see the working of the param tags.

paramTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Param Tag (Data Tag) Example</title> </head> <body> <h1><span style="background-color: #FFFFcc">Param Tag (Data Tags) Example!</span></h1> <ui:component> <ui:param name="empname">Vinod</ui:param><br> <ui:param name="empname">Amit</ui:param><br> <ui:param name="empname">Sushil</ui:param> </ui:component> </body></html>

Output of paramTag.jsp:

Set Tag (Data Tag) Example

In this section, we are going to describe the Set tag. The set tag is a generic tag that is used to assign a value to a variable in a specified scope. It is useful when you wish to assign a variable to a complex expression and then simply reference that variable each time rather than the complex expression.

Add the following code snippet into the struts.xml file.

struts.xml

Page 149: 23277934-STRUTS2-ROSEINDIA

<action name="setTag"> <result>/pages/genericTags/setTag.jsp</result></action>

Now create a jsp page using <s:set> tag as shown in the setTag.jsp page. The set tag is used to assign a value to a variable in a specified scope. The parameters name and value in the tag <s:set name="technologyName" value="%{'Java'}"/> acts as the name-value pair. Here we set the parameters as name="technologyName" value="Java".

setTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Set Tag (Data Tag) Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Set Tag (Data Tags) Example!</span></h1> <s:set name="technologyName" value="%{'Java'}"/> Technology Name: <s:property value="#technologyName"/> </body></html>

Output of the setTag.jsp:

Text Tag (Data Tag) Example

In this section, we are going to describe the text tag. The text tag is a generic tag that is used to render a I18n text message. Follow one of the three steps:

1. Keep the message to be displayed in a resource bundle with the same name as the action that it is associated with ie. create a properties file in the same package as your Java class with the same name as your class, but with .properties extension.

2. If the property file does-not work or the message is not found in the resource bundle, then the body of the tag will be used as default message.

Page 150: 23277934-STRUTS2-ROSEINDIA

3. If there is no body, then the name of the message will be used.

Add the following code snippet into the struts.xml file.

struts.xml

<action name="textTag" class="net.roseindia.textTag"> <result>/pages/genericTags/textTag.jsp</result></action>

Create an action class as shown below:textTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class textTag extends ActionSupport {

public String execute() throws Exception{ return SUCCESS; }}

Create a property file in the same package where your Java program file (textTag.java) is saved with the name as package.properties.package.properties

webname1 = http://www.RoseIndia.netwebname2 = http://www.javajazzup.comwebname3 = http://www.newstrackindia.com

Now create a jsp page to see the working of the text tags.

The first three tags <s:text name="webname1">,<s:text name="webname2"> and <s:text name="webname3"> uses the package.properties file to display the text message.

The next tag <s:text name="empname">Vinod, Amit, Sushil, .......</s:text> uses the body of the tag as a default message.

The last tag <s:text name="empname"></s:text> does not have access to the package.properties files nor does it have a body so it uses name of the message to display.

textTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Text Tag (Data Tag) Example!</title>

Page 151: 23277934-STRUTS2-ROSEINDIA

</head> <body> <h1><span style="background-color: #FFFFcc">Text Tag (Data Tags) Example!</span></h1> <s:text name="webname1"></s:text><br> <s:text name="webname2"></s:text><br> <s:text name="webname3"></s:text><br> <s:text name="empname">Vinod, Amit, Sushil, .......</s:text><br> <s:text name="empname"></s:text>

</body></html>

Output of the textTag.jsp:

Property Tag (Data Tag) Example

In this section, we are going to describe the property tag. The property tag is a generic tag that is used to get the property of a value, which will default to the top of the stack if none is specified.

Add the following code snippet into the struts.xml file.

struts.xml

<action name="propertyTag" class="net.roseindia.propertyTag"> <result>/pages/genericTags/propertyTag.jsp</result></action>

Create an action class as shown:

Page 152: 23277934-STRUTS2-ROSEINDIA

propertyTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class propertyTag extends ActionSupport { public String execute() throws Exception{ return SUCCESS; }}

Create a bean class "companyName" as shown:

companyName.java

package net.roseindia;

public class companyName { private String name;

public void setName(String name){ this.name =name ; }

public String getName(){ return name; }}

Create a jsp using the tags.

<s:property value="%{name}" /> it prints the result of myBean's getMyBeanProperty() method.

<s:property value="name" default="Default Value" /> it prints the result of companyName's getName() method and if it is null, print 'a default value' instead.

propertyTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Property Tag (Data Tag) Example</title> </head> <body> <h1><span style="background-color: #FFFFcc">Property Tag (Data Tags) Example!</span></h1> <!-- Example to pick the value through bean class --> <s:bean name="net.roseindia.companyName" id="uid"> <s:param name="name">RoseIndia</s:param> <s:property value="%{name}" /><br> </s:bean> <!-- Default value --> <s:property value="name" default="Default Value" /> </body></html>

Page 153: 23277934-STRUTS2-ROSEINDIA

Output of the propertyTag.jsp:

Struts 2 Tags (UI Tags) Examples

Form Tags

1. Auto Completer Example In this section, we are going to describe the autocompleter tag. The autocompleter tag always displays a dropdown list with the options that have at least a partial match with entered text in the textbox. If the user clicks on the dropdown button then all options shown in the dropdown list.

2. Checkbox Tag (Form Tag) Example In this section, we are going to describe the checkbox tag. The checkbox tag is a UI tag that is used to render an HTML input element of type checkbox, populated by the specified property from the ValueStack.

3. Checkboxlist Tag (Form Tag) Example In this section, we are going to describe the checkboxlist tag. The checkboxlist tag is a UI tag that creates a series of checkboxes from a list. Setup is like <s:select /> or <s:radio />, but creates checkbox tags.

4. Combobox Tag (Form Tag) Example In this section, we are going to describe the combobox tag. The combo box is basically an HTML INPUT of type text and HTML SELECT grouped together to give you a combo box functionality.

5. Datetimepicker Tag (Form Tag) Example In this section, we are going to describe the datetimepicker tag. The datetimepicker tag is a UI tag that is used to render a date/time picker in a dropdown container.

Page 154: 23277934-STRUTS2-ROSEINDIA

6. Doubleselect Tag (Form Tag) Example In this section, we are going to describe the doubleselect tag. The doubleselect tag is a UI tag that renders two HTML select elements with second one changing displayed values depending on selected entry of first one.

7. File Tag (Form Tag) Example In this section, we are going to describe the file tag. The file tag is a UI tag that renders an HTML file input element achieved through browsing.

8. Form Tag Example In this section, we are going to describe the form tag. The form tag is a UI tag that renders HTML an input form.

9. Label Tag (Form Tag) Example In this section, we are going to describe the label tag. The label tag is a UI tag that is used to render an HTML LABEL that allow to output label:name type of combinations that has the same format treatment as the rest of UI controls.

10.Optiontransferselect Tag (Form Tag) Example In this section, we are going to describe the Optiontransferselect tag. The Optiontransferselect tag is a UI tag that create an option transfer select component.

11.Optgroup Tag (Form Tag) Example In this section, we are going to describe the optgroup tag. The optgroup tag is a UI tag that creates an optgroup component which needs to resides within a select tag <s:select>.

12.Password Tag (Form Tag) Example In this section, we are going to describe the password tag. The password tag is a UI tag that renders an HTML input tag of type password.

13.Radio Tag (Form Tag) Example In this section, we are going to describe the radio tag. The radio tag is a UI tag that renders a radio button input field.

14.Reset Tag (Form Tag) Example In this section, we are going to describe the reset tag. The reset tag is a UI tag that is used together with the form tag to provide form resetting.

15.Select Tag (Form Tag) Example In this section, we are going to describe the select tag. The select tag is a UI tag that is used to render a HTML input tag of type select.

Page 155: 23277934-STRUTS2-ROSEINDIA

16.Submit Tag (Form Tag) Example In this section, we are going to describe the submit tag. The submit tag is a UI tag that is used to render a submit button. The submit tag is used together with the form tag to provide asynchronous form submissions.

17.Textarea Tag (Form Tag) Example In this section, we are going to describe the textarea tag. The textarea tag is a UI tag that is used to render HTML textarea.

18.Textfield Tag (Form Tag) Example In this section, we are going to describe the textfield tag. The textfield tag is a UI tag that is used to render an HTML input field of type text.

19.Updownselect Tag (Form Tag) Example In this section, we are going to describe the updownselect tag. The updownselect tag is a UI tag that creates a select component with buttons to move up and down the elements in the select component.

Non-Form UI Tags

1. Actionerror and Actionmessage Tags (Non-Form UI Tags) Example In this section, we are going to describe the actionerror and actionmessage tags. The actionerror tag is a UI tag that renders action errors(in the jsp pages.) if they exists while the actionmessage tag renders action messages if they exists.

2. Fielderror Tag (Non-Form UI Tags) Example In this section, we are going to describe the fielderror tags. The fielderror tag is a UI tag that renders field errors if they exists.

3. TabbedPanel (Ajax Tag) Example In this section, you will learn about the tabbedPanel tag. This is an Ajax component, where each tab is either a local content or a remote content (refreshed each time when user selects that tab).

4. tree and treenode (Ajax Tag) tags Example In this section, you will learn about the tree and treenode tags. These both work with the Ajax support.

5. Div (Ajax Tag) tag Example In this section, you will learn about the div tag. The div tag is an Ajax component that is used with Ajax refreshes the contents of a particular section without refreshing the entire page.

Auto Completer Example

In this section, we are going to describe the autocompleter tag. The autocompleter tag always displays a dropdown list with the options that have at least a partial match with entered text in

Page 156: 23277934-STRUTS2-ROSEINDIA

the textbox. If the user clicks on the dropdown button then all options shown in the dropdown list. The autocompleter tag generates two input fields. First is "text", whose name is specified with the "name" attribute and another one is "hidden" whose name is "$(name). Key", where ${name} is the value in the "name" attribute.

The autocompleter tag loads its options asynchronously when the page loads suggested options based on the text entered by you in textbox. If the autoComplete attribute is set to 'true' (By defalut 'false') then it makes suggestions in the textbox.

[Note: When we use the "simple" theme, the autocompleter can be used like the ComboBox. When used on the "ajax" theme, the list can be retrieved from an action.]

Add the following code snippet into the struts.xml file.

<action name="autocompleter" class="net.roseindia.autocompleter"> <result>/pages/autocompleter.jsp</result></action>

Create a list in the action class and populate them with various states name of U.S. as shown in the "autocompleter" class.

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class autocompleter extends ActionSupport{ private List state; public String execute() throws Exception{ state = new ArrayList(); state.add("Alabama"); state.add("Alaska"); state.add("Arizona"); state.add("Arkansas"); state.add("California"); state.add("Colorado"); state.add("Connecticut"); state.add("Delaware"); state.add("District of Columbia"); state.add("Florida"); state.add("Georgia"); state.add("Hawaii"); state.add("Idaho"); state.add("Illinois"); state.add("Indiana"); state.add("Iowa"); state.add("Kansas"); state.add("Kentucky"); state.add("Louisiana"); state.add("Maine"); state.add("Maryland"); state.add("Massachusetts"); state.add("Michigan"); state.add("Minnesota"); state.add("Mississippi");

Page 157: 23277934-STRUTS2-ROSEINDIA

state.add("Missouri"); state.add("Montana"); state.add("Nebraska"); state.add("Nevada"); state.add("New Hampshire"); state.add("New Jersey"); state.add("New Mexico"); state.add("New York"); state.add("North Carolina "); state.add("North Dakota"); state.add("Ohio"); state.add("Oklahoma"); state.add("Oregon"); state.add("Pennsylvania"); state.add("Rhode Island"); state.add("South Carolina "); state.add("South Dakota"); state.add("Tennessee"); state.add("Texas"); state.add("Utah"); state.add("Vermont"); state.add("Virginia"); state.add("Washington"); state.add("West Virginia "); state.add("Wisconsin"); state.add("Wyoming"); return SUCCESS; } public List getState(){ return state; }}

<s:autocompleter theme="simple" list="state" StateName/> it creates a autocompleter list with the name of U.S. states.

autocompleter.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Struts 2 Autocompleter Example!</title> <s:head theme="ajax" /> </head> <body> <h1>Struts 2 Autocompleter Example!</h1> <s:label name="stateName" value="Select State Name:" /> <s:autocompleter theme="simple" list="state" name="StateName"/> </body></html>

Output of the autocompleter.jsp :

Page 158: 23277934-STRUTS2-ROSEINDIA

When you enter the 'c' letter in the textbox. You get the following names:

Checkbox Tag (Form Tag) Example

In this section, we are going to describe the checkbox tag. The checkbox tag is a UI tag that is used to render an HTML input element of type checkbox, populated by the specified property from the ValueStack.

Add the following code snippet into the struts.xml file.struts.xml

<action name="checkboxTag"> <result>/pages/uiTags/checkboxTag.jsp</result></action>

Create a jsp using the tag <s:checkbox> It renders an HTML input element of type chechbox.

checkboxTag.jsp

Page 159: 23277934-STRUTS2-ROSEINDIA

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Checkbox (Form Tag) Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Checkbox Tag Example!</span></h1> <b>Sex</b><br> <s:checkbox label="Male" name="male" value="true" /><br> <s:checkbox label="Female" name="male" /> </body></html>

Output of the checkboxTag.jsp :

Checkboxlist Tag (Form Tag) Example

In this section, we are going to describe the checkboxlist tag. The checkboxlist tag is a UI tag that creates a series of checkboxes from a list. Setup is like <s:select /> or <s:radio />, but creates checkbox tags.

Add the following code snippet into the struts.xml file.struts.xml

<action name="checkboxlistTag" class="net.roseindia.checkboxlistTag"> <result>/pages/uiTags/checkboxlistTag.jsp</result></action>

Create two lists in the action class and populate them with various items as shown in the "checkboxlistTag" class.

checkboxlistTag.java

Page 160: 23277934-STRUTS2-ROSEINDIA

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class checkboxlistTag extends ActionSupport{ private List fruits; private List animals; public String execute()throws Exception{ fruits = new ArrayList(); fruits.add("Apple"); fruits.add("Mango"); fruits.add("Orange"); fruits.add("Pine Apple");

animals = new ArrayList(); animals.add("Dog"); animals.add("Elephant"); animals.add("Ox"); animals.add("Fox"); return SUCCESS;

}

public List getFruits(){ return fruits; }

public List getAnimals(){ return animals; }}

Create a jsp using the tags

<s:checkboxlist name="Fruits-name" list="fruits" /> it prints a checboxlist with name Fruits and Creates a series of checkboxes from fruits list of the action class "checkboxlistTag". <s:checkboxlist name="Animals-name" list="animals" /> it prints a checboxlist with name Animals and Creates a series of checkboxes from animals list of the action class "checkboxlistTag".

checkboxlistTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Checkboxlist (Form Tag) Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Checkboxlist Tag Example!</span></h1> <b>Fruits</b><br> <s:checkboxlist name="Fruits-name" list="fruits" /><br> <b>Animals</b><br>

Page 161: 23277934-STRUTS2-ROSEINDIA

<s:checkboxlist name="Animals-name" list="animals" /><br> </body></html>

Output of the checkboxlistTag.jsp:

Combobox Tag (Form Tag) Example

In this section, we are going to describe the combobox tag. The combo box is basically an HTML INPUT of type text and HTML SELECT grouped together to give you a combo box functionality. You can place text in the INPUT control by using the SELECT control or type it in directly in the text field

.

Add the following code snippet into the struts.xml file.struts.xml

<action name="comboboxTag" class="net.roseindia.comboboxTag"> <result>/pages/uiTags/comboboxTag.jsp</result></action>

Create a list in the action class and populate it with various items as shown in the " comboboxTag" class.

comboboxTag.java

package net.roseindia;i mport com.opensymphony.xwork2.ActionSupport;import java.util.*;

Page 162: 23277934-STRUTS2-ROSEINDIA

public class comboboxTag extends ActionSupport{ private List fruits; public String execute()throws Exception{ fruits = new ArrayList(); fruits.add("Apple"); fruits.add("Mango"); fruits.add("Orange"); fruits.add("Pine Apple"); return SUCCESS;

}

public List getFruits(){ return fruits; }}

Create a jsp using the tags <s:combobox> The tag <s:combobox label="Colors Name" name="colorNames" headerValue="--- Please Select ---" headerKey="1" list="{'Black','Green','White','Yellow','Red','Pink'}" /> prints a combobox with name color Name and an HTML INPUT of type text and HTML SELECT grouped together created using the list.

The tag <s:checkboxlist name="Animals-name" list="animals" /> prints a combobox with name Fruits Name and an HTML INPUT of type text and HTML SELECT grouped together created using the "fruits" list of the action class "checkboxlistTag".

comboboxTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Combobox (Form Tag) Tag Example!</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> </head> <body> <h1><span style="background-color: #FFFFcc">Combobox Tag Example!</span></h1> <s:form> <s:combobox label="Colors Name" name="colorNames" headerValue="--- Please Select ---" headerKey="1" list="{'Black','Green','White','Yellow', 'Red','Pink'}" /><br> <!-- Use array list --><br> <s:combobox label="Fruits Name" name="fruitsNames" headerValue="--- Please Select ---" headerKey="1" list="fruits" /> </s:form>

Page 163: 23277934-STRUTS2-ROSEINDIA

</body></html>

Output of the comboboxTag.jsp:

Datetimepicker Tag (Form Tag) Example

In this section, we are going to describe the datetimepicker tag. The datetimepicker tag is a UI tag that is used to render a date/time picker in a dropdown container. A stand-alone DateTimePicker widget

that makes it easy to select a date/time or increment by week, month, and/or year.

It is possible to customize the user-visible formatting with either the 'formatLength' (long, short, medium or full) or 'displayFormat' attributes. By default current locale will be used.

Add the following code snippet into the struts.xml file.struts.xml

<action name="datetimepickerTag" class="net.roseindia.includeTag"> <result>/pages/uiTags/datetimepickerTag.jsp</r

Page 164: 23277934-STRUTS2-ROSEINDIA

esult></action>

Create an action class as shown:

includeTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class includeTag extends ActionSupport { private Date myBirthday; public String execute() throws Exception{ setMyBirthday(new Date("Jan 12, 1984 11:21:30 AM")); return SUCCESS; } public void setMyBirthday(Date date){ this.myBirthday = date; } public Date getMyBirthday(){ return myBirthday; }}

Create a jsp using the tag <s:datetimepicker> This tag renders a date/time picker in a dropdown container.

The tag <s:datetimepicker name="myBirthday" label="My Birth Day (dd-MM-yyyy)" displayFormat="dd-MM-yyyy" /> picks the data from the action class "includeTag" using the parameter name="myBirthday" using the display format as displayFormat="dd-MM-yyyy".

datetimepickerTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Datetimepicker (Form Tag) Tag Example!</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>

<s:head theme="ajax" /> </head> <body> <h1><span style="background-color: #FFFFcc">Datetimepicker Tag Example!</span></h1> <s:datetimepicker name="myBirthday" label="My Birth Day (dd-MM-yyyy)" displayFormat="dd-MM-yyyy" /> </body></html>

Output of the datetimepickerTag.jsp:

Page 165: 23277934-STRUTS2-ROSEINDIA

Doubleselect Tag (Form Tag) Example

In this section, we are going to describe the doubleselect tag. The doubleselect tag is a UI tag that renders two HTML select elements with second one changing displayed values depending on selected entry of first one.

Add the following code snippet into the struts.xml file.struts.xml

<action name="doubleselectTag"> <result>/pages/uiTags/doubleselectTag.jsp</result></action>

Create a jsp using the tag <s:doubleselect> that renders two HTML select elements with second one changing displayed values depending on selected entry of first one. This tag contains various parameters:

The headerKey parameter sets the header key of the second list. Must not be empty. In our case we have set it to"1"The headerValue parameter sets the header value of the second list. In our case we have set it to "--- Please Select ---"The doubleName parameter sets the name for complete component. In our case we have set it as

Page 166: 23277934-STRUTS2-ROSEINDIA

: doubleName="dishes" The doubleList sets the second iterable source to populate from. In our case we have set it as : doubleList="top == 'Color' ? {'Black','Green','White', 'Yellow','Red','Pink'} : { 'Apple','Banana','Grapes','Mango'}"

doubleselectTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Doubleselect Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Doubleselect Tag Example!</span></h1> <s:form> <s:doubleselect label="Select Item" headerValue="--- Please Select ---" headerKey="1" list="{'Color','Fruits'}" doubleName="dishes" doubleList="top == 'Color' ? {'Black','Green','White', 'Yellow','Red','Pink'} : { 'Apple','Banana','Grapes','Mango'}" /> </s:form> </body></html>

Output of the doubleselectTag.jsp:

File Tag (Form Tag) Example

Page 167: 23277934-STRUTS2-ROSEINDIA

In this section, we are going to describe the file tag. The file tag is a UI tag that renders an HTML file

input element achieved through browsing.

Add the following code snippet into the struts.xml file.struts.xml

<action name="fileTag"> <result>/pages/uiTags/fileTag.jsp</result></action>

Create a jsp using the tag <s:file>. It renders an HTML file input element.

The parameter name is used to set a name for element which we have used as name="uploadFile". and the parameter accept is the HTML accept attribute that indicates the accepted file mime types which we have used as accept="text/*".

fileTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>File Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">File Tag Example!</span></h1> <b>File Name</b> <s:form> <s:file name="uploadFile" accept="text/*" /> </s:form> </body></html>

Output of the fileTag.jsp

Page 168: 23277934-STRUTS2-ROSEINDIA

On clicking the "Browse.." button. You will see a window that can be used to browse a file to upload.

Form Tag Example

In this section, we are going to describe the form tag. The form tag is a UI tag that renders HTML an input form. The remote form allows the form to be submitted without the page being refreshed. The results from the form can be inserted into any HTML element on the page.

Add the following code snippet into the struts.xml file.struts.xml

<action name="formTag">

Page 169: 23277934-STRUTS2-ROSEINDIA

<result>/pages/uiTags/formTag.jsp</result></action>

Create a jsp using the tag <s:form>.It renders HTML as an input form

formTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html> <head> <title>Form Tag Example!</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> </head> <body> <h1><span style="background-color: #FFFFcc">Form Tag Example</span></h> <s:form> <s:textfield name="username" label="Login name"/> <s:password name="password" label="Password"/> <s:submit value="Login" align="center"/> </s:form> </body></html>

Output of the formTag.jsp:

Label Tag (Form Tag) Example

In this section, we are going to describe the label tag. The label tag is a UI tag that is used to render an HTML LABEL that allows us to output label:name type of combinations that has the same format treatment as the rest of UI controls.

Page 170: 23277934-STRUTS2-ROSEINDIA

Add the following code snippet into the struts.xml file.struts.xml

<action name="labelTag"> <result>/pages/uiTags/labelTag.jsp</result></action>

Create a jsp using the tag <s:label>. It renders an HTML LABEL that allows us to output <s: label name=" " value=" " /> combination that has the same format treatment as the rest of UI controls.

labelTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html> <head> <title>Label Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Label Tag Example</span></h> <s:form> <s:label name="name" value= "Name" /> <s:label name="roll" value= "Roll" /> <s:label name="address" value= "Address: " /> </s:form> </body></html>

Output of the labelTag.jsp:

Optiontransferselect Tag (Form Tag) Example

In this section, we are going to describe the Optiontransferselect tag. The Optiontransferselect tag is a UI tag that creates an option transfer select component. There are two <select ...> tags

Page 171: 23277934-STRUTS2-ROSEINDIA

with buttons in the middle of them, which allows options in each of the <select ...> to be moved between them. It auto-selects all its elements upon its containing form submission.

NOTE: The id and doubleId parameters are not needed to supply as they will get generated when the optiontransferselect tag is being used in a form tag. The generated id and doubleId will be <form_id>_<optiontransferselect_doubleName> and <form_id>_<optiontransferselect_doubleName> respectively.

Add the following code snippet into the struts.xml file.struts.xml

<action name="optiontransferselectTag"> <result>/pages/uiTags/optiontransferselectTag.jsp</result></action>

Create a jsp using the tag <s:optiontransferselect> that creates an option transfer select component. This tag contains various parameters:

The label parameter sets label expression used for rendering an element specific label. In our case we have set it to "Employee Records"The name parameter sets the name for the element. In our case we have set it to "leftSideEmployeeRecords"The leftTitle parameter sets the left title. In our case we have set it to "RoseIndia"The rightTitle parameter sets the right title. In our case we have set it to "JavaJazzUp"The headerKey sets the header key of the given list. It must not be empty. In our case we have set it to:"headerKey"The headerValue sets the header value of the given list. In our case we have set it to:"--- Please Select ---"The doubleName sets the name for complete component. In our case we have set it to:"rightSideEmployeeRecords"The doubleHeaderKey sets the header key for the second list. In our case we have set it to:"doubleHeaderKey"The doubleHeaderValue sets the header value for the second list. In our case we have set it to:"--- Please Select ---"

optiontransferselectTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html> <head> <title>Optiontransferselect Tag Example!</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> </head> <body> <h1><span style="background-color: #FFFFcc">Optiontransferselect Tag Example!</span></h> <s:form> <s:optiontransferselect label="Employee Records" name="leftSideEmployeeRecords" leftTitle="RoseIndia"

Page 172: 23277934-STRUTS2-ROSEINDIA

rightTitle="JavaJazzUp" list="{'Deepak Kumar', 'Sushil Kumar','Vinod Kumar','Deepak Monthy', 'Deepak Mihanti', 'Sushil Kumar', 'Ravi Kant Kumar'}" headerKey="headerKey" headerValue="--- Please Select ---" doubleName="rightSideEmployeeRecords" doubleList="{'Amar Deep Patel', 'Amit Kumar','Chandan Kumar', 'Noor Kumar','Tammana Kumari'}" doubleHeaderKey="doubleHeaderKey" doubleHeaderValue="--- Please Select ---" /> </s:form> </body></html>

Output of the optiontransferselectTag.jsp:

Optgroup Tag (Form Tag) Example

Page 173: 23277934-STRUTS2-ROSEINDIA

In this section, we are going to describe the optgroup tag. The optgroup tag is a UI tag that creates an optgroup component which needs to reside within a select tag <s:select>.

Add the following code snippet

into the struts.xml file.struts.xml<action name="optgroupTag"> <result>/pages/uiTags/optgroupTag.jsp</result></action>

Create a jsp using the tag <s:optgroup> within the <s:select> tag. It creates an optgroup component. This tag contains few parameters:

The label parameter sets the label attribute In our case we have set it to "Hardware

" and "Software".

optgroupTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html> <head> <title>Optgroup Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Optgroup Tag Example!</span></h> <s:form> <s:select label="Please Select" name="select" list="%{#{'PROGRAMMING':'Programming', 'DATABASE':'DataBase', 'WEBAPPLICATION':'WebApplication'}}"> <s:optgroup label="Hardware" list="%{#{'CPU':'Centeral Processing Unit','MOUSE':'Mouse', 'KEYBOARD':'Keyboard'}}" /> <s:optgroup label="Software" list="%{#{'SYSTEM SOFTWARE':'System Software','APPLICATION SOFTWARE':'Application Software'}}" /> </s:select> </s:form> </body></html>

Output of the optgroupTag.jsp:

Page 174: 23277934-STRUTS2-ROSEINDIA

Password Tag (Form Tag) Example

In this section, we are going to describe the password tag. The password tag is a UI tag that renders an HTML

input tag of type password.

Add the following code snippet into the struts.xml file.struts.xml<action name="passwordTag"> <result>/pages/uiTags/passwordTag.jsp</result></action>

Create a jsp using the tag <s:password>. It renders an HTML input tag of type password.

passwordTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html> <head> <title>Password Tag Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc">Password Tag Example!</span></h> <s:form>

Page 175: 23277934-STRUTS2-ROSEINDIA

<s:password label="Enter Password" name="password" size="10" maxlength="8" /> </s:form> </body></html>

Output of the passwordTag.jsp:

Radio Tag (Form Tag) Example

In this section, we are going to describe the radio tag. The radio tag is a UI tag that renders a radio button input field.

Add the following code snippet into the struts.xml file.struts.xml

<action name="radioTag" class="net.roseindia.checkboxlistTag"> <result>/pages/uiTags/radioTag.jsp</result></action>

Create an action class with two lists as shown below:checkboxlistTag.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class checkboxlistTag extends ActionSupport{ private List fruits; private List animals; public String execute()throws Exception{ fruits = new ArrayList(); fruits.add("Apple");

Page 176: 23277934-STRUTS2-ROSEINDIA

fruits.add("Mango"); fruits.add("Orange"); fruits.add("Pine Apple");

animals = new ArrayList(); animals.add("Dog"); animals.add("Elephant"); animals.add("Ox"); animals.add("Fox"); return SUCCESS;

}

public List getFruits(){ return fruits; }

public List getAnimals(){ return animals; }}

Create a jsp using the tag <s:radio>.It renders a radio button input field.

radioTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html> <head> <title>Radio Tag Example!</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> </head> <body> <h1><span style="background-color: #FFFFcc">Radio Tag Example!</span></h> <s:form> <s:radio label="Fruits" name="fruitsname" list="fruits" /> <s:radio label="Animals" name="animalsname" list="animals" /> </s:form> </body></html>

Output of the radioTag.jsp:

Page 177: 23277934-STRUTS2-ROSEINDIA

Reset Tag (Form Tag) Example

In this section, we are going to describe the reset tag. The reset tag is a UI tag that is used with the form tag to provide form resetting.It renders a reset button.The reset can have two different types of rendering:

• input: renders as html <input type="reset"...>

• button: renders as html <button type="reset"...>

The button type has advantages as it adds the possibility to separate the submitted value from the text shown on the button face.

Add the following code snippet into the struts.xml file.struts.xml

<action name="resetTag"> <result>/pages/uiTags/resetTag.jsp</result></action>

Create a jsp using the tag <s:reset>. It renders a reset button which provides the form resetting.

resetTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html> <head> <title>Reset Tag Example!</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> </head>

Page 178: 23277934-STRUTS2-ROSEINDIA

<body> <h1><span style="background-color: #FFFFcc">Reset Tag Example!</span></h> <s:form> <s:textfield name="username" label="User Name" size="15" maxlength="10" /> <s:password name="password" label="Password" size="15" maxlength="10" /> <s:reset value="Reset" /> </s:form> </body></html>

Output of the resetTag.jsp:

Select Tag (Form Tag) Example

In this section, we are going to describe the select tag. The select tag is a UI tag that is used to render an HTML input tag of type select.

Add the following code snippet

into the struts.xml file.struts.xml<action name="selectTag" class="net.roseindia.weekDay"> <result>/pages/uiTags/selectTag.jsp</result></action>

Create an action class with a list populated with various items as shown below:weekDay.java

Page 179: 23277934-STRUTS2-ROSEINDIA

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class weekDay extends ActionSupport{ private List day; public String execute()throws Exception{ day = new ArrayList(); day.add("Sunday"); day.add("Monday"); day.add("Tuesday"); day.add("Wednesday"); day.add("Thursday"); day.add("Friday"); day.add("Saturday"); return SUCCESS;

}

public List getDay(){ return day; }}

Create a jsp using the tag <s:select> that creates an HTML input tag of type select. This tag contains various parameters:

The label parameter sets the label expression used for rendering an element specific label. In our 1st case we have set it to "Select Day" The name parameter sets the name for the element. In our 1st case we have set it to "daysname"The headerKey sets key for first item in list. It must not be empty and wrongly specified. In both cases we have set it to:"1"The headerValue sets the Value expression for the first item in the list. In both cases we have set it to:"--- Please Select ---"

selectTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Select Tag Example</title> </head> <body> <h1><span style="background-color: #FFFFcc">Select Tag Example!</span></h> <s:form> <s:select label="Select Day" name="daysname" headerKey="1" headerValue="-- Please Select --" list="day" />

<s:select label="Select Month"

Page 180: 23277934-STRUTS2-ROSEINDIA

name="monthname" headerKey="1" headerValue="-- Please Select --" list="#{'01':'January','02':'February','03':'March','04':'April','05':'May','06':'June','07':'July','08':'August','09':'September','10':'October','11':'November','12':'December'}" /> </s:form> </body></html>

Output of the selectTag.jsp :

Submit Tag (Form Tag) Example

In this section, we are going to describe the submit tag. The submit tag is a UI tag that is used to render a submit button. The submit tag is used with the form tag to provide asynchronous form submissions. The submit can have three different types of rendering:

• input: renders as html <input type="submit"...>

• image: renders as html <input type="image"...>

• button: renders as html <button type="submit"...>

Page 181: 23277934-STRUTS2-ROSEINDIA

Add the following code snippet into the struts.xml file.struts.xml

<action name="submitTag"> <result>/pages/uiTags/submitTag.jsp</result></action>

Create a jsp using the tag <s:submit> that renders a submit button. This tag contains various parameters:

The value parameter presets the value of input element. In our 1st case we have set it to "Submit" The type parameter sets the type of submit to use. Valid values are input, button and image. In our case we have set it to "image"The src supplies an image src for image type submit button. It will have no effect for types input and button. In our case we have set it to:"/struts2tags/pages/uiTags/submit.gif" The align sets HTML align attribute. In our case we have set it to:"center"

submitTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Submit Tag Example</title> </head> <body> <h1><span style="background-color: #FFFFcc">Submit Tag Example!</span></h> <s:form> <s:textfield name="username" label="User Name" size="15" maxlength="10" /> <s:textfield name="password" label="Password" size="15" maxlength="10" /> <s:submit value="Submit" /> <!-- To use gif button --> <s:submit type="image" src="/struts2tags/pages/uiTags/submit.gif" align="center" /> </s:form> </body></html>

Output of the submitTag.jsp:

Page 182: 23277934-STRUTS2-ROSEINDIA

Textarea Tag (Form Tag) Example

In this section, we are going to describe the textarea tag. The textarea tag is a UI tag that is used to render an HTML textarea.

Add the following code snippet

into the struts.xml file.struts.xml<action name="textareaTag"> <result>/pages/uiTags/textareaTag.jsp</result></action>

Create a jsp using the tag <s:textarea > that renders an HTML textarea tag.<s:textarea label="Description" name="description" cols="15" rows="10" /> tag displays an HTML textarea with label equal to Description, column value=15 and row value=10.textareaTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Textarea Tag Example</title> <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> </head> <body>

Page 183: 23277934-STRUTS2-ROSEINDIA

<h1><span style="background-color: #FFFFcc">Textarea Tag Example!</span></h> <s:form> <s:textarea label="Description" name="description" cols="15" rows="10" /> </s:form> </body></html>

Output of the textareaTag.jsp:

Textfield Tag (Form Tag) Example

In this section, we are going to describe the textfield tag. The textfield tag is a UI tag that is used to render an HTML input field of type text.

Add the following code snippet into the struts.xml file.struts.xml

<action name="textfieldTag"> <result>/pages/uiTags/textfieldTag.jsp</result></action>

Create a jsp using the tag <s:textfield > that renders an HTML input field of type text.

<s:textfield label="Employee Name" name="empname" size="15" maxlength="10" /> tag displays an HTML text field with label equal to Employee Name with length of 15 columns.

textfieldTag.jsp

Page 184: 23277934-STRUTS2-ROSEINDIA

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Textfield Tag Example</title> </head> <body> <h1><span style="background-color: #FFFFcc">Textfield Tag Example!</span></h> <s:form> <s:textfield label="Employee Name" name="empname" size="15" maxlength="10" /> </s:form> </body></html>

Output of the textfieldTag.jsp:

Updownselect Tag (Form Tag) Example

In this section, we are going to describe the updownselect tag. The updownselect tag is a UI tag that creates a select component with buttons to move up and down the elements in the select component. When the containing form is submitted, its elements will be submitted in the order they are arranged (top to bottom).

Add the following code snippet into the struts.xml file.struts.xml

<action name="updownselectTag"> <result>/pages/uiTags/updownselectTag.jsp</result></action>

Create a jsp using the tag <s:updownselect> that creates a select component with buttons to move up and down. This tag contains various parameters:

The name parameter presets the value of input element. In our case we have set it to "daysname" The moveDownLabel parameter is used for the text to display on the move down button. In our

Page 185: 23277934-STRUTS2-ROSEINDIA

case we have set it to "Move Down"The moveUpLabel parameter is used for the text to display on the move up button. In our case we have set it to:"Move Up"The selectAllLabel parameter is used for the text to be displayed on the select all button In our case we have set it to:"Select All"

updownselectTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Updownselect Tag Example</title> </head> <body> <h1><span style="background-color: #FFFFcc">Updownselect Tag Example!</span></h> <s:form> <s:updownselect list="#{'01':'January','02':'February','03':'March','04':'April','05':'May','06':'June','07':'July','08':'August','09':'September','10':'October','11':'November','12':'December'}" name="daysname" headerKey="1" headerValue="-- Please Select --" moveUpLabel="Move Up" moveDownLabel="Move Down" selectAllLabel="Select All" /> </s:form> </body></html>

Output of the updownselectTag.jsp:

Page 186: 23277934-STRUTS2-ROSEINDIA

Actionerror and Actionmessage Tags (Non-Form UI Tags) Example

In this section, we are going to describe the actionerror and actionmessage tags. The actionerror tag is a UI tag that renders action errors (in the jsp pages.) if they exists while the actionmessage tag renders action messages if they exists.

Add the following code snippet into the struts.xml file.struts.xml

<action name="actionerrorTag"> <result>/pages/uiTags/Login.jsp</result></action>

<action name="login" class="net.roseindia.checkValidUser"> <result name="input">/pages/uiTags/Login.jsp</result> <result name="error">/pages/uiTags/error.jsp</result> <result>/pages/uiTags/validUser.jsp</result></action>

Create an action class that uses methods addActionMessage(String) and addActionError(String) within the execute() method. The addActionMessage(String) will print the passed string on the success jsp page while the addActionError(String) will print the passed string on the error jsp page.

checkValidUser.java

package net.roseindia;

Page 187: 23277934-STRUTS2-ROSEINDIA

import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class checkValidUser extends ActionSupport { private String username = null; private String password = null; public String execute() throws Exception{ if ((getUsername().equals("Roseindia")) && (getPassword().equals("Roseindia"))){ addActionMessage("Valid User!"); return SUCCESS; } else{ addActionError("Invalid User!"); return ERROR; } } //Set and get the user name public void setUsername(String name){ username = name; } public String getUsername(){ return username; } //set and get the password public void setPassword(String pass){ password = pass; } public String getPassword(){ return password; }}

Create a Login jsp page as shown:Login.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Actionerror Tag Example!</title> <body> <s:form action="login" method="POST"> <s:textfield label="User Name" name="username" size="20" maxlength="10" /> <s:password label="Password" name="password" size="20" maxlength="10" /> <s:submit value="Submit" /> </s:form> </body></html>

Create a jsp page that will display your error message (when fails to logged-in) using the empty <s:actionerror /> tag as shown:error.jsp

Page 188: 23277934-STRUTS2-ROSEINDIA

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Actionerror Tag Example!</title> <body> <h1> <s:actionerror /> </h1> <a href="/struts2tags/roseindia/actionerrorTag.action">Go Back</a> </body></html>

Create a jsp page that will display a message (when successfully logged-in) using the empty <s:actionmessage /> tag as shown:

validUser.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Actionerror Tag Example!</title> <body> <h1> <s:actionmessage /> </h1> </body></html>

you will see the output of the Login.jsp as shown below:

Enter the wrong user name but correct password in the login page.

you will get the following output:

Page 189: 23277934-STRUTS2-ROSEINDIA

Enter the correct user name but incorrect password in the login page

you will get the following output:

Enter correct values in both fields of the login page

you will get the following output:

Fielderror Tag (Non-Form UI Tags) Example

In this section, we are going to describe the fielderror tags. The fielderror tag is a UI tag that renders field errors if they exists.

Add the following code snippet into the struts.xml file.struts.xml

Page 190: 23277934-STRUTS2-ROSEINDIA

<action name="fieldError"> <result>/pages/uiTags/loginFielderrorTag.jsp</result></action>

<action name="checkUser" class="net.roseindia.checkField"> <result name="input">/pages/uiTags/loginFielderrorTag.jsp</result> <result name="error">/pages/uiTags/fielderrorTag.jsp</result> <result>/pages/uiTags/validUser.jsp</result></action>

Develop an action class using addFieldError(String fieldName, String errorMessage) method. This method adds an error message for a given field to the corresponding jsp page.checkField.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class checkField extends ActionSupport { private String username = null; private String password = null; public String execute() throws Exception{ if ((getUsername().equals("Roseindia")) && (getPassword().equals("Roseindia"))){ addActionMessage("Valid User!"); return SUCCESS; } if(!(getUsername().equals("Roseindia"))) addFieldError("username","Invalid username!");

if(!(getPassword().equals("Roseindia"))) addFieldError("password","Invalid password!");

return ERROR; } //Set and get the user name public void setUsername(String username){ this.username = username; } public String getUsername(){ return username; } //set and get the password public void setPassword(String pass){ password = pass; } public String getPassword(){

Page 191: 23277934-STRUTS2-ROSEINDIA

return password; }}

Create a Login jsp page as shown:loginFielderrorTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Fielderror Tag Example!</title> <body> <s:form action="checkUser" method="POST"> <s:textfield label="User Name" name="username" size="20" maxlength="10" /> <s:password label="Password" name="password" size="20" maxlength="10" /> <s:submit value="Submit" /> </s:form> </body></html>

Create a jsp page that will display your field error messages (when fails to logged-in) using the empty <s:fielderror/> tag as shown:fielderrorTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Fielderror Tag Example!</title> <body> <h1> <s:fielderror /> </h1> <a href="/struts2tags/roseindia/fieldError.action">Go Back</a> </body></html>

Create a jsp page that will display your messages (when succeed to logged-in) using the empty <s:actionmessage /> tag as shown:validUser.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Fielderror Tag Example!</title> <body> <h1> <s:actionmessage /> </h1> </body></html>

Page 192: 23277934-STRUTS2-ROSEINDIA

you will see the output of the loginFielderrorTag.jsp as shown below:

Enter the wrong user name and correct password in the login page

you will get the following output:

Enter the correct user name and wrong password in the login page

you will get the following output:

Enter incorrect values in both fields of the login page

Page 193: 23277934-STRUTS2-ROSEINDIA

you will get the following output:

Enter correct values in both fields of the login page

you will get the following output:

TabbedPanel (Ajax Tag) Example

In this section, you will learn about the tabbedPanel tag. This is an Ajax component, where each tab is either a local content or a remote content (refreshed each time when user selects that tab).

To use tabbedPanel tag, the head tag must be included on the jsp page and must be configured for performance

or debugging purposes. However, If you want to use the cookie feature then you must provide a unique id for the tabbedpanel component. This is used for identifying the name of component that is stored by the cookie.

Add the following code snippet

Page 194: 23277934-STRUTS2-ROSEINDIA

into the struts.xml file.struts.xml<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="TabbedPanel"> <result>/pages/tabbedpanel.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Create a jsp using the tag <s:tabbedPanel>. This tag is used for creating the tabs. tabbedPane.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <s:head theme="ajax" debug="true"/> </head> <body> <table border="1" width="50%"> <tr> <td width="100%">

<s:tabbedPanel id="test" >

<s:div id="one" label="Tab 1" theme="ajax" labelposition="top" > This is the first panel. RoseIndia.nt<br> JavaJazzUp.com<br> NewsTrackIndia.com </s:div>

<s:div id="two" label="Tab 2" theme="ajax"> This is the second panel. </s:div> <s:div id="three" label="Tab 3" theme="ajax">

Page 195: 23277934-STRUTS2-ROSEINDIA

This is the third panel.<br> Java Tutorial<br> PHP Tutorial<br> Linux Tutorial </s:div>

<s:div id="four" label="Tab 4" theme="ajax"> This is the forth panel. </s:div>

</s:tabbedPanel>

</td> </tr> </table> </body></html>

Output:

When you run the above example, you get the output as:

When you click the "Tab 2" then you get the content of "Tab 2" as shown:

Page 196: 23277934-STRUTS2-ROSEINDIA

If you click "Tab 3" then you get the content of "Tab 3" as shown:

If you click the "Tab 4" you get the content of "Tab 4" as:

tree and treenode (Ajax Tag) tags Example

In this section, you will learn about the tree and treenode tags. These both work with the Ajax support.

tree: This is a tree widget

with AJAX support. Normally this tag uses the "id" attribute. The "id" attribute is required if the "selectedNotifyTopic" or the "href" attribute is going to be used.

treenode: This is a tree node which renders a tree node within a tree widget with AJAX support. The following of the two combinations are used depending on the requirement like the tree is needed to be constructed dynamically or statically.Dynamically

• id - This is an id of tree node.

Page 197: 23277934-STRUTS2-ROSEINDIA

• title - This is as like a label to be displayed for the tree node

Statically

• rootNode - This is the parent node where the tree is derived form.

• nodeIdProperty - This is the current tree node's id.

• nodeTitleProperty - This is the current tree node's title.

• childCollectionProperty - This is the current tree node's children.

In this section, you will learn about the tree and treenode tags. These both work with the Ajax support.

tree: This is a tree widget

with AJAX support. Normally this tag uses the "id" attribute. The "id" attribute is required if the "selectedNotifyTopic" or the "href" attribute is going to be used.

treenode: This is a tree node which renders a tree node within a tree widget with AJAX support. The following of the two combinations are used depending on the requirement like the tree is needed to be constructed dynamically or statically.Dynamically

• id - This is an id of tree node.

• title - This is as like a label to be displayed for the tree node

Statically

• rootNode - This is the parent node where the tree is derived form.

• nodeIdProperty - This is the current tree node's id.

• nodeTitleProperty - This is the current tree node's title.

• childCollectionProperty - This is the current tree node's children.

Div (Ajax Tag) tag Example

In this section, you will learn about the div tag. The div tag is an Ajax component that is used with Ajax that refreshes the content of a particular section without refreshing the entire page.

The div tag when used with Ajax refreshes the content of a particular section without refreshing the entire page.

HTML <DIV /> tag created by Ajax div tag includes it's content and is used to obtain it's content through a remote XMLHttpRequest call through the dojo framework.

THE FOLLOWING ATTRIBUTES ARE VALID IF AJAX IS CONFIGURED

• href: Set 'href' as a url tag reference value.

• errorText: If a request makes any error then 'errorText' is displayed.

• afterLoading: Use 'notifyTopics' since 'afterLoading' has been Deprecated.

• executeScripts: Setting the value of 'executeScripts' to true allows the javascript sections to execute in the returned text.

• loadingText: On making the request the 'targets' element displays the text 'loadingText'.

Page 198: 23277934-STRUTS2-ROSEINDIA

• listenTopics: The comma separated list 'listenTopics' is the list of topic names that is used to trigger a request.

• handler: The function that takes care of any AJAX request is termed as 'handler'. The function uses Dojo's widget and dom node as parameters to be passed).

• formId: The fields of the formId are used to serialize and pass as the parameters in the request.

• formFilter: The function 'formFilter' is used to filter the fields that are to be serialized which receives the elements as parameters and returns true if the element is included.

• targets: Here 'targets' is the list of ids to be updated with the text returned from request.

• notifyTopics: 'notifyTopics' is nothing but the list of topic names separated by commas to be published. It takes three parameters.

1. data: is the html or json object while type = 'error' or type = 'error'

2. type: it should be of the type 'before' before requesting, 'load' whenever request succeeds and 'error' whenever the request fails.

3. request: it requests for the javascript objects if type='error' ortype='load'.

• showErrorTransportText: 'showErrorTransportText' displays the errors on target.

• indicator

The attribute 'updateFreq' refreshes after a certain time period, specified in miliseconds.

The attribute 'autoStart' starts the timer automatically while sets to true which is the default value.

The attribute 'startTimerListenTopics' is used to start the timer whenever 'startTimerListenTopic' is the comma-separated list of topics.

The attribute ''stopTimerListenTopics' is used to start the timer whenever ''stopTimerListenTopics' is the comma-separated list of topics.

'showLoadingText' displays the loaded text on targets while 'separateScript' runs each script in each scope that is unique for each Div.

Add the following code snippet into the struts.xml file.strurts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /><include file="struts-default.xml"/>

<!-- Add packages here -->

<package name="roseindia" namespace="/roseindia" extends="struts-default">

Page 199: 23277934-STRUTS2-ROSEINDIA

<action name="div"> <result>/pages/div.jsp</result> </action>

</package>

</struts>

Create a jsp using the tag <s:div>. div.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Enter first and last name</title> <s:head theme="ajax" debug="false"/> </head> <body> <s:url id="test" value="/pages/mask.jsp" /> <s:div id="one" theme="ajax" href="%{test}"> </s:div> </body></html>

mask.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Enter first and last name</title> <s:head theme="ajax" debug="false"/>

</head> <body> <s:div id="maskValue" > <div style="position:absolute;top:10; left:20; width:300; height:175;background-color:#E5E5E5;"> <h3>Enter first and last name:</h3> <s:form theme="ajax" action="doMask"> <s:textfield name="firstname" label="Firstname" /> <s:textfield name="lastname" label="Lastname" /> <s:submit value="Submit" theme="ajax" targets="maskValue" /> </s:form> </div> <br> <div id="8" style="position:absolute;top:10; left:350; width:300; height:160;background-color:#E5E5E5;"> <h3>Output: </h3>

Page 200: 23277934-STRUTS2-ROSEINDIA

Firstname : <s:property value="firstname" /> <br><br> Lastname : <s:property value="lastname" /> </div> </s:div> </body></html>

Output:

Actionerror and Actionmessage Tags (Non-Form UI Tags) Example

In this section, we are going to describe the actionerror and actionmessage tags. The actionerror tag is a UI tag that renders action errors (in the jsp pages.) if they exists while the actionmessage tag renders action messages if they exists.

Add the following code snippet into the struts.xml file.struts.xml

<action name="actionerrorTag"> <result>/pages/uiTags/Login.jsp</result></action>

<action name="login" class="net.roseindia.checkValidUser"> <result name="input">/pages/uiTags/Login.jsp</result> <result name="error">/pages/uiTags/error.jsp</result> <result>/pages/uiTags/validUser.jsp</result></action>

Create an action class that uses methods addActionMessage(String) and addActionError(String) within the execute() method. The addActionMessage(String) will print the passed string on the success jsp page while the addActionError(String) will print the passed string on the error jsp page.

checkValidUser.java

package net.roseindia;

Page 201: 23277934-STRUTS2-ROSEINDIA

import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class checkValidUser extends ActionSupport { private String username = null; private String password = null; public String execute() throws Exception{ if ((getUsername().equals("Roseindia")) && (getPassword().equals("Roseindia"))){ addActionMessage("Valid User!"); return SUCCESS; } else{ addActionError("Invalid User!"); return ERROR; } } //Set and get the user name public void setUsername(String name){ username = name; } public String getUsername(){ return username; } //set and get the password public void setPassword(String pass){ password = pass; } public String getPassword(){ return password; }}

Create a Login jsp page as shown:Login.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Actionerror Tag Example!</title> <body> <s:form action="login" method="POST"> <s:textfield label="User Name" name="username" size="20" maxlength="10" /> <s:password label="Password" name="password" size="20" maxlength="10" /> <s:submit value="Submit" /> </s:form> </body></html>

Create a jsp page that will display your error message (when fails to logged-in) using the empty <s:actionerror /> tag as shown:error.jsp

Page 202: 23277934-STRUTS2-ROSEINDIA

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Actionerror Tag Example!</title> <body> <h1> <s:actionerror /> </h1> <a href="/struts2tags/roseindia/actionerrorTag.action">Go Back</a> </body></html>

Create a jsp page that will display a message (when successfully logged-in) using the empty <s:actionmessage /> tag as shown:

validUser.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Actionerror Tag Example!</title> <body> <h1> <s:actionmessage /> </h1> </body></html>

you will see the output of the Login.jsp as shown below:

Enter the wrong user name but correct password in the login page.

you will get the following output:

Page 203: 23277934-STRUTS2-ROSEINDIA

Enter the correct user name but incorrect password in the login page

you will get the following output:

Enter correct values in both fields of the login page

you will get the following output:

Fielderror Tag (Non-Form UI Tags) Example

In this section, we are going to describe the fielderror tags. The fielderror tag is a UI tag that renders field errors if they exists.

Add the following code snippet into the struts.xml file.struts.xml

Page 204: 23277934-STRUTS2-ROSEINDIA

<action name="fieldError"> <result>/pages/uiTags/loginFielderrorTag.jsp</result></action>

<action name="checkUser" class="net.roseindia.checkField"> <result name="input">/pages/uiTags/loginFielderrorTag.jsp</result> <result name="error">/pages/uiTags/fielderrorTag.jsp</result> <result>/pages/uiTags/validUser.jsp</result></action>

Develop an action class using addFieldError(String fieldName, String errorMessage) method. This method adds an error message for a given field to the corresponding jsp page.checkField.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;

public class checkField extends ActionSupport { private String username = null; private String password = null; public String execute() throws Exception{ if ((getUsername().equals("Roseindia")) && (getPassword().equals("Roseindia"))){ addActionMessage("Valid User!"); return SUCCESS; } if(!(getUsername().equals("Roseindia"))) addFieldError("username","Invalid username!");

if(!(getPassword().equals("Roseindia"))) addFieldError("password","Invalid password!");

return ERROR; } //Set and get the user name public void setUsername(String username){ this.username = username; } public String getUsername(){ return username; } //set and get the password public void setPassword(String pass){ password = pass; } public String getPassword(){

Page 205: 23277934-STRUTS2-ROSEINDIA

return password; }}

Create a Login jsp page as shown:loginFielderrorTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Fielderror Tag Example!</title> <body> <s:form action="checkUser" method="POST"> <s:textfield label="User Name" name="username" size="20" maxlength="10" /> <s:password label="Password" name="password" size="20" maxlength="10" /> <s:submit value="Submit" /> </s:form> </body></html>

Create a jsp page that will display your field error messages (when fails to logged-in) using the empty <s:fielderror/> tag as shown:fielderrorTag.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Fielderror Tag Example!</title> <body> <h1> <s:fielderror /> </h1> <a href="/struts2tags/roseindia/fieldError.action">Go Back</a> </body></html>

Create a jsp page that will display your messages (when succeed to logged-in) using the empty <s:actionmessage /> tag as shown:validUser.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Fielderror Tag Example!</title> <body> <h1> <s:actionmessage /> </h1> </body></html>

Page 206: 23277934-STRUTS2-ROSEINDIA

you will see the output of the loginFielderrorTag.jsp as shown below:

Enter the wrong user name and correct password in the login page

you will get the following output:

Enter the correct user name and wrong password in the login page

you will get the following output:

Enter incorrect values in both fields of the login page

Page 207: 23277934-STRUTS2-ROSEINDIA

you will get the following output:

Enter correct values in both fields of the login page

you will get the following output:

TabbedPanel (Ajax Tag) Example

In this section, you will learn about the tabbedPanel tag. This is an Ajax component, where each tab is either a local content or a remote content (refreshed each time when user selects that tab).

To use tabbedPanel tag, the head tag must be included on the jsp page and must be configured for performance or debugging purposes. However, If you want to use the cookie feature then you must provide a unique id for the tabbedpanel component. This is used for identifying the name of component that is stored by the cookie.

Add the following code snippet into the struts.xml file.struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

Page 208: 23277934-STRUTS2-ROSEINDIA

<!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="TabbedPanel"> <result>/pages/tabbedpanel.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Create a jsp using the tag <s:tabbedPanel>. This tag is used for creating the tabs. tabbedPane.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <s:head theme="ajax" debug="true"/> </head> <body> <table border="1" width="50%"> <tr> <td width="100%">

<s:tabbedPanel id="test" >

<s:div id="one" label="Tab 1" theme="ajax" labelposition="top" > This is the first panel. RoseIndia.nt<br> JavaJazzUp.com<br> NewsTrackIndia.com </s:div>

<s:div id="two" label="Tab 2" theme="ajax"> This is the second panel. </s:div> <s:div id="three" label="Tab 3" theme="ajax"> This is the third panel.<br> Java Tutorial<br> PHP Tutorial<br> Linux Tutorial </s:div>

<s:div id="four" label="Tab 4" theme="ajax"> This is the forth panel.

Page 209: 23277934-STRUTS2-ROSEINDIA

</s:div>

</s:tabbedPanel>

</td> </tr> </table> </body></html>

Output:

When you run the above example, you get the output as:

When you click the "Tab 2" then you get the content of "Tab 2" as shown:

If you click "Tab 3" then you get the content of "Tab 3" as shown:

Page 210: 23277934-STRUTS2-ROSEINDIA

If you click the "Tab 4" you get the content of "Tab 4" as:

TabbedPanel (Ajax Tag) Example

In this section, you will learn about the tabbedPanel tag. This is an Ajax component, where each tab is either a local content or a remote content (refreshed each time when user selects that tab).

To use tabbedPanel tag, the head tag must be included on the jsp page and must be configured for performance or debugging purposes. However, If you want to use the cookie feature then you must provide a unique id for the tabbedpanel component. This is used for identifying the name of component that is stored by the cookie.

Add the following code snippet into the struts.xml file.struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials -->

Page 211: 23277934-STRUTS2-ROSEINDIA

<constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="TabbedPanel"> <result>/pages/tabbedpanel.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts>

Create a jsp using the tag <s:tabbedPanel>. This tag is used for creating the tabs. tabbedPane.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <s:head theme="ajax" debug="true"/> </head> <body> <table border="1" width="50%"> <tr> <td width="100%">

<s:tabbedPanel id="test" >

<s:div id="one" label="Tab 1" theme="ajax" labelposition="top" > This is the first panel. RoseIndia.nt<br> JavaJazzUp.com<br> NewsTrackIndia.com </s:div>

<s:div id="two" label="Tab 2" theme="ajax"> This is the second panel. </s:div> <s:div id="three" label="Tab 3" theme="ajax"> This is the third panel.<br> Java Tutorial<br> PHP Tutorial<br> Linux Tutorial </s:div>

<s:div id="four" label="Tab 4" theme="ajax"> This is the forth panel. </s:div>

Page 212: 23277934-STRUTS2-ROSEINDIA

</s:tabbedPanel>

</td> </tr> </table> </body></html>

Output:

When you run the above example, you get the output as:

When you click the "Tab 2" then you get the content of "Tab 2" as shown:

If you click "Tab 3" then you get the content of "Tab 3" as shown:

Page 213: 23277934-STRUTS2-ROSEINDIA

If you click the "Tab 4" you get the content of "Tab 4" as:

tree and treenode (Ajax Tag) tags Example

In this section, you will learn about the tree and treenode tags. These both work with the Ajax support.

tree: This is a tree widget

with AJAX support. Normally this tag uses the "id" attribute. The "id" attribute is required if the "selectedNotifyTopic" or the "href" attribute is going to be used.

treenode: This is a tree node which renders a tree node within a tree widget with AJAX support. The following of the two combinations are used depending on the requirement like the tree is needed to be constructed dynamically or statically.Dynamically

• id - This is an id of tree node.

• title - This is as like a label to be displayed for the tree node

Page 214: 23277934-STRUTS2-ROSEINDIA

Statically

• rootNode - This is the parent node where the tree is derived form.

• nodeIdProperty - This is the current tree node's id.

• nodeTitleProperty - This is the current tree node's title.

• childCollectionProperty - This is the current tree node's children.

• Add the following code snippet to the struts.xml file.struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts> <!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" />

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="TreeNode"> <result>/pages/treenode.jsp</result> </action>

<!-- Add actions here --> </package>

<!-- Add packages here -->

</struts> • Create a jsp using the tag <s:tree>. This tag is used for rendering a tree widget.

Similarly the tag <s:treenode> renders a tree node with a label attached to the created tree widget eg.. <s:treenode theme="ajax" id="subchild2" label="subchild2" /> tag attaches a new node to the created tree with a tree node having id="subchild2" and a label="subchild2".

• treenode.jsp<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <s:head theme="ajax" debug="true"/> </head> <body> <s:tree theme="ajax" id="root" label="Root"> <s:treenode theme="ajax" id="child1" label="<b>Child 1</b>" /> <s:treenode theme="ajax" id="subchild1" label="SubChild 1"> <s:treenode theme="ajax" id="subchild2" label="SubChild 2" /> <s:treenode theme="ajax" id="subchild3" label="SubChild 3" />

Page 215: 23277934-STRUTS2-ROSEINDIA

</s:treenode> <s:treenode theme="ajax" id="child2" label="<b>child 2</b>" /> </s:tree> </body></html>

• Output:• When you run the above example, you get:

Div (Ajax Tag) tag Example

In this section, you will learn about the div tag. The div tag is an Ajax component that is used with Ajax that refreshes the content of a particular section without refreshing the entire page.

The div tag when used with Ajax refreshes the content of a particular section without refreshing the entire page.

HTML <DIV /> tag created by Ajax div tag includes it's content and is used to obtain it's content through a remote XMLHttpRequest call through the dojo framework.

THE FOLLOWING ATTRIBUTES ARE VALID IF AJAX IS CONFIGURED

• href: Set 'href' as a url tag reference value.

• errorText: If a request makes any error then 'errorText' is displayed.

• afterLoading: Use 'notifyTopics' since 'afterLoading' has been Deprecated.

• executeScripts: Setting the value of 'executeScripts' to true allows the javascript

sections to execute in the returned text.

• loadingText: On making the request the 'targets' element displays the text 'loadingText'.

• listenTopics: The comma separated list 'listenTopics' is the list of topic names that is used to trigger a request.

Page 216: 23277934-STRUTS2-ROSEINDIA

• handler: The function that takes care of any AJAX request is termed as 'handler'. The function uses Dojo's widget and dom node as parameters to be passed).

• formId: The fields of the formId are used to serialize and pass as the parameters in the request.

• formFilter: The function 'formFilter' is used to filter the fields that are to be serialized which receives the elements as parameters and returns true if the element is included.

• targets: Here 'targets' is the list of ids to be updated with the text returned from request.

• notifyTopics: 'notifyTopics' is nothing but the list of topic names separated by commas to be published. It takes three parameters.

1. data: is the html or json object while type = 'error' or type = 'error'

2. type: it should be of the type 'before' before requesting, 'load' whenever request succeeds and 'error' whenever the request fails.

3. request: it requests for the javascript objects if type='error' ortype='load'.

• showErrorTransportText: 'showErrorTransportText' displays the errors on target.

• indicator

The attribute 'updateFreq' refreshes after a certain time period, specified in miliseconds.

The attribute 'autoStart' starts the timer automatically while sets to true which is the default value.

The attribute 'startTimerListenTopics' is used to start the timer whenever 'startTimerListenTopic' is the comma-separated list of topics.

The attribute ''stopTimerListenTopics' is used to start the timer whenever ''stopTimerListenTopics' is the comma-separated list of topics.

'showLoadingText' displays the loaded text on targets while 'separateScript' runs each script in each scope that is unique for each Div.

Add the following code snippet into the struts.xml file.strurts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software

Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<!-- Rose India Struts 2 Tutorials --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /><include file="struts-default.xml"/>

<!-- Add packages here -->

Page 217: 23277934-STRUTS2-ROSEINDIA

<package name="roseindia" namespace="/roseindia" extends="struts-default">

<action name="div"> <result>/pages/div.jsp</result> </action>

</package>

</struts>

Create a jsp using the tag <s:div>. div.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Enter first and last name</title> <s:head theme="ajax" debug="false"/> </head> <body> <s:url id="test" value="/pages/mask.jsp" /> <s:div id="one" theme="ajax" href="%{test}"> </s:div> </body></html>

mask.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <title>Enter first and last name</title> <s:head theme="ajax" debug="false"/>

</head> <body> <s:div id="maskValue" > <div style="position:absolute;top:10; left:20; width:300; height:175;background-color:#E5E5E5;"> <h3>Enter first and last name:</h3> <s:form theme="ajax" action="doMask"> <s:textfield name="firstname" label="Firstname" /> <s:textfield name="lastname" label="Lastname" /> <s:submit value="Submit" theme="ajax" targets="maskValue" /> </s:form> </div> <br> <div id="8" style="position:absolute;top:10; left:350; width:300; height:160;background-color:#E5E5E5;">

Page 218: 23277934-STRUTS2-ROSEINDIA

<h3>Output: </h3> Firstname : <s:property value="firstname" /> <br><br> Lastname : <s:property value="lastname" /> </div> </s:div> </body></html>

Output:

Struts 2 Date Examples

In this section we will discuss the date processing functionalities available in the Struts 2 Framework. After reading the tutorials you will lean how to use date functions provided by Struts 2 Framework.

1. Date Format Examples In this tutorials you will learn about Date Format function in Struts 2. We have provided fully tested example code to illustrate the concepts.

2. Struts 2 datepicker Example In this section we will show you how to develop datetimepicker in struts 2. Struts 2 uses the dojo toolkit for creating date picker.

Struts 2 Date Format Examples

In this tutorial you will learn about Date Format function in Struts 2. We have provided fully tested example code to illustrate the concepts. You can copy the code and use it for your fast development.

Struts Date tag

Struts date tag is used to output the date into required format. It can be used to format the date into several different formats. Syntax of the date tag is:

<s:date name="todayDate" format="yyyy-MM-dd" />

Parameters

Following table shows the parameters of date tag.

Name Required Default Evaluated Type Descriptionformat false false String The date format patternid false true String It will be used id tag in the HTML

Page 219: 23277934-STRUTS2-ROSEINDIA

name true true StringThe date value which is to be formatted

nice false false true BooleanWhether to print out the date nicely

The nice format is very interesting. The following table shows, how it will format the date output:

i18n key defaultstruts.date.format.past {0} agostruts.date.format.future in {0}struts.date.format.seconds an instantstruts.date.format.minutes {0,choice,1#one minute|1<{0} minutes}

struts.date.format.hours{0,choice,1#one hour|1<{0} hours}{1,choice,0#|1#, one minute|1<, {1} minutes}

struts.date.format.days{0,choice,1#one day|1<{0} days}{1,choice,0#|1#, one hour|1<, {1} hours}

struts.date.format.years{0,choice,1#one year|1<{0} years}{1,choice,0#|1#, one day|1<, {1} days}

Writing Example

In this example we will use DateBean action class to get the current date of the system. This current date will be used in our example. Here is the code of DateBean.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

/** * <p> Validate a user login. </p> */public class DateBean extends ActionSupport {

public String execute() throws Exception {

setTodayDate(new Date()); return SUCCESS;

}

// ---- Username property ----

/** * <p>Field to store Today's Date.</p> * <p/> */ private Date todayDate;

/**

Page 220: 23277934-STRUTS2-ROSEINDIA

* <p>Provide Today's Date.</p> * * @return Returns the Todays date. */ public Date getTodayDate() { return todayDate; }

/** * <p>Store new Date</p> * * @param value The username to set. */ public void setTodayDate(Date value) { todayDate = value; }

}

Add the following entry in the struts.xml file in order to create action mapping:

<action name="FormatDate" class="net.roseindia.DateBean"><result>/pages/dateformat.jsp</result></action>

Following jsp file(dateformat.jsp) shows the usage of date tag:

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Format Date Example!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/>

</head><body>

<s:form action="FormatDate" method="POST">

<tr><td>Date in (yyyy-MM-dd) Format:</td><td><b><s:date name="todayDate" format="yyyy-MM-dd" /></b></td></tr>

<tr><td>Date in (MM/dd/yyyy hh:mm AM/PM) Format:</td><td><b><s:date name="todayDate" format="MM/dd/yyyy 'at' hh:mm a" /></b>

Page 221: 23277934-STRUTS2-ROSEINDIA

</td></tr>

<tr><td>Date in (dd-MMM-yyyy hh:mm AM/PM) Format:</td><td><b><s:date name="todayDate" format="dd-MMM-yyyy 'at' hh:mm a" /></b></td></tr>

<tr><td>Date in (dd/MM/yyyy hh:mm) Format:</td><td><b><s:date name="todayDate" format="dd/MM/yyyy hh:mm" /></b></td></tr>

<tr><td>Nice Format:</td><td><b><s:date name="todayDate" format="yyyy-MM-dd" nice="true"/></b></td></tr>

</s:form>

</body>

</html>

Output of the program:

In this section you learnt how to use Struts 2 Date format tag.

Struts 2 datetimepicker Example

Page 222: 23277934-STRUTS2-ROSEINDIA

In this section we will show you how to develop datetimepicker in struts 2. Struts 2 uses the dojo toolkit for creating date picker. In Struts 2 its very easy to create date time picker.

The <s:datetimepicker .../> tag

The Struts 2 <s:datetimepicker ...> actually renders date/time picker in the dropdown container. When user clicks on the calendar icon the date/time picker is displayed on the form.

Struts 2 date picker is actually Dojo widget, that makes it easy to select a date. It also provides easy way to select any date/month/year very fast. The date time picker will make your web application very user friendly.

Writing time picker code

Action class to get today's date is DateBean. Here is the code of DateBean.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

/** * <p> Validate a user login. </p> */public class DateBean extends ActionSupport {

public String execute() throws Exception {

setTodayDate(new Date()); return SUCCESS;

}

// ---- Username property ----

/** * <p>Field to store Today's Date.</p> * <p/> */ private Date todayDate;

/** * <p>Provide Today's Date.</p> * * @return Returns the Todays date. */ public Date getTodayDate() { return todayDate; }

/** * <p>Store new Date</p> * * @param value The username to set.

Page 223: 23277934-STRUTS2-ROSEINDIA

*/ public void setTodayDate(Date value) { todayDate = value; }

}

Add the following entry in the struts.xml file in order to create action mapping:

<action name="DateTimePicker" class="net.roseindia.DateBean"><result>/pages/datepicker.jsp</result></action>

Following jsp file(datepicker.jsp) shows the usage of datepicker tag:

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Format Date Example!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/>

<s:head theme="ajax" />

</head><body>

<s:form action="DateTimePicker" method="POST">

<s:datetimepicker name="todayDate" label="Format (yyyy-MM-dd)" displayFormat="yyyy-MM-dd"/>

<s:datetimepicker name="todayDate" label="Format (dd-MMM-yyyy)" displayFormat="dd-MMM-yyyy"/>

</s:form>

</body>

</html>

Struts 2 date picker is dojo widget so, it is necessary to generate the client side JavaScript code. The <s:head theme="ajax" /> generates the client side dojo specific java script. Here is the code generated by this tag:

<link rel="stylesheet" href="/struts2tutorial/struts/xhtml/styles.css" type="text/css"/><script language="JavaScript" type="text/javascript"> // Dojo configuration

Page 224: 23277934-STRUTS2-ROSEINDIA

djConfig = { baseRelativePath: "/struts2tutorial/struts/dojo", isDebug: false, bindEncoding: "UTF-8", debugAtAllCosts: true // not needed, but allows the Venkman debugger to work with the includes };</script><script language="JavaScript" type="text/javascript" src="/struts2tutorial/struts/dojo/dojo.js"></script><script language="JavaScript" type="text/javascript" src="/struts2tutorial/struts/simple/dojoRequire.js"></script><script language="JavaScript" type="text/javascript" src="/struts2tutorial/struts/ajax/dojoRequire.js"></script><script language="JavaScript" type="text/javascript" src="/struts2tutorial/struts/CommonFunctions.js"></script>

The code:

<s:datetimepicker name="todayDate" label="Format (yyyy-MM-dd)" displayFormat="yyyy-MM-dd"/>

generates the date/time picker on the form.

Following table summarizes the format by datepicker component: Format Descriptiondd This format is used to display day in two digits formatd Try to display day in one digit format, if cannot use 2 digit formatMM The format displays month in two digits formatM It try to display month in one digits format, if cannot use 2 digit formatyyyy Display year in four digits formatyy Display the last two digits of the yeary Display the last digits of the year

Here is the output of the program

Page 225: 23277934-STRUTS2-ROSEINDIA

In this section we have studied how to use Struts 2 datepicker control.

Struts 2 Format Examples

In this section you will learn how to format Date and numbers in Struts 2 Framework. Our Struts 2 Format Examples are very easy to grasp and you will learn these concepts in very small time.

If you start developing any real world web application, at some point of time you will delve into the problem of displaying the date and number in some specific format. You can easily write your code and then format the output as string in your action class. But there is some drawback it like:

• Your code are not aware of i18n. It will be very difficult to adapt to different locals.

• Your action class are also clutter with unnecessary code.

Struts 2 in-built formatting functionality can save you from above problem. You can use s:text tag built-in formatting functionality to format your date and numbers.

Steps to Develop Example code

Write Action class

In the action class we are creating three fields:

private String productName;private Double productCost;private Date orderDate;

The values in these variables will be used for displaying on the jsp page. Here is the code of action class (OrderBean.java):

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

Page 226: 23277934-STRUTS2-ROSEINDIA

/** * <p> Validate a user login. </p> */public class OrderBean extends ActionSupport {

private String productName; private Double productCost;

public String execute() throws Exception {

setOrderDate(new Date()); setProductName("ICE Cream"); setProductCost(102.08); return SUCCESS;

}

// ---- Order Date property ----

/** * <p>Field to store Today's Date.</p> * <p/> */ private Date orderDate;

/** * <p>Provide Today's Date.</p> * * @return Returns the Todays date. */ public Date getOrderDate() { return orderDate; }

/** * <p>Store new Date</p> * * @param value The Order date to set. */ public void setOrderDate(Date value) { orderDate = value; }

public Double getProductCost() { return productCost; }

public void setProductCost(Double productCost) { this.productCost = productCost; }

public String getProductName() { return productName; }

Page 227: 23277934-STRUTS2-ROSEINDIA

public void setProductName(String productName) { this.productName = productName; }

}

The execute method of action class populates Product Name, Product cost and Order date. public String execute() throws Exception {

setOrderDate(new Date()); setProductName("ICE Cream"); setProductCost(102.08); return SUCCESS;

}

Writing JSP page

In the following jsp page (struts2format.jsp) you can view the actual usage of the tag.

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Struts 2 Format Example!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"type="text/css"/>

</head><body>

<s:form action="Struts2Format" method="POST">

<tr><td align="right">Product Name:</td><td><b><s:text name="product.name"><s:param name="value" value="productName"/></s:text></b></td></tr>

<tr><td align="right">Product cost:</td><td><s:text name="product.cost" ><s:param name="value" value="productCost"/></s:text></td></tr>

Page 228: 23277934-STRUTS2-ROSEINDIA

<tr><td align="right">Order Date:</td><td><b><s:text name="product.orderDate"><s:param name="value" value="orderDate"/></s:text></b></td></tr>

</s:form>

</body>

</html>

Please note that the formatting for product.name, product.cost and product.orderDate are defined in the package.properties message resource file.

Defining the formatting in properties file

In Struts 2 the formatting is defined in the message resource file (package.properties). The package.properties file is saved in the directory (package) where your action class resides. Here is the content of package.properties file:

product.cost= USD {0,number,##0.00}product.orderDate = {0,date,dd-MMM-yyyy}product.name = {0}

So, you can easily define or change the formatting of output just modifying the properties file.

Modification in struts.xml

Add the following line in struts.xml file:

<action name="Struts2Format" class="net.roseindia.OrderBean"><result>/pages/struts2format.jsp</result></action>

To test the program, compile and package the code and then start tomcat. Type http://localhost:8080/struts2tutorial/roseindia/Struts2Format.action in the browser to view the result. Your browser should show the following output:

In this section you learnt how to use Struts 2 Format functionality.

Struts 2 File Upload

Page 229: 23277934-STRUTS2-ROSEINDIA

In this section you will learn how to write program in Struts 2 to upload the file on the server. In this example we are also providing the code to save the uploaded file in any directory on the server machine.

The Struts 2 FileUpload component can be used to upload the multipart file in your Struts 2 application. In this section you will learn about the code to upload file on the server.

How File Upload Works in Struts 2?

Struts 2 utilizes the service of File Upload Interceptor to add the support for uploading files in the Struts applications. The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element. Then it adds the following parameters to the request (assuming the uploaded file name is MyFile).

• [MyFile] : File - the actual File

• [MyFile]ContentType : String - the content type of the file

• [File Name]FileName : String - the actual name of the file uploaded (not the HTML name)

In the action class you can get the file, the uploaded file name and content type by just creating getter and setters. For example, setMyfile(File file), setMyFileContentType(String contentType), getMyFile(), etc..

The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:

• struts.messages.error.uploading - error when uploading of file fails

• struts.messages.error.file.too.large - error occurs when file size is large

• struts.messages.error.content.type.not.allowed - when the content type is not allowed

Parameters

You can use the following parameters to control the file upload functionality.

• maximumSize This parameter is optional. The default value of this is 2MB.

• allowedTypes This parameter is also optional. It allows you to specify the allowed content type.

Writing Example code to upload file

Now we will write the code to upload the file on server.

Action Class

In the action class we will define four properties to facilitate the file upload.private File upload; // The actual file

private String uploadContentType;// The content type of the file

private String uploadFileName;// The uploaded file name and path

private String fileCaption;// The caption of the file entered by user.

Here is the full code of action class StrutsFileUpload.java

package net.roseindia;

Page 230: 23277934-STRUTS2-ROSEINDIA

import java.util.Date;import java.io.File;import com.opensymphony.xwork2.ActionSupport;public class StrutsFileUpload extends ActionSupport { private File upload;//The actual file private String uploadContentType; //The content type of the file private String uploadFileName; //The uploaded file name private String fileCaption;//The caption of the file entered by user public String execute() throws Exception {

return SUCCESS;

} public String getFileCaption() { return fileCaption; } public void setFileCaption(String fileCaption) { this.fileCaption = fileCaption; } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; }

}

Here we have not shown the code to save the uploaded file. But it can be done easily using the following code in execute(..) method of action class. Here is code snippet. //Following code can be used to save the uploaded file

try {

String fullFileName = "c:/upload/myfile.txt";

File theFile = new File(fullFileName);

FileUtils.copyFile(upload, theFile);

} catch (Exception e) {

addActionError(e.getMessage());

return INPUT;

Page 231: 23277934-STRUTS2-ROSEINDIA

}

Writing JSP page

Here is the code of jsp file (upload.jsp) that displays the file upload form to the user.

<%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>File Upload Example</title><link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>

</head>

<body>

<s:actionerror /><s:fielderror /><s:form action="doUpload" method="POST" enctype="multipart/form-data"><tr><td colspan="2"><h1>File Upload Example</h1></td></tr>

<s:file name="upload" label="File"/><s:textfield name="caption" label="Caption"/><s:submit /></s:form></body></html>

In the above code the form encrypt type is "multipart/form-data" and <s:file ../> tag renders the html file tag.

File upload success page

Here is the code of file upload(upload-success.jsp) success page.

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><html><head><title>Showcase</title><link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/></head>

<body><table class="wwFormTable"><tr>

<td colspan="2"><h1>File Upload Example</h1></td>

Page 232: 23277934-STRUTS2-ROSEINDIA

</tr>

<tr><td class="tdLabel"><label for="doUpload_upload" class="label">Content Type:</label></td><td><s:property value="uploadContentType" /></td></tr>

<tr><td class="tdLabel"><label for="doUpload_upload" class="label">File Name:</label></td><td ><s:property value="uploadFileName" /></td></tr>

<tr><td class="tdLabel"><label for="doUpload_upload" class="label">File:</label></td><td><s:property value="upload" /></td></tr>

<tr><td class="tdLabel"><label for="doUpload_upload" class="label">File Caption:</label></td><td><s:property value="caption" /></td></tr>

</table>

</body></html>

Adding mapping in struts.xml file

Add the following mapping in the struts.xml file.

<!-- File Upload -->

<action name="showUpload"><result>/pages/upload.jsp</result></action>

<action name="doUpload" class="net.roseindia.StrutsFileUpload"><result name="input">/pages/upload.jsp</result><result>/pages/upload-success.jsp</result></action>

<!-- End File Upload -->

Page 233: 23277934-STRUTS2-ROSEINDIA

The "showUpload" action displays the upload form and "doUpload" action actually uploads the file.

Running the example

To test the application compile code and then run the tomcat. Type http://localhost:8080/struts2tutorial/roseindia/showUpload.action in your browser. You browser should show the following form:

Now browse the file, enter caption and then click on the "Submit" button. Application will upload your file and then following success screen will be displayed.

There is one important point to be noted about File Upload Interceptor. The File Upload Interceptor actually deletes the the upload, once the action is executed. Here is the screen shot of tomcat that shows the file delete message:

INFO: Removing file upload C:\apache-tomcat-6.0.10Struts2\apache-tomcat-6.0.10\work\Catalina\localhost\struts2tutorial\upload__13f532f7_1132e1d4754__8000_00000000.tmp

In this section you learnt the concept of file upload in struts 2.

Struts 2 Resources Examples

Static ParameterIn this section, we will develop a simple application to access the static parameters. We will use a JavaBean to set and get the static parameters. Each static parameter has a value.

Accessing Session ObjectIn this section, we will develop a simple application to access the framework resources like the session object, session context and the last accessed session time.

Page 234: 23277934-STRUTS2-ROSEINDIA

Access Request and Response In this section, you will learn to develop an application that accesses the request and response object in struts 2 application.

Static Parameter

In this section, we will develop a simple application to access the static parameters. We will use a JavaBean to set and get the static parameters. Each static parameter has a value.

Description :

Develop a JavaBean with three properties (Static Parameters) of string type ( parameter1,parameter2, parameter3 ). Define three JavaBean properties and add their corresponding values in the action mapping (in the application's struts.xml ). Set the name(s) and value(s) as shown below:

code snippet from struts.xml

<action name="StaticParameter" class="net.roseindia.StaticParameter"> <param name="pramater1">Value 1</param> <param name="pramater2">Value 2</param> <param name="pramater3">Value 3</param> <result>/pages/staticparameter/showparamerts.jsp</result></action>

Create a simple JavaBean StaticParameter.java in the "struts2tutorial\WEB-INF\src\java\net\roseindia" directory. Here the "StaticParameter" class extends the ActionSupport class. It sets and gets the three static parameters by using the setParameter1(), setParameter2(), setParameter3() and getParameter1(), getParameter2(), getParameter3() methods.

Now compile the JavaBean (StaticParameter.java) through the 'ant' command.

StaticParameter.java

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

public class StaticParameter extends ActionSupport {

private String pramater1; private String pramater2; private String pramater3; public String execute() throws Exception { return SUCCESS; }

public String getPramater1() { return pramater1; }

public void setPramater1(String pramater1) { this.pramater1 = pramater1; }

Page 235: 23277934-STRUTS2-ROSEINDIA

public String getPramater2() { return pramater2; }

public void setPramater2(String pramater2) { this.pramater2 = pramater2; }

public String getPramater3() { return pramater3; }

public void setPramater3(String pramater3) { this.pramater3 = pramater3; }

}

Create a jsp page (showparameters.jsp) to view the static parameters.

showparameters.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><html> <head> <title>Static Parameter Example!</title> </head> <body> <h1>Static Parameter</h1> <table border="1" width="25%" bgcolor="#ffffcc"> <tr> <td width="25%"><b>Key</b></td> <td width="25%"><b>Value</b></td> </tr> <tr> <td width="25%">pramater1</td> <td width="25%"><s:property value="pramater1" /></td> </tr> <tr> <td width="25%">pramater2</td> <td width="25%"><s:property value="pramater2" /></td> </tr> <tr> <td width="25%">pramater3</td> <td width="25%"><s:property value="pramater3" /></td> </tr> </table> </body></html>

Open web browser and give request as http://localhost:8080/struts2tutorial/roseindia/StaticParameter.action. It displays a table that contains three static parameters in key-value format.

Output of this application:

Page 236: 23277934-STRUTS2-ROSEINDIA

Accessing Session Object

In this section, we will develop a simple application to access the framework resources like the session object, session context and the last accessed session time. To access the session, you need an action class implementing the SessionAware interface and extending ActionSupport class.

org.apache.struts2.interceptor.SessionAware Interface: Actions that need access to the user's HTTP session should implement this interface. This interface is only relevant if the Action is used in a servlet environment. Note that using this interface makes the Action tied to a servlet environment, so it should be avoided if possible since things like unit testing will become more difficult.

Description:

add the following action snippet to the following struts.xml file.

struts.xml

<action name="GetSession" class="net.roseindia.GetSession"> <result>/pages/staticparameter/GetSession.jsp</result></action>

Now, create a JavaBean (GetSesstion.java). This is a simple POJO (Plain Old Java Object). Here, we implement SessionAware interface.

The setSession() method sets the session in a Map object. It is called at the running time.

GetSession.java

package net.roseindia;import org.apache.struts2.interceptor.SessionAware;

Page 237: 23277934-STRUTS2-ROSEINDIA

import com.opensymphony.xwork2.ActionSupport;import java.util.*;

public class GetSession extends ActionSupport implements SessionAware{

private Map session; public String execute() throws Exception{ return SUCCESS; }

public void setSession(Map session){ session = this.getSession(); }

public Map getSession(){ return session; }

}

Now, we create a jsp page for viewing the session object, session context and session time. The session object provides information about the session, getSessionContext() method provides the information about the session context and getLastAccessedTime() provides date and time when the last session is accessed.

GetSession.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><%@page language="java" import="java.util.*" %><html> <head> <title>Get Session Example!</title> </head> <body> <h1><span style="background-color: #FFFFcc"> Session Example! </span></h1> <b>Session:</b><%=session%><br> <b>Session Context: </b><%=session.getSessionContext() %><br> <b>Session Time: </b><%=new Date(session.getLastAccessedTime())%> </body></html>

Finally, open the web-browser and type the http://localhost:8080/struts2tutorial/roseindia/GetSession.action in the address bar. It displays the information about framework session, session context and last accessed session time.

Output of this application:

Page 238: 23277934-STRUTS2-ROSEINDIA

Access Request and Response

In this section, you will learn to develop an application that accesses the request and response object in struts 2 application. To access the request object , use the ActionContext or implement the ServletRequestAware interface and to access the response object, use the ActionContext or implement the ServletResponseAware interface.

Here, in this application, we are going to implement the ServletRequestAware and ServletResponseAware interfaces in our action class.

Accessing the request and response object, you need a struts.xml file.

struts.xml

<action name="AccessRequest" class="net.roseindia.AccessRequest"> <result>/pages/staticparameter/AccessRequest.jsp</result></action>

Now, create a simple action "AccessRequest.java "

Here we use the setServletRequest() (for setting the request object) and getServletRequest() (for getting the request object) methods of ServletRequestAware interface. Similarly, we use the setServletResponse() (for setting the response) and getServletResponse() (for getting the response) methods of ServletResponseAware interace.

AccessRequest.java

package net.roseindia;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.interceptor.ServletRequestAware;import org.apache.struts2.interceptor.ServletResponseAware;

public class AccessRequest extends ActionSupport implements

Page 239: 23277934-STRUTS2-ROSEINDIA

ServletRequestAware,ServletResponseAware{ private HttpServletRequest request; private HttpServletResponse response; public String execute() throws Exception{ return SUCCESS; } public void setServletRequest(HttpServletRequest request){ this.request = request; }

public HttpServletRequest getServletRequest(){ return request; }

public void setServletResponse(HttpServletResponse response){ this.response = response; }

public HttpServletResponse getServletResponse(){ return response; }}

Finally, create a jsp page for accessing the request and response object.

AccessRequest.jsp

<%@ taglib prefix="s" uri="/struts-tags" %><%@page language="java" import="java.util.*" %>

<html> <head> <title>Access Request and Response Example! </title> </head> <body> <h1><span style="background-color: #FFFFcc">Access Request and Response Example!</span></h1> <b>Request: </b><%=request%><br> <b>Response: </b><%=response%><br> <b>Date: </b><%=new Date()%> </body></html>

Open the web-browser and type the "http://localhost:8080/struts2tutorial/roseindia/AccessRequest.action" in the address bar and press the "enter key" it displays the access request and response object as well as accessed date and time.

Output of this application:

Page 240: 23277934-STRUTS2-ROSEINDIA

Struts 2 Ajax

In this section, we explain you Ajax based development in Struts 2. Struts 2 provides built-in support for Ajax using Dojo toolkit. This is one of the greatest feature added to the Struts 2 framework. Ajax allows the developers to develop GUI like web applications. In this section we will provide you many examples to use Ajax in Struts 2 applications.

1. Ajax Feature in Struts 2

2. Login Application Using Ajax This section provides you an easy and complete implementation of login form using the Ajax (DOJO). Lets develop a login application using Ajax. This login application first authenticates a user, it asks for a login name and password.

3. Login or Cancel Application Using Ajax This section provides you, an easy and complete implementation of login application with features like submit and cancel buttons using the Ajax (DOJO). This application also checks the user validation i.e. the logging user is valid or not.

Struts 2 Session ScopeIn this section, you will learn to create an AJAX application in Struts2 Framework that displays some messages with session

This section provides you an easy and complete implementation of login form using the Ajax (DOJO).

Lets develop a login application using Ajax. This login application first authenticates a user, it asks for a login name and password (Both the login name and password is "Admin"). It displays a welcome page, when both fields are correctly filled by the user. Otherwise it shows an error and DEBUG message (Invalid user name and password! Please try again! and DEBUG: widget ID collision on ID: ajaxLogin_0).

Create an action mapping in the struts.xml file. Here is the code to be added in the struts.xml:

<action

Page 241: 23277934-STRUTS2-ROSEINDIA

name="showAjaxLoginForm"> <result>/pages/ajaxlogin.jsp</result></action>

<action name="ajaxLogin" class="net.roseindia.Login"> <result name="input">/pages/ajaxlogin.jsp</result> <result name="error">/pages/ajaxlogin.jsp</result> <result>/pages/ajaxloginsuccess.jsp</result></action>

Develop a Login Form Using Ajax : The GUI of the application consists of a login form (ajaxlogin.jsp). The "ajaxlogin.jsp" displays the login page to the user. This jsp page uses the <s:div> tag, this tag creates a content area that can load its content using Ajax tags, optionally refreshing. Here we also use the <s:submit> tag that is used to update element (s) or submit a form with the help of Ajax.

Whenever an error occurs then the <s:actionerror> and <s:fielderror> tags execute and display an error message the login form is submitted.

Here is the code of ajaxlogin.jsp file:

<%@ taglib prefix="s" uri="/struts-tags"%><html> <head> <s:head theme="ajax" debug="true"/> </script> </head> <body> <s:div id="loginDiv" theme="ajax"> <div style="width: 300px;border-style: solid"> <s:form action="ajaxLogin" validate="true"> <tr> <td colspan="2"> Login </td> </tr> <tr> <td colspan="2"> <s:actionerror /> <s:fielderror /> </td> </tr> <s:textfield name="username" label="Login name"/> <s:password name="password" label="Password"/> <s:submit theme="ajax" targets="loginDiv" notifyTopics="/ajaxLogin"/>

Page 242: 23277934-STRUTS2-ROSEINDIA

</s:form> </div> </s:div> </body></html>

Develop an action class that handles the login request and checks for the user authentication. If the user name and password is "Admin" then it returns SUCCESS otherwise ERROR object.

Here is the code of "Login.java" action class:

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

/** * <p> Validate a user login. </p> */public class Login extends ActionSupport {

public String execute() throws Exception { System.out.println("Validating login"); if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){ addActionError("Invalid user name or password! Please try again!"); return ERROR; }else{ return SUCCESS; } }

// ---- Username property ----

/** * <p>Field to store User username.</p> * <p/> */ private String username = null;

/** * <p>Provide User username.</p> * * @return Returns the User username. */ public String getUsername() { return username; }

/** * <p>Store new User username</p> * * @param value The username to set. */

Page 243: 23277934-STRUTS2-ROSEINDIA

public void setUsername(String value) { username = value; }

// ---- Username property ----

/** * <p>Field to store User password.</p> * <p/> */ private String password = null;

/** * <p>Provide User password.</p> * * @return Returns the User password. */ public String getPassword() { return password; }

/** * <p>Store new User password</p> * * @param value The password to set. */ public void setPassword(String value) { password = value; }

}

The "ajaxloginsuccess.jsp" page displays the Login Success message (Welcome to Admin) when the user is successfully authenticated.

Here is the code of "ajaxloginsuccess.jsp" file:

<html> <head> <title>Login Success</title> </head> <body> <p align="center"><font color="#000080" size="5">Login Successful !</font></p> <h1> Welcome to <%=request.getParameter("username")%> </h1> </body></html>

Output of the Ajax login application:

When this application executes you get a login page:

Page 244: 23277934-STRUTS2-ROSEINDIA

If you leave the "Login name" field empty and just fills the "Password" field in the login page then a message is displayed as shown below:

If you fills the "Login name" field empty and just leaves the "Password" field empty in the login page then a message is displayed as shown below:

Page 245: 23277934-STRUTS2-ROSEINDIA

If you enter the wrong login name and password in the login page then it displays a message as shown below::

When you enter the correct login name and password to the login page, it shows a success message as shown :

Page 246: 23277934-STRUTS2-ROSEINDIA

Login or Cancel Application Using Ajax

This section provides you, an easy and complete implementation of login application with features like submit and cancel buttons using the Ajax (DOJO). This application also checks the user validation i.e. the logging user is valid or not.

Lets develop a login application using Ajax with features like submit and cancel buttons. This login application first authenticates a user, it asks the login name and password (Both the login name and password is "Admin") from the user. It displays a welcome page, when both fields are correctly filled by the user. Otherwise it displays an error and DEBUG messages (Invalid user name and password! Please try again! and DEBUG: widget ID collision on ID: ajaxLogin_0).

If you want to cancel the filled-up details from the form then click the "Cancel" button. After clicking, it again asks for the login name and password.

Create an action mapping in the struts.xml file. Here is the code to be added in the struts.xml:

<action name="showAjaxLoginCancelForm"> <result>/pages/ajaxloginCancel.jsp</result></action>

<action name="ajaxloginCancel" class="net.roseindia.Login"> <result name="input">/pages/ajaxloginCancel.jsp</result> <result name="error">/pages/ajaxloginCancel.jsp</result> <result name="cancel"

Page 247: 23277934-STRUTS2-ROSEINDIA

type="redirect">/pages/ajaxloginCancel.jsp</result> <result>/pages/ajaxloginsuccess.jsp</result></action>

Develop an action class that handles the login and cancel request and it also checks for the user authentication. If the user name and password is "Admin" then it returns SUCCESS otherwise ERROR strings. Whenever you click the "Cancel" button, it returns the NONE field (NONE field: The action execution was successful but did not show a view).

Here is the code of "Login.java" action class:

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import java.util.Date;

/** * <p> Validate a user login. </p> */public class Login extends ActionSupport {

public String execute() throws Exception { if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){ addActionError("Invalid user name or password! Please try again!"); return ERROR; } if(getUsername().equals("Admin") || getPassword().equals("Admin")){ return SUCCESS; }else{ return NONE; } }

// ---- Username property ----

/** * <p>Field to store User username.</p> * <p/> */ private String username = null;

/** * <p>Provide User username.</p> * * @return Returns the User username. */ public String getUsername() { return username; }

/** * <p>Store new User username</p>

Page 248: 23277934-STRUTS2-ROSEINDIA

* * @param value The username to set. */ public void setUsername(String value) { username = value; }

// ---- Username property ----

/** * <p>Field to store User password.</p> * <p/> */ private String password = null;

/** * <p>Provide User password.</p> * * @return Returns the User password. */ public String getPassword() { return password; }

/** * <p>Store new User password</p> * * @param value The password to set. */ public void setPassword(String value) { password = value; }

}

Develop a Login or Cancel Form Using Ajax : The GUI of the application consists of a login form (ajaxloginCancel.jsp). This jsp page uses the <s:div> tag, this tag creates a content area that can load its content using Ajax tags, optionally refreshing. Here we also use the <s:submit> tag that is used to update element (s) or submit a form with the help of Ajax. The "Cancel" button calls submit tag to notify an action to perform cancel operation.

Whenever an error occurs then the <s:actionerror> and <s:fielderror> tags execute and the page displays an error message.

Here is the code of ajaxloginCancel.jsp file:

<%@ taglib prefix="s" uri="/struts-tags"%><html> <head> <s:head theme="ajax" debug="true"/> </head> <body> <s:div id="loginDiv" theme="ajax"> <div style="width: 300px;border-style: solid"> <s:form action="ajaxloginCancel" validate="true">

Page 249: 23277934-STRUTS2-ROSEINDIA

<tr> <td colspan="2"> Login </td> </tr> <tr> <td colspan="2"> <s:actionerror /> <s:fielderror /> </td> <s:textfield name="username" label="Login name"/> <s:password name="password" label="Password"/> <s:submit value="Submit" theme="ajax" targets="loginDiv" notifyTopics="/ajaxloginCancel"/> <s:submit action="showAjaxLoginCancelForm" value="Cancel"

onclick="form.onsubmit=null"/> </s:form> </div> </s:div> </body></html>

The "ajaxloginsuccess.jsp" page displays the Login Success message (Welcome to Admin) when the user is successfully authenticated.

Here is the code of "ajaxloginsuccess.jsp" file:

<html> <head> <title>Login Success</title> </head> <body> <p align="center"><font color="#000080" size="5">Login Successful !</font></p> <h1> Welcome to <%=request.getParameter("username")%> </h1> </body></html>

Output of the ajax login or cancel application:

When this application executes you get a login page as shown:

Page 250: 23277934-STRUTS2-ROSEINDIA

If you leave the "Login name" and "password" field empty in the login page then a message is displayed as shown below:

If you leave the "Login name" field empty and just fills the "Password" field in the login page then a message is displayed as shown below:

Page 251: 23277934-STRUTS2-ROSEINDIA

If you fill the "Login name" field empty and just leaves the "Password" field empty in the login page then a message is displayed as shown below:

Page 252: 23277934-STRUTS2-ROSEINDIA

If you enter the wrong login name and password in the login page then it displays a message as shown below:

After clicking the "Cancel" button, you get the following:

Page 253: 23277934-STRUTS2-ROSEINDIA

When you enter the correct login name and password to the login page:

Displays a success message as shown:

Struts 2 Session Scope

In this section, you will learn to create an AJAX application in Struts2 Framework that displays some messages with session.

The current application displays a jsp page having the two text fields. If the user enters nothing in the text fields and submit the form it displays an error message "nothing entered".

Page 254: 23277934-STRUTS2-ROSEINDIA

If the user enters some text in the WELCOME1 field, then the corresponding attribute is set to "welcome1". If the user leaves the WELCOME1 field empty and enters some text in the WELCOME2 field, then the corresponding attribute is set to "welcome2".

This application is created with AJAX in Struts2 Framework. Before we start the things, we need to do the following:

1. Download Struts2 from Apache.org

2. Deploy the jars under Tomcat server WEB-INF/lib

3. Rename the jars containing "plug-in" (this is very important as our application doesn't need any plugin's and Tomcat class loader sometimes fails to find the class files associated with the plugin's)

4. Make sure the Tomcat server is the latest (Tomcat 5.5.0 and above)

5. Download xwork-2.0.4.jar from opensymphony.com as it is not available with the Struts2 distribution.

The struts.xml file contains the information about the files, constants, packages and actions to be included. The <include file> tag provides standard information provided by Struts2. The <constant> tags are also there, you may set the struts.devMode constant to true, but it is not necessary. The package tag specifies a name, namespace and extends attributes.

Pay attention to namespace as it affects the URL you have to type in the browser. If you give a namespace say "/roseindia" then your URL will be "http://localhost:8080/struts2tutorial/roseindia/showAjaxTestActionForm.action".

To make it simpler as we don't have many packages we have set the namespace to blank so that we need only use the URL "http://localhost:8080/struts2tutorial/roseindia/showAjaxTestActionForm.action"

The action with name showAjaxTestActionForm shows in the view AjaxTest.jsp. Note that the pages don't have to be in the classpath.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<!-- Rose India Struts 2 Tutorials --><constant name="struts.enable.DynamicMethodInvocation" value="false" /><constant name="struts.devMode" value="true" />

<include file="struts-default.xml"/><package name="roseindia" namespace="/roseindia"

Page 255: 23277934-STRUTS2-ROSEINDIA

extends="struts-default">

<action name="showAjaxTestActionForm"><result>/pages/AjaxTest.jsp</result></action><action name="AjaxTestAction" class="net.roseindia.SampleForm"><result name="error">/pages/AjaxTest.jsp</result><result name="success">/pages/AjaxTest.jsp</result><result>/pages/AjaxTest.jsp</result></action>

<!-- Add actions here --></package>

<!-- Add packages here -->

</struts>

The action AjaxTestAction is the form action attribute. It is associated with the support class net.roseindia.SampleForm which is in the class path. The result tags mean as follows:

• If the class returns "error" then show the error message set in the Java class in the view.

• If the class returns "success" then update the view.

• If the class returns nothing then update the view.

The JSP file contains a form, two text fields and a submit button. The <s:actionerror>, <s:fielderror> and <s:actionmessage> tags will display the errors associated while processing this form. The <s:div id="loginDiv" theme="ajax"> tag prints a message at the top of the view indicating which textfield has been set. It displays a message from the session's set attribute.

Here is the code for the JSP form: AjaxTest.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>

<html> <head> <s:head theme="ajax" debug="true"/> </head> <body> <s:div id="loginDiv" theme="ajax"> <h3> Your Session: <s:property value="#session.ret" /></h3> <div style="width: 300px;border-style: solid"> <s:form action="AjaxTestAction" validate="false"> <tr> <td colspan="2"> Run Test </td> </tr> <tr> <td colspan="2"> <s:actionerror /> <s:fielderror />

Page 256: 23277934-STRUTS2-ROSEINDIA

<s:actionmessage/> </td> <s:textfield name="welcome1" label="WELCOME1"/> <s:textfield name="welcome2" label="WELCOME2"/> <s:submit value="Submit" theme="ajax" targets="loginDiv" notifyTopics="/AjaxTestAction"/> </tr> </s:form> </div> </s:div> </body></html>

The following java class extends the ActionSupport class that implements the SessionAware interface. This way we can get the best of the both worlds because SessionAware will add attributes to the session that can be accessed from the JSP. In our case it will be the "ret" attribute. The setter and getter methods are straightforward.

Here is the code of SampleForm.java:

package net.roseindia;import com.opensymphony.xwork2.ActionSupport;import org.apache.struts2.interceptor.SessionAware;import java.util.Map;

public class SampleForm extends ActionSupport implements SessionAware{ //Fields that hold data private String Welcome1=""; private String Welcome2=""; private Map session;

public String execute() throws Exception { if (getWelcome1().trim().equals("") && getWelcome2().trim().equals("")){ addActionError("nothing entered"); return ERROR; } if (!getWelcome1().trim().equals("") && !getWelcome2().trim().equals("")){ addActionMessage("Both have data!"); return ERROR; } if (!getWelcome1().trim().equals("")){ getSession().put("ret", "welcome1"); addActionMessage("Welcome 2 is empty!"); return ERROR; } if (!getWelcome2().trim().equals("")){ getSession().put("ret", "welcome2"); addActionMessage("Welcome 1 is empty!"); return ERROR; } return SUCCESS; } public void setWelcome1(String s) { this.Welcome1= s; }

Page 257: 23277934-STRUTS2-ROSEINDIA

public String getWelcome1() { return Welcome1; }

public void setWelcome2(String s) { this.Welcome2= s; } public String getWelcome2() { return Welcome2; }

public void setSession(Map session) { this.session = session; } public Map getSession() { return session; }

}

Compile the class, start the Tomcat, and test the application by typing the following URL on the address bar of web browser: "http://localhost:8080/struts2tutorial/roseindia/showAjaxTestActionForm.action"

Output:

When this application executes you get a page as shown:

If you leave the "WELCOME1" and "WELCOME2" field empty then a message is displayed with session as shown below:

Page 258: 23277934-STRUTS2-ROSEINDIA

After clicking the "Submit" button then you get:

If you leave the "WELCOME1" field empty and just fill the "WELCOME2" field then a message is displayed with session as shown below:

Page 259: 23277934-STRUTS2-ROSEINDIA

If you fill the "WELCOME1" field and just leave the "WELCOME2" field empty then a message is displayed with session as shown below:

Page 260: 23277934-STRUTS2-ROSEINDIA

If you fill both field then you get:

Page 261: 23277934-STRUTS2-ROSEINDIA