Manual Struts 2 Tutorial for beginners.docx

Embed Size (px)

Citation preview

Struts 2 Tutorial for beginnersPosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial,Struts-2|25 comments

Introduction to Struts 2 FrameworkIn this course we will learn how to use Struts 2 to create an MVC based Java web application.Struts 2 is a framework for developing MVC based web applications in Java. When building a complex web application it is often difficult to keep business and view logic separate from each other. In this course we will learn how to create a Java based web application using the Struts 2 MVC framework to cleanly separate our views from business logic.We will cover important features of Struts 2 like creating Actions and mapping them to Results. We will also learn how to use OGNL to access data from Java objects inside of our Views and even see how to create AJAX style views. If you are interesting in learning Struts 2, this course is a great start point to get you started by building your first Struts 2 application.Struts 2 Complete Tutorial Model 1 and Model 2 (MVC) Architecture

Introduction to Struts 2 Framework Struts 2 Environment SetupStruts 2 Quick Start Hello world in struts 2 Getting Started Concept of Servlets Vs Concept of Struts 2 Roles of Actions class in Struts 2 Struts2 Configuration file and its roles Architecture overview of Struts 2 DispatchAction Functionality in struts2 Dynamic Method Invocation using Action WildcardsNon Form UI Tags Struts 2 ActionError & ActionMessage Example Struts 2 FieldError ExampleStruts 2 Configurations Understanding Namespace configuration example and explanation Multiple Struts configuration files example Struts2 Custom extension example Struts 2 Development modeStruts 2 Model driven JavaBean class as a property in struts 2 action class.

Struts 2 ModelDriven exampleStruts 2 File Manipulation Tutorial Struts 2 File Upload example How to override struts 2.x file upload error messages? Struts 2 File Download ExampleStruts 2 UI Tags TextBox example Password example Hidden value example Textarea example head example Datetimepicker example Datetimepicker using Jquery Struts 2 Autocompleter Textbox & dropdown exampleStruts 2 Control Tags Struts 2 If, Else, ElseIf Tag example Struts 2 iterator tag exampleStruts 2 Data Tags bean tag example push tag example debug Tag Example Url tag exampleInterceptors in Struts 2 Interceptors in Struts 2 Creating Custom Interceptors in Struts2 Login Interceptor in Struts 2Struts 2 + Display tag Struts 2 Pagination example Struts 2 tag not working inside a Display tag Solution How to get checkbox values from displaytag using struts2 Displaytag export option is not working- SolutionStruts 2 Theme Tips to Override Default Theme in Struts 2 ?

Ajax implementation in Struts 2 Ajax implementation in Struts 2 without jQuery AJAX implementation in Struts 2 using JQuery and JSON Autocomplete in Struts 2 using Jquery and JSON via Ajax Integrating jQuery DataTable with Struts2 using Ajax to implement GridviewStruts 2 + jTable Plugin Integrating jQuery jTable plugin with Struts 2 framework CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax Pagination in Struts 2 using jQuery jTable pluginStruts 2 Integrate with Other Frameworks Struts 2 + Spring integration example Struts 2 + Log4j integration example Struts2-Jfreechart integration Struts 2 and Tiles Framework Integration Integrating Quartz Scheduler in Struts 2 Web ApplicationStruts 2 FAQ Difference Between Struts 2 FilterDispatcher And StrutsPrepareAndExecuteFilter How to exclude action methods from validation in struts2 How To Get The ServletContext In Struts 2 Action Chaining and Action redirect Difference between # , $ and % signs in Struts2 Handling Exception in Struts 2 Example to Call Struts2 action from java script Dynamically add, remove list of objects from jsp Using Struts2 Changing default style of s:actionerror / s:actionmessage tag Common Support class for Action classes in Struts 2Struts 2 Errors There is no Action mapped for namespace / and action name yourActionNameStruts 2 Reference Struts 2 Official Documentation

Model 1 and Model 2 (MVC) ArchitecturePosted byMohaideen Jamilon Jan 14, 2014 inJava,Servlet,Struts 1,Struts-2|1 comment

MisconceptionsStudent:Master, what is the difference between MVC 1 and MVC 2 ?Master:Grasshopper, there is no such thing as MVC 1 and MVC 2, theres just MVC. if you meant to ask about the difference between Model 1 and Model 2 with respect to web applications, then this article will help you out.In Java there are two types of programming models1. Model 1 Architecture2. Model 2 (MVC) Architecture** UPDATE: Struts 2 Complete tutorial now availablehere.Model 1 Architecture

Flow of the Model 1 architecture.1. Browser sends request for the JSP page2. JSP accesses Business service Bean class and invokes business logic3. Business service Bean class connects to the database to store/retrieve data4. Response generated by JSP is sent to the browserDisadvantageNavigation control is decentralizedModel 2 (MVC) Architecture

Model 2 is based on the MVC (Model View Controller) design pattern. Model Represents the data and business logic of the application. View Represents the presentation. Controller The controller module acts as an interface between view and model.It intercepts all the requests i.e. receives input and commands to Model / View tochange accordingly.Advantage of Model 2 (MVC) Architecture Navigation control is centralized(Controller only has the control to determine the next page) Easy to maintain, extend and test.Disadvantage of Model 2 (MVC) ArchitectureIf we change the controller code, we need to recompile the class and redeploy the application.

Introduction to Struts 2 FrameworkPosted byMohaideen Jamilon Mar 20, 2014 inStruts-2|0 commentsIn our last article we have learned about the difference betweenModel 1 and Model 2 (MVC) Architecture.In this article we will learn about Struts 2 framework and about theArchitecturewhich it follows.In general if you are about to build a standard application using JSP and Servlets, then you will end up in a followingMVCpattern.

** UPDATE:Struts 2 Complete tutorial now availablehere.Why web Framework ?Web framework is a basic ready made underlying ofMVCstructure, where you have to just add components related to your business. It forces the team to implement their code in a standard way. (helpsdebugging, fewer bugs etc).Step involved in building a framework.Step 1: Router to route the request to the correct MODEL and correct View layerStep 2: Handle the request parametersStep 3: Create a interface class(Model) for business service classStep 4: View part(Jsp) to render the resultThe above steps are depicted photographically below.

Struts 2 developers have identified all these modules and had builded the same. Below is how a struts 2 design will look like.

HereInterceptoris the gate way through which a request is passed. It takes care of getting user request parameters,Struts 2 framework get all the request parameters from interceptor and makes it available forAction classand we dont need to fetch it in the action class via any request or session objects like we do inServlets, because struts 2 makes it available.HereStruts.xmlacts as controller which Controls the execution flow of the request, Action class represents Model and JSP represent View layer.Note:In struts 2 the data can be displayed in jsp with tab library,In our next tutorial, we will learn toset up struts 2 environment in eclipse.Struts 2 Environment SetupPosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|0 comments

In our previous tutorial we got introduced towhat a framework is, and why we go for struts 2. In this tutorial you will learn how to setup development environment for Struts 2 Framework.Environment Used JDK 7 (Java SE 7) Eclipse JUNO IDE Apache Tomcat 7.x Struts 2 jarsSetting up development environmentTo install Eclipse IDE and to configure Apache Tomcatread this pageStruts 2 Framework library download:Downloading Struts 2 Framework:It is available for downloading straight from its official site. The latest version of this framework for this day is 2.3.8Simply go tohttp://struts.apache.org/.ChooseStruts-2.3.8Download option as shown on the picture below:

Extracting Struts 2 download:Now extract the downloaded file (struts-2.3.8-all.zip) into your favourite. Say, D:\\Struts 2.3.8-all\And download latest version eclipse fromhttp://www.eclipse.org/, once installed** UPDATE: Struts 2 Complete tutorial now availablehere.

Create a Dynamic Web Project:Nowcreate a new Dynamic web projectusing the following option:File > New > Dynamic Web Projectand enter project name asLoginStruts2and set rest of the options as given in the following screen:

Now copy following files from struts 2 lib folderD:\struts-2.3.8-all\libto our projectsWEB-INF\libfolder.

Now restart your tomcat server or build and clean it.Thats all on how to create a Struts 2 project in eclipse, in our next article we shall learn to implement a basichello world program in struts 2

Hello world in Struts 2 Getting startedPosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|1 commentIn our previous article we learnt that there are4 basic component in struts 2 framework.They are1.struts.xml2.Interceptors3.Action class4. JSP

Sinceinterceptormodule is available in struts 2 by default, so for simplicity lets us ignore this module as of now and we shall explore then latter.Now ignoring interceptors the flow diagram of struts 2 looks as below.

Now create aDynamic web projectwith the following folder structure.Include the below list of commonly used JAR files required by Struts 2 framework to your projects WEB-INF/lib folder.

commons-fileupload-1.2.2.jar commons-io-2.0.1.jar commons-lang-2.4.jar commons-lang3-3.1.jar commons-logging-1.1.1.jar commons-logging-api-1.1.jar freemarker-2.3.19.jar javassist-3.11.0.GA.jar ognl-3.0.6.jar struts2-core-2.3.8.jar xwork-core-2.3.8.jar

Now the role of struts.xml here is to Controls the execution flow of the request1. It maps the input URL to the action classes2. It maps the input URL to the Jsp

Now consider a scenario where i receive the input request ashttp://localhost/login, in this case I need this request to be mapped to a Action class, let assume that action class to be LoginAction.

Which Method ?In case of Servlets when a servlet got invoked, then by either doget() or dopost() method will get invoked. But in case of struts 2, when an action class gets invoked then by default execute method will executed, provided the signature of this execute method should be as belowpublic String execute()

We can haveother method configured in Action class, we will learn about that in our upcoming tutorialsConfiguring request in struts.xmlThe struts.xml file needs to be configured with these basictags, and this file should always present in src folder.

When a clients request matches the action name, the framework uses the mapping fromstruts.xmlfile to process the request. The mapping to an action is usually generated by a Struts Tag. The action tag ( struts.xml file) specifies the action class to be executed.Here the configuration in struts.xml is incomplete, I have just mapped the request to Action class and we need to map the response from our action class to jsp, once after creating action class we shall come back to configuring struts.xml again.Note In struts.xml we declare a package and wrap the action classes inside. package name= default? Just give any valid unique name. struts-default? By default, this package extends from struts-default base package, and it is nothing but an xml file present in struts2-core-2.x.x.jar This xml is responsible for invoking series of interceptors which is configured in it. We shall explore aboutwhat is role of this struts-default?andwhat is interceptors?in our latter part of our tutorial series. As of now forget about it :P :)Action classpackage com.action;

public class LoginAction {

private String userName;

public String execute() { if (userName.isEmpty()) { return "error"; } else { return "success"; } }

public String getUserName() { return userName; }

public void setUserName(String userName) { this.userName = userName; }}Now note that the Action Class returns a string, which can be either success or error. In struts 2, the controller maps the response from action class to a jsp using this string.Lets assume if Action class return success then we need to map the response to success page. If Action class returns error then we need to map its response to error.jsp.

Note: The Action class in struts 2 is not required to implement any interface or extend any class i.e, can be simple POJO, and there arefour different ways to create an Action classwhich we shall explore in our upcoming tutorials. In case ofstruts 1 Action classused will be extending several classes in turn in order to process request and response.Configuring Response struts.xmlEarlier we have configured request flow in struts.xml now we have to configure the response via result tag in it as shown below.

success.jsp error.jsp

Jsp pagesNow lets go a head and create jsp pages to receive request and send response back.Create a new JSP file login.jsp inside the WebContent folder and type in the below code in this JSP file.File : login.jspuse the Struts 2 tags to display username input fields and submit button.File: login.jsp

Login

Struts 2 Hello World

In Struts 2, the userName will map to the JavaBean property of Action class automatically. In this case, on form submit, the textbox value with name=userName will call the corresponding Actions setUserName(String xx) to set the value We shall explore different types of tags used in struts 2 in our tutorials. Also Note that I have referred taglib at the beginning of jsp, By defenision the Struts Taglib component provides a set of JSP custom tag libraries that help developers create interactive form-based applications. There are several different tags to help with everything from displaying error messages to dealing with nested ActionForm beans.file : success.jsp: A JSP view page to display a welcome message to user.

Welcome Page

Hello

file :error.jsp: A JSP view page to display error message when a wrong user id and password is entered.

Error Page

Login failed

Configuring web.xmlweb.xmlis the entry point for any request sent, hence in order to indicate web.xml that this is a struts2 project, and to indicate that the request and response are handled in struts.xml, we have to provide any filter entry in web.xml file as shown below.

Struts2 struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* login.jsp

That all on building a struts 2 project, now lets go a head and run this application inTomCat ServerDemoSince I have given welcome file to be login.jsp in my web.xml, so on running the application in tomcat the login.jsp gets rendered as shown below.Url: http://localhost:8089/HelloWorldStruts2/

When you give a non empty value in userName then success page appears

If you have not entered any value for userName then error page appears as shown below.

In our next article we will learn about theconceptional difference between struts 2 and servletsConcept of Servlets Vs Concept of Struts 2Posted byMohaideen Jamilon Dec 22, 2013 inJava,Servlet,Struts 2 Tutorial,Struts-2|2 commentsIn our previous article we have created ahello world program in struts2, in which I have passed parameter from request and setted in action class via a member variable, which may led you in some confusion, since in case of servlets the member variable in it are shared between all request and only those variable inside doget and dopost methods remains unique. So inorder to know why a member variable in struts 2 remains unique per request, we have look into the conceptual difference betweenServletsand Struts 2. This article deals with the same.

** UPDATE: Struts 2 Complete tutorial now availablehere.In case of Servlet when we have N number of request then only one object is created out of which N number of Threads are created , in which a request object is created. So the objects inside the thread are safe and not shared with other thread objects.But suppose if the Servlet has Member variable, then those variable are not thread safe, as they are shared between all the threads created for each request.The above concept is depicted pictographically below.

Recommended Article Interceptors in Struts 2 Creating Custom Interceptors in Struts2Note: Servlet & Struts 1 follows same concept.In case of struts 2 for N number of request N number of object is created. So in this case, even the member variable for these objects are not shared between objects of other request, that the reason Struts 2 is said to be thread safe.The concept of Struts 2 is depicted pictographically as below.

In our next article we shall learn about theroles of Action class in struts 2.Roles of Actions class in Struts 2Posted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial,Struts-2|0 comments

The functionality of the action class is to retrieve resource bundle, hold the data, provide validation, perform business logic and select the view result page that should be sent back to the user.

There are four different ways to write struts 2 action class , which are as follows1. ActionFor Struts 2 actions, it is not mandatory to implement any interface or extend any class. It is only required to implementexecute()method that returns a string which is to be used instruts.xml, to indicate the result page that has to be rendered(return)** UPDATE: Struts 2 Complete tutorial now availablehere.package com.action;public class LoginAction{ public String execute() { return "success"; }}In thestruts.xml, configure the action class withaction tagandclass attribute. Define which result page should be returned to the user withresult tagand the name of the action you can use to access this action class withname attribute.

success.jsp

Now you can access the action via

http://localhost:8089/StrutsLogin/loginNote :To change the extension to any value that suits your need, view Struts2 Custom extension example.

2. Action interfaceThe second way of creatingAction classon Struts 2 is to implement an optional action interface (com.opensymphony.xwork2.Action).This interface , comes with 5 common used constant values :success, error, none, input and logic. By implements this interface, the action class can use the constant value directly.The Source code for Action interface :package com.opensymphony.xwork2;public interface Action { public static final String SUCCESS = "success"; public static final String NONE = "none"; public static final String ERROR = "error"; public static final String INPUT = "input"; public static final String LOGIN = "login"; public String execute() throws Exception;}Example: Struts 2 Action class implementing Action interfacepackage com.action;import com.opensymphony.xwork2.Action;public class LoginAction implements Action{ public String execute() { return SUCCESS; }}3. ActionSupportThe third way of creatingAction classon Struts 2 is to extend the ActionSupport class (com.opensymphony.xwork2.ActionSupport). The ActionSupport class is a very powerful and convenient class that provides default implementation of few of the important interfaces :public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {...}Note:Instead of implementing Action interface, it is better to extend the ActionSupport, Since the ActionSupport class implements Action interface along with other useful interfaces.

TheActionSupportclass give you the ability to do :1. ValidationDeclare a validate() method and put the validation code inside.2. Text localizationUse GetText() method to get the message from resource bundle.LoginAction.properties, (The resource bundle name must be same as Action class name with the extension .properties), and should be in the same folder where the action class liesNote :We will get to know about what is property file and the use ofaddFiendError, and use of other functionality likeaddActionErrorandaddActionMessagein our upcoming tutorials.

Example: Struts 2 Action class extending ActionSupport classpackage com.action;import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {private static final long serialVersionUID = 6677091252031583948L;private String userName;

public String execute() { return SUCCESS; }

public String getUserName() { return userName; }

public void setUserName(String userName) { this.userName = userName; }

public void validate() { if (!userName.isEmpty()) { addFieldError("userName", getText("username.required")); } }}** UPDATE: Android Complete tutorial now availablehere.4. Action annotationStruts 2 has very good support for annotations, you can get rid of the XML file and replace with@actionin your action class.package com.simplecode.action;import org.apache.struts2.convention.annotation.Action;import org.apache.struts2.convention.annotation.Namespace;import org.apache.struts2.convention.annotation.Result;import org.apache.struts2.convention.annotation.ResultPath;import com.opensymphony.xwork2.ActionSupport;@ResultPath(value="/")public class LoginAction extends ActionSupport{ @Action(value="login", results={@Result(name="success", location="success.jsp")}) public String execute() { return SUCCESS; }}Struts2 Configuration file and its rolesPosted byMohaideen Jamilon Mar 15, 2013 inStruts 2 Tutorial,Struts-2|0 commentsStruts 2 application is mainly dependent on two configuration files.1. web.xml2. struts.xml

1. web.xmlweb.xml is common for all J2EE application and in case of Struts 2, it is used in the configuration ofStrutsPrepareAndExecuteFilter,TilesListeneretc.When any request comes for struts web application, that request is first handled by web.xml file, where we do an entry forStrutsPrepareAndExecuteFilter, which dispatch a request object to appropriate action name.StrutsPrepareAndExecuteFilter is having following responsibility :1. Executing struts actions name2. Cleaning up theActionContext3. Serving static content4. Invokinginterceptorchain for the request life-cycleWe are defining StrutsPrepareAndExecuteFilter entry in web.xml as: struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* Note :We dont have to do an entry for taglib of struts in web.xml file because its already included into struts-core.jar file, so container automatically discover it .

Do read : Introduction to Struts 2 Framework Interceptors in Struts 2 Creating Custom Interceptors in Struts2 Login Interceptor in Struts 2

2. struts.xmlThe struts.xml file contains information about all theAction classesof application, configuredinterceptorsfor each Action class, Result for each Action execution. This file also describes the package structure of the application in which different modules are defined. Application specific constant like resource file,devMode,custom extension,theme settingsalso configured in this file. Below is the sample struts.xml file. All terms will be explained in their respective article.** UPDATE: Struts 2 Complete tutorial now availablehere.

success.jsp error.jsp

Architecture overview of Struts 2 and how it worksPosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|6 comments

Struts Execution Flow Diagram

The articleConcept of Servlets Vs Concept of Struts 2helps you in understanding the concepts of struts 2 better.Execution flow of struts2The flow starts with the web browser placing a request for a particular resource. This request is received by the web container. The container loadsweb.xmland checks if the url patterns match. If it matches, the web container transfers the request to Filter Dispatcher.The Filter Dispatcher decides the suitable action , by calling the ActionMapper , which in turn calls the ActionProxy. ActionProxy reads theconfiguration filesuch asstruts.xml, and finds the suitable action for the request. ActionProxy creates an instance of ActionInvocation class. The ActionInvocation class invokes theInterceptorsone by one (if required).Do Read Concept of Interceptors in Struts 2The Interceptors use the required functions and after that, the Action method executes all the functions like storing and retrieving data from a database. ActionInvocation receives the final result produced by anaction class.Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. TheInterceptorsare executed again in reverse order and the response is returned from ActionProxy to the Filter (In most cases to FilterDispatcher). FilterDispatcher selects an appropriate view, basing on the result. The result is then sent to the servlet container which in turn sends it back to the client. Then the result can be seen on the output of the browser in HTML, PDF, images or any other format.The other important features of Struts 2 are ValueStack & OGNL. Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL expression language provides simplified syntax to reference java objects. It helps in data transfer and type conversion by binding the java-side data properties to the string-based view layer.

** UPDATE: Struts 2 Complete tutorial now availablehere.In Struts 2 the action resides on the ValueStack which is a part of theActionContext. ActionContext is a global storage area that holds all the data associated with the processing of a request.When a request comes theparaminterceptor helps in moving the request data to the ValueStack. Now the OGNL does the job of converting the string based form data to their corresponding java types. OGNL does this by using the set of availablebuilt-in type converters.Again when the results are generated the OGNL converts the java types of the property on the ValueStack to the string-based HTML output.Here for N number of request N number of object is created, this makes the Struts 2 actionsthread safe.The articleServlets Vs Concept of Struts 2helps you in understanding the concepts of struts 2 better.

DispatchAction Functionality in Struts 2Posted byMohaideen Jamilon Sep 12, 2013 inStruts 2 Tutorial,Struts-2|10 commentsIn Struts 1 DispatchAction helps us in grouping a set of related functions into a single action. In Struts 2 all the Actions by default provide this functionality. To use this functionality we need to create different methods with the similar signature of the execute() method.

In our example the CalculatorAction class has all the methods related to a Calculator like add(), multiply(), division() and subtract() which are used for performing mathematical operation on two numbers and it displays the result in a single jsp based on the action button clicked in jsp.** UPDATE: Struts 2 Complete tutorial now availablehere.Action Classpackage com.simplecode.action;

import com.opensymphony.xwork2.Action;

public class CalculatorAction implements Action { private float number1;private float number2;private float result;private String methodName;

public String execute() { number1 = 0; number2 = 0; result = 0; setMethodName("execute Method"); return SUCCESS; }

public String add() { result=number1+number2; setMethodName("add Method"); return SUCCESS; }

public String subtract() { result = number1 - number2; setMethodName("subtract Method"); return SUCCESS; }

public String multiply() { result = number1 * number2; setMethodName("multiply Method"); return SUCCESS; }

public String divide() { if(number2!=0) result = number1/number2; else if(number1!=0) result = number2/number1; else result=0; setMethodName("divide Method"); return SUCCESS; }

public float getNumber1() { return number1; }

public void setNumber1(float number1) { this.number1 = number1; }

public float getNumber2() { return number2; }

public void setNumber2(float number2) { this.number2 = number2; }

public float getResult() { return result; }

public void setResult(float result) { this.result = result; }

public String getMethodName() { return methodName; }

public void setMethodName(String methodName) { this.methodName = methodName; }}Recommended Article GridView in struts 2 using jQuery DataTable plugin CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax Autocomplete in Struts 2 using Jquery via Ajax Tab Style Login and Signup example using jQuery in Java web applicationStruts.xmlHere in order to do a DispatchAction functionality we need to create separate action mapping for each method in the action class, which is done in the struts.xml as shown below.

/curd.jsp /curd.jsp /curd.jsp /curd.jsp /curd.jsp

Here note that we use the same action class in all the action mappings but only the method name differs. So now When the request URL is Number the execute() method in the CalculatorAction class will be executed. When the request URL is addNumber the add() method in the CalculatorAction class will be invoked, this is specified using the method attribute of the action tag in struts xml. Similarly for subtract, multiply and divide request the subtract() ,multiply() and divide() methods will be invoked respectively.This way configuring a separate action mapping for each method of same action class can be avoided by using a feature calledDynamic Method Invocation. We will learn about this in our upcoming tutorial.JspIn the curd.jsp page we create five different buttons to invoke the different methods in the CalculatorAction class.

Dispatch Action

On running the example the following page will be displayed in the browser. Now when the user click a button the appropriate method in the CalculatorAction class gets invoked.

For example When the user clicks the add button the add() method in the CalculatorAction class gets executed and the following page is displayed.

Note:Dispatch action functionality is used when you have multiple submit buttons in a single form.Zip file DispatchAction.zip

War file DispatchAction.war

Struts 2 Dynamic Method Invocation using Action WildcardsPosted byMohaideen Jamilon Sep 21, 2013 inStruts 2 Tutorial,Struts-2|2 commentsThis tutorial is a continuation of previous example (DispatchAction functionality). In this example you will see about avoiding configuration of separate action mapping for each method in Action class by using the wildcard method. Look at the following action mapping to under stand the concept.** UPDATE: Struts 2 Complete tutorial now availablehere.Action mapping From previous example

/curd.jsp /curd.jsp /curd.jsp /curd.jsp /curd.jsp

Action mapping Using Wildcard

/curd.jsp

As you can see we have replaced all the method names with an asterisk(*) symbol. The word that matches for the first asterisk will be substituted for the method attribute. So when the request URL is divideNumber the divide() method in the CalculatorAction class will be invoked.Do read : Introduction to Struts 2 Framework Interceptors in Struts 2 Creating Custom Interceptors in Struts2 Login Interceptor in Struts 2Note :1. We can also substitute asterisk in the jsp pages.For example /{1}curd.jsp 2. The wild card can be placed in any position in a action nameFor example /{1}curd.jsp 3. You can have multiple wild card , for example /{1}curd{2}.jsp To match first wildcard, we have to use {1}, to match second wild card we have to use {2}.War file Dynamic Method Invocation.war

Zip file Dynamic Method Invocation.zip

ActionError & ActionMessage Example in Struts 2Posted byMohaideen Jamilon Apr 18, 2013 inStruts 1,Struts 2 Tutorial,Struts-2|1 commentIn this tutorial we will learn aboutActionError&ActionMessageclass and its usage.

a) ActionError classis used to send error feedback message to user and it get rendered in jsp by usingtag.b) ActionMessage class is used to send information feedback message to user, and it get rendered in jsp usingtag.** UPDATE: Struts 2 Complete tutorial now availablehere.In this tutorial we will use the previous tutorials example to implement the functionality ofActionErrorandActionMessageclass.

Heres a simple login form, display the error message (actionerror) if the username is empty, Otherwise redirect to another page and display the a welcome message (actionmessage).1. Folder Structure

Action ClassTheaction class, do a simple checking to make sure that the username is not empty, if the userName is not valid then the action class set the error message withaddActionError(), if its valid then it set the successful message withaddActionMessage().package com.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

private static final long serialVersionUID = 6677091252031583948L;

private String userName;

public String execute() {

return SUCCESS; }

public String getUserName() { return userName; }

public void setUserName(String userName) { this.userName = userName; }

public void validate() { if (userName.isEmpty()) { addActionError("Username can't be blanked"); } else { addActionMessage("Welcome " + userName + ", You have been Successfully Logged in"); } }}You might be interested to read: jQuery form validation using jQuery Validation plugin FieldError in Struts 2 ExampleJSPTwo simple JSP pages with css style to customize the error message.login.jsp

Login

ActionError & ActionMessage Example

success.jsp

Welcome Page

ActionError & ActionMessage Example

struts.xmlThe mapping in struts.xml should be as below

success.jsp login.jsp

Run ithttp://localhost:8089/ActionErrorMessage/

When Username is invalid, display error message with

When Username is valid, display welcome message

Note:In struts 2 when you use tag, it displays the errors with bullets, read the article onChange default style of s:actionerror / s:actionmessage tagin order to remove this

FieldError in Struts 2 ExamplePosted byMohaideen Jamilon Aug 14, 2014 inStruts 2 Tutorial,Struts-2|6 comments

In our previous tutorial we learnt aboutactionError and actionMessagein struts 2, in this tutorial, we are going to describe the fielderror tags. The fielderror tag is a UI tag that renders field errors if they exist.

** UPDATE: Struts 2 Complete tutorial now availablehere.Folder Structure

Action ClassDevelop an action class usingaddFieldError(String fieldName, String errorMessage)method. This method adds an error message for a given field to the corresponding jsp page.Here the error messages is added to each field individually using the addFieldError() method. The error messages can either be specified in a separate property file or can be added directly in the Action class itself.package com.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

private static final long serialVersionUID = 6677091252031583948L;

private String userName; private String password;

public String getPassword() { return password; }

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

public String execute() { return SUCCESS; }

public String getUserName() { return userName; }

public void setUserName(String userName) { this.userName = userName; }

public void validate() {

if (userName.isEmpty()) { addFieldError("userName", "Username can't be blank"); } if (password.isEmpty()) { addFieldError("password", "Password Can't be blank"); } else { addActionMessage("Welcome " + userName + ", You have been Successfully Logged in"); } }}Here when either of userName or password is empty then fieldError is added this action via addFiedError method, so the execute method does not get invoked, andinterceptorstake case altering the flow of response by sending error string.If userName and password are valid then a success message is added toactionMessage, the execute method get invoked, the jsp page get displayed based on execute methods returned value.Recommended Article Interceptors in Struts 2 Exception handling in Struts 2JSPFile: Login.jspCreate a jsp page that will display your field error messages (when fails to logged-in) usingtag as shown:

Login

FieldError in Struts 2

File : Success.jsp

Welcome Page

ActionError & ActionMessage Example

Note :We have done the coding such that If the username or password is empty , then the user will be forwarded to login.jsp where the field error added using addFieldError will get displayed.

You might be interested to read: jQuery form validation using jQuery Validation pluginActionError & ActionMessage Example in Struts 2struts.xmlMake sure that the struts.xml has the following mapping

success.jsp login.jsp

The web.xml configuration is same as given in hello world programe.DemoOn running the application

When Username or password is empty, display error message set by

When Username and password is non empty, then application executes successfully and redirects to success.jsp and displays theActionMessagesetted in Validate method via tag.

ReferenceFieldError Apache

Struts 2 Namespace ConfigurationPosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|0 comments

Struts 2 Namespace is a new concept to handle the multiple modules by giving a namespace to each module The namespace attribute of element in struts.xml is an optional attribute. The default namespace is . i.e. an empty string. The value of your namespace must always begin with a /. Namespaces are used to group together a set of actions. An action with the same name can exist in several namespaces. The action that will be invoked depends upon the namespace in which it is called.** UPDATE: Struts 2 Complete tutorial now availablehere.See this picture to understand how an URL matches to Struts 2 action namespace.

1. Final project structure

2. Namespace configurationLet us go through a Struts 2 namespace configuration example to know how it matches with URL and folder.Note :The package name will not affect the result, just give a meaningful name.

File:struts.xml

jsp/home.jsp

/jsp/staff.jsp

/jsp/student.jsp

3. JSP PagesFile:home.jsp

Home

Welcome user

File:Staff.jsp

Staff home page

Welcome staff

File:Student.jsp

Student home page

Welcome Student

4. Mapping - How it works?Example 1The URL : http://localhost:8089/Name_Space/student/Student.action.Will match the root namespace, and display the content ofWebContent/jsp/student.jsp.

/jsp/student.jsp

Example 2URL : http://localhost:8089/Name_Space/staff/Staff.actionWill match the common namespace, and display the content ofWebContent/jsp/staff.jsp

/jsp/staff.jsp

Example 3URL : http://localhost:8089/Name_Space/default Will match the common namespace, and display the content ofWebContent/jsp/home.jsp.

jsp/home.jsp

** UPDATE: Struts 2 Complete tutorial now availablehere.Note :Given below is the genaralised urlHttp://:///.action

Struts 2- Include multiple Struts configuration filesPosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|0 comments

Struts 2 comes with include file- feature to include multiple Struts configuration files into a single unit.Single Struts configuration fileBad way of Struts 2 configuration example (From Previous Example).File:struts.xml

jsp/home.jsp

/jsp/staff.jsp

/jsp/student.jsp

** UPDATE: Struts 2 Complete tutorial now availablehere.In the above Struts configuration file, it groups all the -student and staff- settings in a single file,which is not recommended and MUST BE AVOID. You should break thisstruts.xmlfile into smaller module related pieces.Multiple Struts configuration filesIn Struts 2, you should always assign each module a struts configuration file. In this case, you can create three files :1. student.xml - Put all student module settings here.2. staff.xml - Put all staff modules settings here.3. struts.xml - Put default settings and include the staff.xml and student.xml.File:student.xml -Put all student module settings here.

/jsp/student.jsp

File: Staff.xml Put all staff modules settings here.

/jsp/staff.jsp

File: Struts.xml Put default settings and include the staff.xml and student.xml

jsp/home.jsp

Final project structure

Remove .action extension in struts2 and to give user defined extensionPosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|0 comments

In Older version of Struts 2, all action class by default has .action as extension,For example, by default to access an action say LoginAction class, we will use the following URLAction URL: http://localhost:8089/Struts2/Login.actionIn its latest version i.e version after 2.2.x by default action class has no extension, in this case the default wat to access an action isAction URL: http://localhost:8089/Struts2/LoginThis article aims to change this default extension.** UPDATE: Struts 2 Complete tutorial now availablehere.So in order to remove or to give any user defined extension, just declare a constantstruts.action.extensionin struts.xml and set the value to the extension you wish.For example to change the extension from .action to .jsp, the following code is used.

Output URL will be shown like this:-Action URL: http://localhost:8089/Struts2/Login.jspSuppose If you want to shown empty extension URL try this:-

Output URL will be shown like this:-Action URL: http://localhost:8089/Struts2/LoginHope This Help You :)Article to read Next: Introduction to Struts 2 Framework Interceptors in Struts 2 Creating Custom Interceptors in Struts2 Login Interceptor in Struts 2

Struts 2 Development Mode ExamplePosted byMohaideen Jamilon Mar 27, 2013 inStruts 2 Tutorial|1 comment

Struts 2 has a setting which can be set totrueorfalseinstruts.propertiescalled devMode. When this setting is enabled, Struts 2 will provide additional logging and debug information, which can significantly speed up development.** UPDATE: Struts 2 Complete tutorial now availablehere.Enable the Strut2 development modeSet thestruts.devModevalue to true, either in Struts properties file or XML configuration file.struts.propertiesstruts.devMode = truestruts.xml

Note :1.By default, the development mode is disabled, because it has a significant impact on performance, since the entire configuration will be reloaded on every request.2. The development mode is only suitable in development ordebuggingenvironment. In production environment, you have to disable it. As It will caused significant impact on performance, because the entire application configuration, properties files will be reloaded on every request, many extra logging and debug information will be provide also.Do read : How to Debug a java application in EclipseDisable the Strut2 development modeSet thestruts.devModeto false, either in Struts properties file or XML configuration file.struts.propertiesstruts.devMode = falsestruts.xml

Reference Struts 2 development mode documentation

How to use a JavaBean class as a property in struts 2 action class.Posted byMohaideen Jamilon Feb 24, 2014 inStruts-2|0 comments

In this tutorial we will learn how to use a JavaBean class as a property in struts 2 action.Consider a scenario, in which you have written an action class, which in turn has a JavaBean class as its property as shown below.** UPDATE: Struts 2 Complete tutorial now availablehere.Action classHelloAction.javapackage com.simplecode.action;

import com.opensymphony.xwork2.Action;import com.simplecode.bo.User;

public class HelloAction implements Action{ private User user; public User getUser() { return user; }

public void setUser(User user) { this.user = user; }

public String execute() { if (getUser().getUserName().isEmpty()) return ERROR; else return SUCCESS; }}Transferring the JavaBeans property values to Action classIn Struts 2 transferring of data to the Java bean object is automatically done by the params interceptor, all we have to do is to create a JavaBeans object and its corresponding getter and setter methods in the action class.Retrieving the JavaBeans property from action class to JspTo refer the attributes of User class, we need to first get the User object and then access its properties. For example to access the Users, userName attribute in the Action class, the following syntax is used.getUser().getUserName();JavaBean classUser.javapackage com.simplecode.bo;

public class User{ private String userName;

public String getUserName() { return userName; }

public void setUserName(String userName) { this.userName = userName; }}JSPIn jsp page the user attributes cannot be directly referenced. Since the attributes we refer in the jsp page belongs to the User object (JavaBean object) we need to go one level deeper to reference the attributes. To refer the userName attribute of User class, the value of the name attribute in the s:property tag should be"user.userName"login.jsp

Login

Struts 2 JavaBeans as property

success.jsp

Welcome Page

Welcome,

error.jsp

Error Page

Login failed! Please enter a valid user name

Demohttp://localhost:8089/JavaBean/

On entering the details and clicking the Submit button the following page will be dispalyed.

In struts 2 there is a concept call Model objects, using which we can refer to the JavaBean objects attributes directly, instead of doing a deeper reference as shown in this example above. In ournext articlewe will learn about struts 2 Model Objects which simplifies the amount of code written above viaModelDriven interfaceZip file JavaBean.zip

ModelDriven Interceptors in Struts 2Posted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial,Struts-2|0 comments

In our lastarticle we have learned how to use a JavaBean class as a property in struts 2 action.In this tutorial we will learn about Struts 2 support for model objects.The Model object is a simple JavaBean object, which will be available to action class directly from ValueStack,i.e we dont need to do deeper referencing to refer its attribute(JavaBeans attribute).To make a JavaBean object as a model object, our Action class should implement ModelDriven interface which forces the getModel() method to be implemented. This method provides the model object to be pushed into the Value Stack.Here the getModel() must be invoked earlier for populating its input properties with data from request parameters,To make sure that the model is available in Value Stack when input parameters are being set, the ModelDrivenInterceptor is configured for the Action in struts.xml.Most Popular Article for Reference AJAX implementation in Struts 2 without JQuery AJAX implementation in Struts 2 using JQuery and JSONSince the ModelDriven interceptor is already included in the default stack, we dont need to inculde modelDriven interceptor explicitly.** UPDATE: Struts 2 Complete tutorial now availablehere.Lets see a sample example of POJO form, which can be injected in the action as its model.Bean Class(Model Class)File : User.javapackage com.simplecode.bo;

public class User{ private String userName;

public String getUserName() { return userName; }

public void setUserName(String userName) { this.userName = userName; }}Action ClassAction class implements theModelDriven interface, declared thegetModel()method to return theusers object.When the form data is submitted to this action, it will transfers the form data into the user properties automatically.File : HelloAction.javapackage com.simplecode.action;

import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ModelDriven;import com.simplecode.bo.User;

public class HelloAction implements Action,ModelDriven { // Need to initialize model object private User user = new User(); public String execute() { if (user.getUserName().isEmpty()) return ERROR; else return SUCCESS; } public User getModel() { return user; }}Note:1. Since the model object to be pushed into ValueStack must not be null hence model must be initialized before returned by getModel() method.2. We can use only one model object per action classDo read : Difference between Action Chaining & Action redirect in Struts 2 GridView in struts 2 using jQuery DataTable plugin Autocomplete in Struts 2 using Jquery via AjaxJSP pageJSP pages for theModelDriven demonstration.login.jsp

Login

Struts 2 ModelDriven Example

success.jsp

Welcome Page

Welcome,

error.jsp

Error Page

Login failed! Please enter a valid user name

struts.xml

/jsp/success.jsp /jsp/error.jsp

Demohttp://localhost:8089/ModelDriven/

When I enter a non empty value in the textbox and press submit button, then the application redirects to success page as shown.

On Clicking submit button without any value in textbox, then the application redirects to error page as shown.

File Upload Example in Struts 2Posted byMohaideen Jamilon Nov 18, 2012 inStruts 2 Tutorial,Struts-2|1 comment

In Struts 2 file uploading can done with the help of built-in FileUploadInterceptor. We usetag to create a file upload component, which allow users to select file from their local disk and upload it to the server. The encoding type of the form should be set to multipart/form-data and the HTTP method should be set to post. The Struts 2 File UploadInterceptoris 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** UPDATE: Struts 2 Complete tutorial now availablehere.(assuming the uploaded file name is uploadDoc). [uploadDoc]File Will store the actual uploaded File [uploadDoc]ContentType: This String will store the content type of the file [uploadDoc]FileName: This String will store the actual name of the uploaded file (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 exampleprivate File uploadDoc;This will store actual uploaded Fileprivate String uploadDocFileName;This string will contain the file name of uploaded file.private String uploadDocContentType;This string will contain the Content Type of uploaded file.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

Do read : AJAX style File Upload in Java Web Application using jQuery Creating Custom Interceptors in Struts2ParametersYou can use the following parameters to control the file upload functionality. maximumSizeThis parameter is optional. The default value of this is 2MB.Example:1024000

Note:You can also set the upload file size using the following code

allowedTypesThis parameter is also optional. It allows you to specify the allowed content type.Note: To upload txt file text/plain To upload PDF files application/pdf

Recommended reading Struts 2 File Download ExampleFolder Structure

Action classFileUploadAction.javapackage com.simplecode.action;

import java.io.File;import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

private static final long serialVersionUID = 1L; private File uploadDoc; private String uploadDocFileName; private String uploadDocContentType;

public String execute() { return SUCCESS; }

public File getUploadDoc() { return uploadDoc; }

public void setUploadDoc(File uploadDoc) { this.uploadDoc = uploadDoc; }

public String getUploadDocFileName() { return uploadDocFileName; }

public void setUploadDocFileName(String uploadDocFileName) { this.uploadDocFileName = uploadDocFileName; }

public String getUploadDocContentType() { return uploadDocContentType; }

public void setUploadDocContentType(String uploadDocContentType) { this.uploadDocContentType = uploadDocContentType; } }

JSP Pagefileupload.jsp

file upload page

Struts 2 file upload example

uploadSuccess.jsp

Upload Successful

Struts 2 file upload exampleFile Name :
Content type:
User file :

struts.xmlMake sure you have done action mapping properly in struts.xml file. An example of this is given below,

1024000 application/pdf input,back,cancel,browse input,back,cancel,browse /jsp/uploadSuccess.jsp /jsp/fileUpload.jsp

Demohttp://localhost:8089/Struts2_FileUpload/

Error message prompts if you upload a file which is more than 10kb, or not a text file.

The uploaded file will be treat as a temporary file, with a long random file name, upload__376584a7_12981122379__8000_00000010.tmp. This file will be stored some where in the metadata directory

Note:In order to save the .tmp file in a desired location ,which you wish , then use the following code in yourstruts.xml

To more about overriding these default file upload error message, click on-Override struts 2.x file upload messages

Caution :The problem with above code snippet is, you cannot see the uploaded file in the target folder. Also the file uploaded wont have any proper extension, instead it will have the extension as .tmp.Struts 2 Upload File to Desire Folder LocationSo in-order to upload and save a file in target space and in-order to have a file with proper extension, i.e .pdf , .doc etc, we should use the following code snippet in the action classs execute method.Modified execute methodpublic String execute() {// Location to store the uploaded file in our desired pathString targetPath = "D:/file target/";File fileToCreate = new File(targetPath, uploadDocFileName); try { FileUtils.copyFile(this.uploadDoc, fileToCreate); } catch (IOException e) { addActionError(e.getMessage()); } return SUCCESS;}Zip file FileUpload.zip

War file FileUpload.war

How to override struts 2.x file upload error messages?Posted byMohaideen Jamilon Sep 28, 2013 inStruts 2 Tutorial,Struts-2|0 comments

In myprevious tutorialI have explained about how to upload file in struts 2 web application. This article aims at overriding the default file upload error message which are added byfile upload interceptorduring file upload validation. 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 failsstruts.messages.error.file.too.large - error occurs when file size is largestruts.messages.error.content.type.not.allowed - when the content type is not allowedstruts.messages.error.file.extension.not.allowed - when the file extension is not allowed** UPDATE: Struts 2 Complete tutorial now availablehere.In-order to override these message, you need follow the below steps.1. Create a global.properties file in the src folder and add the following test to your global.properties file:struts.messages.error.file.too.large = Uploaded File size is too largestruts.messages.error.uploading = File upload failedstruts.messages.error.content.type.not.allowed =File type is not allowed.struts.messages.error.file.extension.not.allowed =File extension is not allowed.2. Add the constant Instruts.xml:

After implementing these changes restart the application, and now in case of error in validation you get the custom error message which we have written in the properties file.File Download Example in Struts 2Posted byMohaideen Jamilon Sep 29, 2013 inStruts 2 Tutorial,Struts-2|2 comments

This tutorial will help you understanding how to create a Struts 2 action class that allows users to download files from server to their local computer.struts.xmlStruts 2 provides a custom result type called stream that performs file download by streaming an InputStream of a file to the client through the HttpServletResponse. Heres an example that shows how to define this result type element in struts.xml:The struts.xml file should have the following mapping

attachment;filename=${fileName} application/vnd.ms-excel fileInputStream 1024

Note that we declare a property placeholder called fileName which will be dynamically updated by Struts. Now in the action class, we need to declare a variable with the same name along with getter and setter method. By this way we have configured the download file name dynamically.In addition to that, we must define an InputStream object which has the same name as the name specified by the inputName parameter in struts.xml. All the variables must have appropriate getter methods.Recommended Article GridView in struts 2 using jQuery DataTable plugin CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax Autocomplete in Struts 2 using Jquery via Ajax Tab Style Login and Signup example using jQuery in Java web applicationAction Classpackage com.simplecode.action;

import java.io.File;import java.io.FileInputStream;import java.io.InputStream;

import com.opensymphony.xwork2.Action;

public class DownloadAction implements Action { private InputStream fileInputStream; // Used to set file name dynamically private String fileName; public InputStream getFileInputStream() { return fileInputStream; }

public String execute() throws Exception { File fileToDownload = new File("C:/Download/MyFile.xls"); fileName = fileToDownload.getName(); fileInputStream = new FileInputStream(fileToDownload); return SUCCESS; }

public String getFileName() { return fileName; }

public void setFileName(String fileName) { this.fileName = fileName; } }** UPDATE: Struts 2 Complete tutorial now availablehere.Jsp

File Download

Struts 2 file download example Download file - MyFile.xls

Related Article File Upload Example in Struts 2Demo

On running this application

Struts 2 examplePosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|0 comments

In Struts 2 , you can use theto create a HTML input textbox. For example, you can declare the s:textfield with a key attribute or label and name attribute.

//or

In Struts 2, the name will map to the JavaBean property automatically. In this case, on form submit, the textbox value with name=userName will call the corresponding Actions setUsername(String xx) to set the value** UPDATE: Struts 2 Complete tutorial now availablehere.Struts 2 example1. Properties fileTwo properties files to store the message.project.propertiesproject.username = Usernameproject.submit = SubmitLoginAction.propertiesusername.required = Username Cannot be blank2. ActionA simple Action class with a validation to make sure the username is not empty, otherwise return an error message.LoginAction.javapackage com.simplecode.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

private static final long serialVersionUID = 6677091252031583948L;

// Need to Initiize a morden driven object private String userName; private String password;

public String getUserName() { return userName; }

public void setUserName(String userName) { this.userName = userName; }

public String getPassword() { return password; }

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

public String execute() {

return SUCCESS; }

public void validate() { if (userName.equals("")) { addFieldError("userName", getText("username.required")); } }}3. View pageResult page to use Struts 2s:textfieldto create a HTML textbox input field.login.jsp

Login

Struts 2 < S:textfield > Textbox Examplee

success.jsp

Welcome Page

Struts 2 < S:textfield > Textbox Example Welcome

4. struts.xml

/jsp/login.jsp /jsp/success.jsp /jsp/login.jsp

5. Demohttp://localhost:8089/Struts2_textfield/

Download It -

Struts2_textfield.zip

Struts2_Textbox.war

Struts 2 examplePosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|0 comments

Download It -

Struts2-Password-Example without Library files

Struts2-Password-Example with Library files (war)

In Struts 2 , you can use theto create a HTML password field. For example, you can declare the s:password with a key attribute or label and name attribute.

//or

** UPDATE: Struts 2 Complete tutorial now availablehere.In Struts 2, the name will map to the JavaBean property automatically. In this case, on form submit, the textbox value with name=password will call the corresponds Actions setPassword(String xx) to set the valueStruts 2 exampleA page with password and confirm password fields, and do the validation to make sure the confirm password is match with the password.1. Properties fileTwo properties files to store the message.project.propertiesproject.username = Usernameproject.password= Passwordproject.submit = LoginLoginAction.propertiesusername.required = Username Cannot be blankpassword.required = Password Cannot be blank2. ActionLoginAction.javapackage com.simplecode.action;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

private static final long serialVersionUID = 1L; private String userName; private String password;

public String getUserName() { return userName; }

public void setUserName(String userName) { this.userName = userName; }

public String getPassword() { return password; }

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

public String execute() {

return SUCCESS; }

public void validate() { if (userName.equals("")) { addFieldError("userName", getText("username.required")); } if (password.equals("")) { addFieldError("password", getText("password.required")); } }}3. View pageResult page with Struts 2 s:password tag to create a HTML password field.login.jsp

Login

Struts 2 < s:password > Example

success.jsp

Welcome Page

Struts 2 < s:password > Textbox Examplee Username :
Password :

4. struts.xml

/jsp/login.jsp /jsp/success.jsp /jsp/login.jsp

5. Demo

http://localhost:8089/Struts2_password/

Download It -

Struts2-Password-Example without Library files

Struts2-Password-Example with Library files (war)

Struts 2 examplePosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|2 comments

Download It -

Struts2_hidden.zip

Struts2_hidden.war

In Struts 2 , you can use thetag to create a HTML hidden field.

It will render as the following HTML code.

Struts 2 exampleA page with a url hidden value, and display the hidden value after form is submitted.** UPDATE: Struts 2 Complete tutorial now availablehere.1. Folder Structure :

2. Action classHiddenAction.javapackage com.simplecode.action;

import com.opensymphony.xwork2.ActionSupport;

public class HiddenAction extends ActionSupport {

private static final long serialVersionUID = 1L; private String hiddenValue;

public String getHiddenValue() { return hiddenValue; }

public void setHiddenValue(String hiddenValue) { this.hiddenValue = hiddenValue; }

public String execute() { return SUCCESS; }

}3. JSP View pageStruts 2 s:hidden tag to create a hidden value field.hidden.jsp

Hidden

Struts 2 - tag example This page has a hidden value (view source):

success.jsp

Welcome Page

Struts 2 - tag example

The hidden value :

4. struts.xml

/jsp/hidden.jsp /jsp/success.jsp /jsp/hidden.jsp

5. Demohttp://localhost:8089/Struts2_hidden/jsp/Hiddenjsp

Output :

Download It -

Struts2_hidden.zip

Struts 2_hidden.war

Struts 2 examplePosted byMohaideen Jamilon Apr 18, 2013 inStruts 2 Tutorial|0 comments

Download It -

Struts2_Textarea-Example without Library files

Struts2_Textarea-Example with Library files (war)

In Struts 2 , you can use theto create a HTML textarea field.Example: ** UPDATE: Struts 2 Complete tutorial now availablehere.Struts 2 exampleA page contains address textarea field, and displays the textarea value after the form is submitted.1. Action classTextAreaAction.javapackage com.simplecode.action;

import com.opensymphony.xwork2.ActionSupport;

public class TextAreaAction extends ActionSupport{ private static final long serialVersionUID = 1L; private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String execute() { return SUCCESS; }}2. View pageStruts 2 s:textarea tag to create a textarea field.textarea.jsp

Text area

Struts 2 - example

result.jsp

Text area

Struts 2 - example

3. struts.xml

/jsp/textarea.jsp /jsp/result.jsp

4. Demo

http://localhost:8089/Struts2_Textarea/jsp/textarea

Download It -

Struts2_Textarea-Example without Library files

Struts2_Textarea-Example with Library files (war)

Handling double form submissions in Struts2Posted byMohaideen Jamilon Apr 12, 2013 inStruts-2|2 comments

Double form submissions(either by refreshing or by hitting the browser back button) can be irritating and in some cases leads to big problem .Luckly struts2 has a build in functionality that prevents such scenarios : tag and token interceptor. As an example, lets say that we have a form that looks like this:

** UPDATE: Struts 2 Complete tutorial now availablehere.In order to prevent double submissions all we have to do is to addtag in the above form. This tag will add a unique identifier in the form that will be used later from the token interceptor in order to check if the form is submitted for the first time or not. In case the form is not submitted for the first time, interceptors result will be invalid.token.

/inputPage.jsp/invalidToken.jsp/successPage.jsp

Note that invalid.token result in the above action declaration actually means that in the case of invalid token the user should be redirected in invalidToken.jsp

Struts 2 examplePosted byMohaideen Jamilon Mar 27, 2013 inStruts 2 Tutorial|0 comments

The tag should be placed in theheadsection of the HTML page. The s:head tag automatically generates links to the css and javascript libraries that are necessary to render the form elements.This tag is used to output the HTML head information like encoding, CSS or JavaScript file. See the following snippet** UPDATE: Struts 2 Complete tutorial now availablehere.

Here Since no theame is provided in tag ,it uses the default xhtml theme, it will render the output according to the template\xhtml\head.ftl file as shown below

To include your own user defiend js or css file, just add it into the template\xhtml\head.ftl template file, and output it viatagThe tag also includes the option to set a custom datepicker theme if needed.

My page If you use the ajax theme you can turn a debug flag by setting the debug parameter totrue.

My page Struts 2 datetimepicker examplePosted byMohaideen Jamilon Mar 27, 2013 inStruts 2 Tutorial,Struts-2|3 comments

Zip file Date Picker.zip

War file Date Picker.war

Click here to learn aboutDatetime picker in struts 2 using jquery jarTo create a date time pick component in struts 2, please follow this two steps :1. Add struts2-dojo-plugin.jar in your class path.2. Include the struts-dojo-tags tag and its header in your jsp page** UPDATE: Struts 2 Complete tutorial now availablehere.

Recommended Article GridView in struts 2 using jQuery DataTable plugin CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax Autocomplete in Struts 2 using Jquery via AjaxAction classDatePickerAction.javapackage com.simplecode.action;

import java.util.Date;

import com.opensymphony.xwork2.Action;

public class DatePickerAction implements Action { private Date birthDay;

public Date getBirthDay() { return birthDay; }

public void setBirthDay(Date birthDay) { this.birthDay = birthDay; }

public String execute() throws Exception { return SUCCESS; }}JSP Pagedatepicker.jsp

Date Picker

Struts2 Date Picker example

result.jsp

Date Picker Result

Struts2 Date Picker exampleBirthday :

struts.xml

/jsp/result.jsp

DemoOn running the above example http://localhost:8089/Struts2_DatePicker/

Now on clicking the date picker icon, the calendar gets displayed as shown below.

On selecting the date and clicking the submit button, the following output is obtained

Suppose you want to include a static date in jsp, then the following code can be used

Suppose you want to include a static date in jsp, then the following code can be used

So now when you run the application, these values will be displayed in the jsp page. Inorder to make this values appear in the result page, you just need to include the getter and setter forstaticDateFromJspandtodaysDatein the action class, and render it via property tag in result.jsp pageClick here to learn aboutDatetime picker in struts 2 using jquery jarDatetime picker in struts 2 using jqueryPosted byMohaideen Jamilon Nov 10, 2013 inStruts-2|1 comment

Zip file Jquery DatePicker

Last time when I worked out how to get thedojo datetimepickerWell, it faced some issues like, I could not customize the size of the text box, and also its appearance. As an alternative I found out a pluginStruts2- Jquerywhich provide a lots of customizing features.** UPDATE: Struts 2 Complete tutorial now availablehere.To create a date time pick component in struts 2, please follow this two steps :1. Add struts2-jquery-plugin-3.6.1.jar in your class path.2. Include the struts-jquery-tags tag and its header in your jsp page

Do read : Introduction to Struts 2 Framework Interceptors in Struts 2 Creating Custom Interceptors in Struts2 Login Interceptor in Struts 2Feature of jquerySimple Calculator

Calander with change year Option

Calander with ChangeYear and Monthyear Option

Calander with Button Pannel Option

Calander with Show Seconds Option

Now lets see the complete exampleJsp PageFile: datepicker.jsp

Date Picker

Struts2 Date Picker example

File: result.jsp

Date Picker Result

Struts2 Date Picker using Jquery simpleCalander :
changeYear :
changeYearAndMonth :

showSeconds :
withPannel :
slideDownEffect :
fadeInEffect :
yearRage :
withOutButton :

Action Classpackage com.simplecode.action;

import com.opensymphony.xwork2.Action;

public class DatePickerAction implements Action {

private String simpleCalander; private String changeYear; private String changeYearAndMonth; private String showSeconds; private String withPannel; private String slideDownEffect; private String fadeInEffect; private String yearRage; private String withOutButton;

public String getSimpleCalander() { return simpleCalander; }

public String getChangeYear() { return changeYear; }

public String getChangeYearAndMonth() { return changeYearAndMonth; }

public String getShowSeconds() { return showSeconds; }

public String getWithPannel() { return withPannel; }

public String getSlideDownEffect() { return slideDownEffect; }

public String getFadeInEffect() { return fadeInEffect; }

public String getYearRage() { return yearRage; }

public String getWithOutButton() { return withOutButton; }

public void setSimpleCalander(String simpleCalander) { this.simpleCalander = simpleCalander; }

public void setChangeYear(String changeYear) { this.changeYear = changeYear; }

public void setChangeYearAndMonth(String changeYearAndMonth) { this.changeYearAndMonth = changeYearAndMonth; }

public void setShowSeconds(String showSeconds) { this.showSeconds = showSeconds; }

public void setWithPannel(String withPannel) { this.withPannel = withPannel; }

public void setSlideDownEffect(String slideDownEffect) { this.slideDownEffect = slideDownEffect; }

public void setFadeInEffect(String fadeInEffect) { this.fadeInEffect = fadeInEffect; }

public void setYearRage(String yearRage) { this.yearRage = yearRage; }

public void setWithOutButton(String withOutButton) { this.withOutButton = withOutButton; }

public String execute() { return SUCCESS; }}struts.xml

/jsp/result.jsp

DemoOn running the application:-

Autocompleter Textbox & dropdown in Struts 2Posted byMohaideen Jamilon Oct 26, 2013 inStruts 2 Tutorial,Struts-2|14 comments

To create a Autocompleter component in struts 2, please follow this two steps :1. Add struts2-dojo-plugin.jar in your class path.2. Include the struts-dojo-tags tag and its header(shown below) in your jsp page

** UPDATE: Struts 2 Complete tutorial now availablehere.Action classAutoCompleteAction.javapackage com.simplecode.action;

import java.util.ArrayList;import com.opensymphony.xwork2.Action;

public class AutoCompleteAction implements Action { public ArrayList cricketNations = new ArrayList(); public String country;

public String execute() { populateCircketNations(); return SUCCESS; }

public void populateCircketNations() { cricketNations.add("Australia"); cricketNations.add("England"); cricketNations.add("India"); cricketNations.add("West Indies"); cricketNations.add("New Zealand"); cricketNations.add("Pakistan"); cricketNations.add("Bangladesh"); cricketNations.add("South Africa"); cricketNations.add("Sri Lanka"); cricketNations.add("Zimbabwe"); }

public String displayCountry() { return SUCCESS; }

public String getCountry() { return country; }

public void setCountry(String country) { this.country = country; } }Do read:Autocomplete in Struts 2 using Jquery and JSON via AjaxJSP PageautoComplete.jspHere is a directive used in jsp for including dojo ajax tag files.

Auto complete

Auto complete Dropdown | Textbox

Note:In tag, showDownArrow property indicates whether to show dropdown or not, on setting to false textbox will appear and when set to true dropdown box will appear.struts.xml

autoComplete.jsp

WelcomeToCountry.jsp

Do read:AJAX implementation in Struts 2 using JQuery and JSONDemoOn running the above examplehttp://localhost:8089/AutoComplete/autoComplete.actionSetting showDownArrow = true

Setting showDownArrow = false

Zip file AutoCompleter.zip

War file AutoCompleter.war

Struts 2 Bean TagPosted byMohaideen Jamilon Aug 12, 2013 inStruts 2 Tutorial,Struts-2|0 comments

The bean tag is like a hybrid of the set and push tags. The main difference is that you dont need to work with an existing object. You can create an instance of an object and either push it onto the ValueStack or set a top-level reference to it in the Action-Context. By default, the object will be pushed onto the ValueStack and will remain there for the duration of the tag.** UPDATE: Struts 2 Complete tutorial now availablehere.In this tutorial let us learn how to use the Struts 2 Bean Tag with the help of a DollarConverter bean example. In this example we will convert dollars to rupees.Download It BeanTag Example.zip

1.Bean ClassFile name : DollarConverter .javapackage com.simplecode.action;

public class DollarConverter {

private double rupees; private double dollars;

public double getRupees() { return dollars * 55; }

public void setRupees(double rupees) { this.rupees = rupees; }

public double getDollars() { return rupees / 55; }

public void setDollars(double dollars) { this.dollars = dollars; }}The next step is to create an instance of the DollarConverter bean in the jsp page using the bean tag.We can use the bean tag in two ways.1. By pushing the value onto the ValueStack.2. By setting a top-level reference to it in the ActionContext.Lets implement both the methods one by one.Method 1Hear we will see how we can do this by pushing the value onto the ValueStack. We do this using the following code in jsp.Method 1 - push the value onto the ValueStack

100 Dollars = Rupees


The name attribute of the bean tag hold the fully qualified class name of the JavaBean. The param tag is used to set the dollar value. We now use the property tag to retrive the equivalent value in rupees. The DollarConverter bean will resides on the ValueStack till the duration of the bean tag. So its important that we use the property tag within the bean tag.Method 2Now we will see how we can do the same by creating a top-level reference to the bean in the ActionContext. We do this using the following code.

Method 2 - Set a top-level reference to it in the ActionContext

100 Dollars = RupeesTo create an instance of the bean in theActionContextwe need to specify the instance name using the var attribute of the bean tag. Here our instance name is converter. Once we do this we can access the bean values outside the bean tag. Since the value is in the ActionContext we use the # operator to refer it.4. Demohttp://localhost:8089/BeanTagOutput

Struts 2 Push Tag ExamplePosted byMohaideen Jamilon Aug 12, 2013 inStruts 2 Tutorial,Struts-2|0 comments

Struts 2 pushtag is used topush a value into the ValueStack. The value we pushed using push tag will be on top of the ValueStack, so it can be easily referenced using the first-level OGNL expression instead of a deeper reference. The following code show how to do this.** UPDATE: Struts 2 Complete tutorial now availablehere.Download It PushTag

1. Actionpackage com.simplecode.action;

import com.simplecode.util.AuthorBean;

//PushTag Action classpublic class BookInfoAction {

private AuthorBean authorBean;

public String populate() { authorBean = new AuthorBean ("Mohammed masjid", "Akuland Nz","8051 Micro Controller"); return "populate"; }

public String execute() { return "success"; }

public AuthorBean getAuthorBean() { return authorBean; }

public void setAuthorBean(AuthorBean authorBean) { this.authorBean = authorBean; }

}2. BeanA simple AuthorBean class, later will push it into the stack for easy access.package com.simplecode.util;

public class AuthorBean {

private String name; private String university; private String book;

public AuthorBean(String name, String university, String book) { this.name = name; this.university = university; this.book = book; }

public String getName() { return name; }

public void setName(String name) { this.name = name; }

public String getUniversity() { return university; }

public void setUniversity(String university) { this.university = university; }

public String getBook() { return book; }

public void setBook(String book) { this.book = book; } }3. Push tag exampleIt shows the use of push tag.

Book Details

Author name property can be accessed in two ways:
(Method 1 - Normal method)
Author Name:
University:
Book Title :

(Method 2-push tag) Author Name: University: Book Title :

How it work?Normally, if you want to get the beans property, you may reference it like

With push tag, you can push theauthorBeanto the top of the stack, and access the property directly

Both are returned the same result, but with different access mechanism only.4. Struts.xmlLink it

/bookDetails.jsp

5. Demohttp://localhost:8089/PushTag/populateBookAction.actionRun it

Struts 2 Debug Tag ExamplePosted byMohaideen Jamilon Aug 2, 2013 inStruts 2 Tutorial|0 comments

In Struts 2, the debug tag is used to output the content of the Value Stack andStack Contextdetails in the web page.** UPDATE: Struts 2 Complete tutorial now availablehere.1. Jsp debug tag exampleA JSP page to output the systems Value Stack and Stack Context using debug tag.debug.jsp

Debug tag

Debug tag

2. Action classA Action class, with a field namedactionProperty property, show in value stack in jsp.DebugTag.javapackage com.simplecode.action;import com.opensymphony.xwork2.Action;

public class DebugTag implements Action{ public String actionProperty;

public String getActionProperty() { return actionProperty; }

public void setActionProperty(String actionProperty) { this.actionProperty = actionProperty; }}3. struts.xml

/debug.jsp

4. Demohttp://localhost:8089/Debug/debugTagAction.actionOutputThewill generate a text link named debug, On clicking this link, it expands to show the debugging details.

Download It Struts2Debug.zip

Struts 2 URL tag examplePosted byMohaideen Jamilon Aug 7, 2013 inStruts 2 Tutorial|0 comments

The Struts 2 url tag can be useful if you need to use a url in many places and dont want to repeat the code again and again. You need to specify an id attribute for your url and you can also use actions instead of simple links in this tag. Adding parameters to the url can be done by using the param tag.** UPDATE: Struts 2 Complete tutorial now availablehere.Url tag exampleHere are some examples to show the use of Struts 2 url tag.1. Create an image url.

Output (assume the root context name is URLtag)

2. Create a Yahoo text and link it to http://www.yahoo.com.