Struts2 – Quick Guide

Struts 2 – Quick Guide ”; Previous Next Basic MVC Architecture Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts − Model − The lowest level of the pattern which is responsible for maintaining data. View − This is responsible for displaying all or a portion of the data to the user. Controller − Software Code that controls the interactions between the Model and View. MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here the Controller receives all requests for the application and then works with the Model to prepare any data needed by the View. The View then uses the data prepared by the Controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows. The Model The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself. The View It means presentation of data in a particular format, triggered by a controller”s decision to present the data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology. The Controller The controller is responsible for responding to the user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model. Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC methodology within Struts2. Struts 2 – Overview Struts2 is a popular and mature web application framework based on the MVC design pattern. Struts2 is not just a new version of Struts 1, but it is a complete rewrite of the Struts architecture. The Webwork framework initially started with Struts framework as the basis and its goal was to offer an enhanced and improved framework built on Struts to make web development easier for the developers. After a while, the Webwork framework and the Struts community joined hands to create the famous Struts2 framework. Struts 2 Framework Features Here are some of the great features that may force you to consider Struts2 − POJO Forms and POJO Actions − Struts2 has done away with the Action Forms that were an integral part of the Struts framework. With Struts2, you can use any POJO to receive the form input. Similarly, you can now see any POJO as an Action class. Tag Support − Struts2 has improved the form tags and the new tags which allow the developers to write less code. AJAX Support − Struts2 has recognized the take over by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, this function is very similar to the standard Struts2 tags. Easy Integration − Integration with other frameworks like Spring, Tiles and SiteMesh is now easier with a variety of integration available with Struts2. Template Support − Support for generating views using templates. Plugin Support − The core Struts2 behavior can be enhanced and augmented by the use of plugins. A number of plugins are available for Struts2. Profiling − Struts2 offers integrated profiling to debug and profile the application. In addition to this, Struts also offers integrated debugging with the help of built in debugging tools. Easy to Modify Tags − Tag markups in Struts2 can be tweaked using Freemarker templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS knowledge is enough to modify the tags. Promote Less configuration − Struts2 promotes less configuration with the help of using default values for various settings. You don”t have to configure something unless it deviates from the default settings set by Struts2. View Technologies − Struts2 has a great support for multiple view options (JSP, Freemarker, Velocity and XSLT) Listed above are the Top 10 features of Struts 2 which makes it as an Enterprise ready framework. Struts 2 Disadvantages Though Struts 2 comes with a list of great features, there are some limitations of the current version – Struts 2 which needs further improvement. Listed are some of the main points − Bigger Learning Curve − To use MVC with Struts, you have to be comfortable with the standard JSP, Servlet APIs and a large & elaborate framework. Poor Documentation − Compared to the standard servlet and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized. Less Transparent − With Struts applications, there is a lot more going on behind the scenes than with normal Java-based Web applications which makes it difficult to understand the framework. Final note, a good framework should provide generic behavior that many different types of applications can make use of it. Struts 2 is one of the best web frameworks and being highly used for the development of Rich Internet Applications (RIA). Struts 2 – Environment Setup Our first task is to get a minimal Struts 2 application running. This chapter will guide you on how to prepare a development environment to start your work with Struts 2. I assume that you already have JDK (5+), Tomcat and Eclipse installed on your machine. If you do not have these components installed, then follow the given steps on fast track − Step 1 – Setup Java Development Kit (JDK) You can download the latest version of SDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in

Struts2 – Result Types

Struts 2 – Results & Result Types ”; Previous Next As mentioned previously, the <results> tag plays the role of a view in the Struts2 MVC framework. The action is responsible for executing the business logic. The next step after executing the business logic is to display the view using the <results> tag. Often there is some navigation rules attached with the results. For example, if the action method is to authenticate a user, there are three possible outcomes. Successful Login Unsuccessful Login – Incorrect username or password Account Locked In this scenario, the action method will be configured with three possible outcome strings and three different views to render the outcome. We have already seen this in the previous examples. But, Struts2 does not tie you up with using JSP as the view technology. Afterall the whole purpose of the MVC paradigm is to keep the layers separate and highly configurable. For example, for a Web2.0 client, you may want to return XML or JSON as the output. In this case, you could create a new result type for XML or JSON and achieve this. Struts comes with a number of predefined result types and whatever we”ve already seen that was the default result type dispatcher, which is used to dispatch to JSP pages. Struts allow you to use other markup languages for the view technology to present the results and popular choices include Velocity, Freemaker, XSLT and Tiles. The Dispatcher Result Type The dispatcher result type is the default type, and is used if no other result type is specified. It”s used to forward to a servlet, JSP, HTML page, and so on, on the server. It uses the RequestDispatcher.forward() method. We saw the “shorthand” version in our earlier examples, where we provided a JSP path as the body of the result tag. <result name = “success”> /HelloWorld.jsp </result> We can also specify the JSP file using a <param name = “location”> tag within the <result…> element as follows − <result name = “success” type = “dispatcher”> <param name = “location”> /HelloWorld.jsp </param > </result> We can also supply a parse parameter, which is true by default. The parse parameter determines whether or not the location parameter will be parsed for OGNL expressions. The FreeMaker Result Type In this example, we are going to see how we can use FreeMaker as the view technology. Freemaker is a popular templating engine that is used to generate output using predefined templates. Let us now create a Freemaker template file called hello.fm with the following contents − Hello World ${name} The above file is a template where name is a parameter which will be passed from outside using the defined action. You will keep this file in your CLASSPATH. Next, let us modify the struts.xml to specify the result as follows − <?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.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success” type = “freemarker”> <param name = “location”>/hello.fm</param> </result> </action> </package> </struts> Let us keep our HelloWorldAction.java, HelloWorldAction.jsp and index.jsp files as we have created them in examples chapter. Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen . Enter a value “Struts2” and submit the page. You should see the next page. As you can see, this is exactly same as the JSP view except that we are not tied to using JSP as the view technology. We have used Freemaker in this example. The Redirect Result Type The redirect result type calls the standard response.sendRedirect() method, causing the browser to create a new request to the given location. We can provide the location either in the body of the <result…> element or as a <param name = “location”> element. Redirect also supports the parse parameter. Here”s an example configured using XML − <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success” type = “redirect”> <param name = “location”> /NewWorld.jsp </param > </result> </action> So just modify your struts.xml file to define redirect type as mentioned above and create a new file NewWorld.jpg where you will be redirected whenever hello action will return success. You can check Struts 2 Redirect Action example for better understanding. Print Page Previous Next Advertisements ”;

Struts2 – Ajax Tags

Struts 2 – The Ajax Tags ”; Previous Next Struts uses the DOJO framework for the AJAX tag implementation. First of all, to proceed with this example, you need to add struts2-dojo-plugin-2.2.3.jar to your classpath. You can get this file from the lib folder of your struts2 download (C:struts-2.2.3allstruts-2.2.3libstruts2-dojo-plugin-2.2.3.jar) For this exercies, let us modify HelloWorld.jsp as follows − <%@ page contentType = “text/html; charset = UTF-8″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <%@ taglib prefix = “sx” uri = “/struts-dojo-tags”%> <html> <head> <title>Hello World</title> <s:head /> <sx:head /> </head> <body> <s:form> <sx:autocompleter label = “Favourite Colour” list = “{”red”,”green”,”blue”}” /> <br /> <sx:datetimepicker name = “deliverydate” label = “Delivery Date” displayformat = “dd/MM/yyyy” /> <br /> <s:url id = “url” value = “/hello.action” /> <sx:div href=”%{#url}” delay=”2000″> Initial Content </sx:div> <br/> <sx:tabbedpanel id = “tabContainer”> <sx:div label = “Tab 1”>Tab 1</sx:div> <sx:div label = “Tab 2″>Tab 2</sx:div> </sx:tabbedpanel> </s:form> </body> </html> When we run the above example, we get the following output − Let us now go through this example one step at a time. First thing to notice is the addition of a new tag library with the prefix sx. This (struts-dojo-tags) is the tag library specifically created for the ajax integration. Then inside the HTML head we call the sx:head. This initializes the dojo framework and makes it ready for all AJAX invocations within the page. This step is important – your ajax calls will not work without the sx:head being initialized. First we have the autocompleter tag. The autocompleter tag looks pretty much like a select box. It is populated with the values red, green and blue. But the different between a select box and this one is that it auto completes. That is, if you start typing in gr, it will fill it with “green”. Other than that this tag is very much similar to the s:select tag which we covered earlier. Next, we have a date time picker. This tag creates an input field with a button next to it. When the button is pressed, a popup date time picker is displayed. When the user selects a date, the date is filled into the input text in the format that is specified in the tag attribute. In our example, we have specified dd/MM/yyyy as the format for the date. Next we create a url tag to the system.action file which we created in the earlier exercises. It doesn”t have to be the system.action – it could be any action file that you created earlier. Then we have a div with the hyperlink set to the url and delay set to 2 seconds. What happens when you run this is, the “Initial Content” will be displayed for 2 seconds, then the div”s content will be replaced with the contents from the hello.action execution. Finally we have a simple tab panel with two tabs. The tabs are divs themseleves with the labels Tab 1 and Tab2. It should be worth noting that the AJAX tag integration in Struts is still a work in progress and the maturity of this integration is slowly increasing with every release. Print Page Previous Next Advertisements ”;

Struts2 – Type Conversion

Struts 2 – Type Conversion ”; Previous Next Everything on a HTTP request is treated as a String by the protocol. This includes numbers, booleans, integers, dates, decimals and everything else. However, in the Struts class, you could have properties of any data types. How does Struts autowire the properties for you? Struts uses a variety of type converters under the covers to do the heavy lifting. For example, if you have an integer attribute in your Action class, Struts automatically converts the request parameter to the integer attribute without you doing anything. By default, Struts comes with a number of type converters If you are using any of the below listed converters, then you have nothing to worry about − Integer, Float, Double, Decimal Date and Datetime Arrays and Collections Enumerations Boolean BigDecimal At times when you are using your own data type, it is necessary to add your own converters to make Struts aware how to convert those values before displaying. Consider the following POJO class Environment.java. package com.tutorialspoint.struts2; public class Environment { private String name; public Environment(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } This is a very simple class that has an attribute called name, so nothing special about this class. Let us create another class that contains information about the system –SystemDetails.java. For the purpose of this exercise, I have hardcoded the Environment to “Development” and the Operating System to “Windows XP SP3”. In a real-time project, you would get this information from the system configuration. Let us have the following action class − package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class SystemDetails extends ActionSupport { private Environment environment = new Environment(“Development”); private String operatingSystem = “Windows XP SP3”; public String execute() { return SUCCESS; } public Environment getEnvironment() { return environment; } public void setEnvironment(Environment environment) { this.environment = environment; } public String getOperatingSystem() { return operatingSystem; } public void setOperatingSystem(String operatingSystem) { this.operatingSystem = operatingSystem; } } Next, let us create a simple JSP file System.jsp to display the Environment and the Operating System information. <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>System Details</title> </head> <body> Environment: <s:property value = “environment”/><br/> Operating System:<s:property value = “operatingSystem”/> </body> </html> Let us wire the system.jsp and the SystemDetails.java class together using struts.xml. The SystemDetails class has a simple execute () method that returns the string “SUCCESS“. <?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.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “system” class = “com.tutorialspoint.struts2.SystemDetails” method = “execute”> <result name = “success”>/System.jsp</result> </action> </package> </struts> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/system.action. This will produce the following screen − What is wrong with the above output? Struts knows how to display and convert the string “Windows XP SP3” and other built-in data types, but it does not know what to do with the property of Environment type. It is simply called toString() method on the class To resolve this problem, let us now create and register a simple TypeConverter for the Environment class. Create a class called EnvironmentConverter.java with the following. package com.tutorialspoint.struts2; import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; public class EnvironmentConverter extends StrutsTypeConverter { @Override public Object convertFromString(Map context, String[] values, Class clazz) { Environment env = new Environment(values[0]); return env; } @Override public String convertToString(Map context, Object value) { Environment env = (Environment) value; return env == null ? null : env.getName(); } } The EnvironmentConverter extends the StrutsTypeConverter class and tells Struts how to convert Environment to a String and vice versa by overriding two methods which are convertFromString() and convertToString(). Let us now register this converter before we use it in our application. There are two ways to register a converter. If the converter will be used only in a particular action, then you would have to create a property file which needs to be named as ”[action-class]”converstion.properties. In our case, we create a file called SystemDetails-converstion.properties with the following registration entry − environment = com.tutorialspoint.struts2.EnvironmentConverter In the above example, “environment” is the name of the property in the SystemDetails.java class and we are telling Struts to use the EnvironmentConverter for converting to and from this property. However, we are not going to do this, Instead we are going to register this converter globally, so that it can be used throughout the application. To do this, create a property file called xwork-conversion.properties in the WEBINF/classes folder with the following line com.tutorialspoint.struts2.Environment = com.tutorialspoint.struts2.EnvironmentConverter This simply registers the converter globally, so that Struts can automatically do the conversion every time when it encounters an object of the type Environment. Now, if you re-compiling and re-running the program, then you will get a better output as follows − Obviously, now the result will be better which means our Struts convertor is working fine. This is how you can create multiple convertors and register them to use as per your requirements. Print Page Previous Next Advertisements ”;

Struts2 – Control Tags

Struts 2 – Control Tags ”; Previous Next The Struts 2 tags has a set of tags that makes it easy to control the flow of page execution. Following is the list of important Struts 2 Control Tags − The If and Else Tags These tags perform basic condition flow found in every language. ”If” tag is used by itself or with ”Else If” Tag and/or single/multiple ”Else” Tag as shown below − <s:if test = “%{false}”> <div>Will Not Be Executed</div> </s:if> <s:elseif test = “%{true}”> <div>Will Be Executed</div> </s:elseif> <s:else> <div>Will Not Be Executed</div> </s:else> Check Detailed Example The Iterator Tags This iterator will iterate over a value. An iterable value can be either itherjava.util.Collection or java.util.Iterator file. While iterating over an iterator, you can use Sort tag to sort the result or SubSet tag to get a sub set of the list or array. The following example retrieves the value of the getDays() 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. <s:iterator value = “days”> <p>day is: <s:property/></p> </s:iterator> Check Detailed Example The Merge Tag These merge tag takes two or more lists as parameters and merge them all together as shown below − <s:merge var = “myMergedIterator”> <s:param value = “%{myList1}” /> <s:param value = “%{myList2}” /> <s:param value = “%{myList3}” /> </s:merge> <s:iterator value = “%{#myMergedIterator}”> <s:property /> </s:iterator> Check Detailed Example The Append Tag These append tag take two or more lists as parameters and append them all together as shown below − <s:append var = “myAppendIterator”> <s:param value = “%{myList1}” /> <s:param value = “%{myList2}” /> <s:param value = “%{myList3}” /> </s:append> <s:iterator value = “%{#myAppendIterator}”> <s:property /> </s:iterator> Check Detailed Example The Generator Tag These generator tag generates an iterator based on the val attribute supplied. The following generator tag generates an iterator and prints it out using the iterator tag. <s:generator val = “%{”aaa,bbb,ccc,ddd,eee”}”> <s:iterator> <s:property /><br/> </s:iterator> </s:generator> Check Detailed Example Print Page Previous Next Advertisements ”;

Struts2 – Interceptors

Struts 2 – Interceptors ”; Previous Next Interceptors are conceptually the same as servlet filters or the JDKs Proxy class. Interceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework. You can achieve the following using interceptors − Providing preprocessing logic before the action is called. Providing postprocessing logic after the action is called. Catching exceptions so that alternate processing can be performed. Many of the features provided in the Struts2 framework are implemented using interceptors; Examples include exception handling, file uploading, lifecycle callbacks, etc. In fact, as Struts2 emphasizes much of its functionality on interceptors, it is not likely to have 7 or 8 interceptors assigned per action. Struts2 Framework Interceptors Struts 2 framework provides a good list of out-of-the-box interceptors that come preconfigured and ready to use. Few of the important interceptors are listed below − Sr.No Interceptor & Description 1 alias Allows parameters to have different name aliases across requests. 2 checkbox Assists in managing check boxes by adding a parameter value of false for check boxes that are not checked. 3 conversionError Places error information from converting strings to parameter types into the action”s field errors. 4 createSession Automatically creates an HTTP session if one does not already exist. 5 debugging Provides several different debugging screens to the developer. 6 execAndWait Sends the user to an intermediary waiting page while the action executes in the background. 7 exception Maps exceptions that are thrown from an action to a result, allowing automatic exception handling via redirection. 8 fileUpload Facilitates easy file uploading. 9 i18n Keeps track of the selected locale during a user”s session. 10 logger Provides simple logging by outputting the name of the action being executed. 11 params Sets the request parameters on the action. 12 prepare This is typically used to do pre-processing work, such as setup database connections. 13 profile Allows simple profiling information to be logged for actions. 14 scope Stores and retrieves the action”s state in the session or application scope. 15 ServletConfig Provides the action with access to various servlet-based information. 16 timer Provides simple profiling information in the form of how long the action takes to execute. 17 token Checks the action for a valid token to prevent duplicate formsubmission. 18 validation Provides validation support for actions Please look into Struts 2 documentation for complete detail on the abovementioned interceptors. But I will show you how to use an interceptor in general in your Struts application. How to Use Interceptors? Let us see how to use an already existing interceptor to our “Hello World” program. We will use the timer interceptor whose purpose is to measure how long it took to execute an action method. At the same time, I”m using params interceptor whose purpose is to send the request parameters to the action. You can try your example without using this interceptor and you will find that name property is not being set because parameter is not able to reach to the action. We will keep HelloWorldAction.java, web.xml, HelloWorld.jsp and index.jsp files as they have been created in Examples chapter but let us modify the struts.xml file to add an interceptor as follows − <?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.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <interceptor-ref name = “params”/> <interceptor-ref name = “timer” /> <result name = “success”>/HelloWorld.jsp</result> </action> </package> </struts> Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen − Now enter any word in the given text box and click Say Hello button to execute the defined action. Now if you will check the log generated, you will find the following text − INFO: Server startup in 3539 ms 27/08/2011 8:40:53 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Executed action [//hello!execute] took 109 ms. Here bottom line is being generated because of timer interceptor which is telling that action took total 109ms to be executed. Create Custom Interceptors Using custom interceptors in your application is an elegant way to provide crosscutting application features. Creating a custom interceptor is easy; the interface that needs to be extended is the following Interceptor interface − public interface Interceptor extends Serializable { void destroy(); void init(); String intercept(ActionInvocation invocation) throws Exception; } As the names suggest, the init() method provides a way to initialize the interceptor, and the destroy() method provides a facility for interceptor cleanup. Unlike actions, interceptors are reused across requests and need to be threadsafe, especially the intercept() method. The ActionInvocation object provides access to the runtime environment. It allows access to the action itself and methods to invoke the action and determine whether the action has already been invoked. If you have no need for initialization or cleanup code, the AbstractInterceptor class can be extended. This provides a default nooperation implementation of the init() and destroy() methods. Create Interceptor Class Let us create the following MyInterceptor.java in Java Resources > src folder − package com.tutorialspoint.struts2; import java.util.*; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class MyInterceptor extends AbstractInterceptor { public String intercept(ActionInvocation invocation)throws Exception { /* let us do some pre-processing */ String output = “Pre-Processing”; System.out.println(output); /* let us call action or next interceptor */ String result = invocation.invoke(); /* let us do some post-processing */ output = “Post-Processing”; System.out.println(output); return result; } } As you notice, actual action will be executed using the interceptor by invocation.invoke()call. So you can do some pre-processing and some postprocessing based on your requirement. The framework itself starts the process by making the first call to the ActionInvocation object”s invoke(). Each time invoke() is called, ActionInvocation consults its state and executes whichever interceptor comes next. When all of

Struts2 – Value Stack/OGNL

Struts 2 – Value Stack/OGNL ”; Previous Next The Value Stack The value stack is a set of several objects which keeps the following objects in the provided order − Sr.No Objects & Description 1 Temporary Objects There are various temporary objects which are created during execution of a page. For example the current iteration value for a collection being looped over in a JSP tag. 2 The Model Object If you are using model objects in your struts application, the current model object is placed before the action on the value stack. 3 The Action Object This will be the current action object which is being executed. 4 Named Objects These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes. The value stack can be accessed via the tags provided for JSP, Velocity or Freemarker. There are various tags which we will study in separate chapters, are used to get and set struts 2.0 value stack. You can get valueStack object inside your action as follows − ActionContext.getContext().getValueStack() Once you have a ValueStack object, you can use the following methods to manipulate that object − Sr.No ValueStack Methods & Description 1 Object findValue(String expr) Find a value by evaluating the given expression against the stack in the default search order. 2 CompoundRoot getRoot() Get the CompoundRoot which holds the objects pushed onto the stack. 3 Object peek() Get the object on the top of the stack without changing the stack. 4 Object pop() Get the object on the top of the stack and remove it from the stack. 5 void push(Object o) Put this object onto the top of the stack. 6 void set(String key, Object o) Sets an object on the stack with the given key so it is retrievable by findValue(key,…) 7 void setDefaultType(Class defaultType) Sets the default type to convert to if no type is provided when getting a value. 8 void setValue(String expr, Object value) Attempts to set a property on a bean in the stack with the given expression using the default search order. 9 int size() Get the number of objects in the stack. The OGNL The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion. The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a root or default object within the context. The properties of the default or root object can be referenced using the markup notation, which is the pound symbol. As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContext map consists of the following − Application − Application scoped variables Session − Session scoped variables Root / value stack − All your action variables are stored here Request − Request scoped variables Parameters − Request parameters Atributes − The attributes stored in page, request, session and application scope It is important to understand that the Action object is always available in the value stack. So, therefore if your Action object has properties “x” and “y” there are readily available for you to use. Objects in the ActionContext are referred using the pound symbol, however, the objects in the value stack can be directly referenced. For example, if employee is a property of an action class, then it can be referenced as follows − <s:property value = “name”/> instead of <s:property value = “#name”/> If you have an attribute in session called “login” you can retrieve it as follows − <s:property value = “#session.login”/> OGNL also supports dealing with collections – namely Map, List and Set. For example to display a dropdown list of colors, you could do − <s:select name = “color” list = “{”red”,”yellow”,”green”}” /> The OGNL expression is clever to interpret the “red”,”yellow”,”green” as colours and build a list based on that. The OGNL expressions will be used extensively in the next chapters when we will study different tags. So rather than looking at them in isolation, let us look at it using some examples in the Form Tags / Control Tags / Data Tags and Ajax Tags section. ValueStack/OGNL Example Create Action Let us consider the following action class where we are accessing valueStack and then setting few keys which we will access using OGNL in our view, i.e., JSP page. package com.tutorialspoint.struts2; import java.util.*; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { private String name; public String execute() throws Exception { ValueStack stack = ActionContext.getContext().getValueStack(); Map<String, Object> context = new HashMap<String, Object>(); context.put(“key1”, new String(“This is key1”)); context.put(“key2”, new String(“This is key2”)); stack.push(context); System.out.println(“Size of the valueStack: ” + stack.size()); return “success”; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Actually, Struts 2 adds your action to the top of the valueStack when executed. So, the usual way to put stuff on the Value Stack is to add getters/setters for the values to your Action class and then use <s:property> tag to access the values. But I”m showing you how exactly ActionContext and ValueStack work in struts. Create Views Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. This view will be displayed in case action returns success − <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Hello World</title> </head> <body> Entered value : <s:property value = “name”/><br/> Value of key 1 : <s:property value = “key1” /><br/> Value of key 2 : <s:property value = “key2” /> <br/> </body> </html> We also need to create index.jsp in the WebContent folder whose content is as follows − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC

Struts2 – Actions

Struts 2 – Actions ”; Previous Next Actions are the core of the Struts2 framework, as they are for any MVC (Model View Controller) framework. Each URL is mapped to a specific action, which provides the processing logic which is necessary to service the request from the user. But the action also serves in two other important capacities. Firstly, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result. Secondly, the action must assist the framework in determining which result should render the view that will be returned in the response to the request. Create Action The only requirement for actions in Struts2 is that there must be one noargument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method. Optionally you can extend the ActionSupport class which implements six interfaces including Action interface. The Action interface is as follows − 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; } Let us take a look at the action method in the Hello World example − package com.tutorialspoint.struts2; public class HelloWorldAction { private String name; public String execute() throws Exception { return “success”; } public String getName() { return name; } public void setName(String name) { this.name = name; } } To illustrate the point that the action method controls the view, let us make the following change to the execute method and extend the class ActionSupport as follows − package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { private String name; public String execute() throws Exception { if (“SECRET”.equals(name)) { return SUCCESS; } else { return ERROR; } } public String getName() { return name; } public void setName(String name) { this.name = name; } } In this example, we have some logic in the execute method to look at the name attribute. If the attribute equals to the string “SECRET”, we return SUCCESS as the result otherwise we return ERROR as the result. Because we have extended ActionSupport, so we can use String constants SUCCESS and ERROR. Now, let us modify our struts.xml file as follows − <?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.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success”>/HelloWorld.jsp</result> <result name = “error”>/AccessDenied.jsp</result> </action> </package> </struts> Create a View Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. To do this, right click on the WebContent folder in the project explorer and select New >JSP File. This file will be called in case return result is SUCCESS which is a String constant “success” as defined in Action interface − <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value = “name”/> </body> </html> Following is the file which will be invoked by the framework in case action result is ERROR which is equal to String constant “error”. Following is the content of AccessDenied.jsp <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Access Denied</title> </head> <body> You are not authorized to view this page. </body> </html> We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where the user can click to tell the Struts 2 framework to call the executemethod of the HelloWorldAction class and render the HelloWorld.jsp view. <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action = “hello”> <label for = “name”>Please enter your name</label><br/> <input type = “text” name = “name”/> <input type = “submit” value = “Say Hello”/> </form> </body> </html> That”s it, there is no change required for web.xml file, so let us use the same web.xml which we had created in Examples chapter. Now, we are ready to run our Hello World application using Struts 2 framework. Execute the Application Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you following screen − Let us enter a word as “SECRET” and you should see the following page − Now enter any word other than “SECRET” and you should see the following page − Create Multiple Actions You will frequently define more than one actions to handle different requests and to provide different URLs to the users, accordingly you will define different classes as defined below − package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; class MyAction extends ActionSupport { public static String GOOD = SUCCESS; public static String BAD = ERROR; } public class HelloWorld extends ActionSupport { … public String execute() { if (“SECRET”.equals(name)) return MyAction.GOOD; return MyAction.BAD; } … } public class SomeOtherClass extends ActionSupport { … public String execute() { return MyAction.GOOD; } … } You will configure these actions in struts.xml file as follows − <?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.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorld” method = “execute”> <result name =

Struts2 – Home

Struts 2 Tutorial Job Search PDF Version Quick Guide Resources Discussion Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. This framework is designed to streamline the full development cycle from building, to deploying and maintaining applications over time. Apache Struts 2 was originally known as Web Work 2. This tutorial will teach you, how to use Apache Struts for creating enterprise-ready Java web applications in simple and easy steps. Audience This tutorial is designed for Java programmers who are interested to learn the basics of Struts 2.x framework and its applications. Prerequisites Before proceeding with this tutorial, you should have a good understanding of the Java programming language. A basic understanding of MVC Framework and JSP or Servlet is very helpful. Print Page Previous Next Advertisements ”;

Struts2 – Overview

Struts 2 – Overview ”; Previous Next Struts2 is a popular and mature web application framework based on the MVC design pattern. Struts2 is not just a new version of Struts 1, but it is a complete rewrite of the Struts architecture. The Webwork framework initially started with Struts framework as the basis and its goal was to offer an enhanced and improved framework built on Struts to make web development easier for the developers. After a while, the Webwork framework and the Struts community joined hands to create the famous Struts2 framework. Struts 2 Framework Features Here are some of the great features that may force you to consider Struts2 − POJO Forms and POJO Actions − Struts2 has done away with the Action Forms that were an integral part of the Struts framework. With Struts2, you can use any POJO to receive the form input. Similarly, you can now see any POJO as an Action class. Tag Support − Struts2 has improved the form tags and the new tags which allow the developers to write less code. AJAX Support − Struts2 has recognized the take over by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, this function is very similar to the standard Struts2 tags. Easy Integration − Integration with other frameworks like Spring, Tiles and SiteMesh is now easier with a variety of integration available with Struts2. Template Support − Support for generating views using templates. Plugin Support − The core Struts2 behavior can be enhanced and augmented by the use of plugins. A number of plugins are available for Struts2. Profiling − Struts2 offers integrated profiling to debug and profile the application. In addition to this, Struts also offers integrated debugging with the help of built in debugging tools. Easy to Modify Tags − Tag markups in Struts2 can be tweaked using Freemarker templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS knowledge is enough to modify the tags. Promote Less configuration − Struts2 promotes less configuration with the help of using default values for various settings. You don”t have to configure something unless it deviates from the default settings set by Struts2. View Technologies − Struts2 has a great support for multiple view options (JSP, Freemarker, Velocity and XSLT) Listed above are the Top 10 features of Struts 2 which makes it as an Enterprise ready framework. Struts 2 Disadvantages Though Struts 2 comes with a list of great features, there are some limitations of the current version – Struts 2 which needs further improvement. Listed are some of the main points − Bigger Learning Curve − To use MVC with Struts, you have to be comfortable with the standard JSP, Servlet APIs and a large & elaborate framework. Poor Documentation − Compared to the standard servlet and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized. Less Transparent − With Struts applications, there is a lot more going on behind the scenes than with normal Java-based Web applications which makes it difficult to understand the framework. Final note, a good framework should provide generic behavior that many different types of applications can make use of it. Struts 2 is one of the best web frameworks and being highly used for the development of Rich Internet Applications (RIA). Print Page Previous Next Advertisements ”;