Download struts2-core-2.1.2.jar: struts2 core « s « Jar File Download. MF META-INF/hdiv-tags.tld META-INF/maven/org.hdiv/hdiv-struts-2.0.11/pom.properties META-INF/maven/org.hdiv/hdiv-struts-2.0.11/pom.xml NOTICE.txt.
( JavaServer Page): JavaServer Page allows programmer to embed java code directly in the HTML code. Jsp can call custom java classes ( taglibs) with HTML-like tags.
Separates both dynamic content(java code) and presentation( HTML code) of a Web page. Struts 2: Apache struts is an open source Java EE framework to develop web applications.It supports model– view– controller ( MVC) architecture.It is a widely used framework for application development. Struts framework comes in the form of jar files, so add struts jar files to the lib folder. Hibernate 4: Hibernate is an object-relational mapping ( ORM) framework and it is a free software. Hibernate’s primary feature is mapping from Java classes to database tables (ie From Java data types to SQL data types) and it provides data query and retrieval facilities.
Hibernate provides an SQL language called Hibernate Query Language ( HQL) which allows SQL-like queries to be written against Hibernate’s data objects. Require Java 6 or higher version (building Hibernate from source requires JDK 7 due to a bug in the JDK 6 compiler). Basic requirements for Jsp, Struts 2 and hibernate 4 example. Softwares: Java. GlassFish server. Eclipse IDE ( ). Struts 2 Jar files: ( ).
Commons-fileupload-1.3.1.jar ( ) commons-io-2.2.jar ( ) commons-lang3-3.1.jar ( ) commons-logging-1.1.3.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.16.3.jar ( ) xwork-core-2.3.16.3.jar ( ) Hibernate 4 Jar files: javax.servlet.jar ( ). Javax.servlet.jsp.jar. Antlr-2.7.7.jar. Dom4j-1.6.1.jar. Hibernate-commons-annotations-4.0.5.Final.jar. Hibernate-core-4.3.6.Final.jar. Hibernate-jpa-2.1-api-1.0.0.Final.jar.
Jandex-1.1.0.Final.jar. Javassist-3.18.1-GA.jar. Jboss-logging-3.1.3.GA.jar. Jboss-logging-annotations-1.2.0.Beta1.jar. Jboss-transaction-api1.2spec-1.0.0.Final.jar. Mysql-connector-java-5.1.6.jar.
Source files: login.jsp UserAuthentication.java User.java web.xml hibernate.cfg.xml Mapping.hbm.xml struts.xml home.jsp error.jsp Complete Directory Structure in Eclipse: Create a dynamic web project in any IDE and copy the below source code to appropriate files. Source code for Jsp, Struts 2 and hibernate 4 example: login.jsp.
Struts 2 Architecture Struts 2 is a very elegant and flexible front controller framework based on many standard technologies like Java Filters, Java Beans, ResourceBundles, XML etc. For the Model, the framework can use any data access technologies like JDBC, EJB, Hibernate etc and for the View, the framework can be integrated with JSP, JTL, JSF, Jakarta Velocity Engine, Templates, PDF, XSLT etc. Exception Handling: The Struts 2 Framework allows us to define exception handlers and inceptors. Exception Handlers: Exception handlers allows us to define the exception handling procedure on global and local basis.
Framework catches the exception and then displays the page of our choice with appropriate message and exception details. Interceptors:The Interceptors are used to specify the 'request-processing lifecycle' for an action. Interceptors are configured to apply the common functionalities like workflow, validation etc. To the request. Struts 2 Architecture The following diagram depicts the architecture of Struts 2 Framework and also shows the the initial request goes to the servlet container such as tomcat, which is then passed through standard filer chain.
Image: Struts 2 Architecture. The filter chain includes:.
Action ContextCleanUp filter: The ActionContextCleanUp filter is optional and it is useful when integration has to be done with other technologies like SiteMash Plugin. FilterDispatcher: Next the FilterDispatch is called, which in turn uses the ActionMapper to determine whether to invoke an Action or not. If the action is required to be invoked, the FilterDispatcher delegates the control to the ActionProxy. ActionProxy: The ActionProxy takes help from Configuration Files manager, which is initialized from the struts.xml. Then the ActionProxy creates an ActionInvocation, which implements the command pattern.
The ActionInvocation process invokes the Interceptors (if configured) and then invokes the action. The the ActionInvocation looks for proper result.
Then the result is executed, which involves the rendering of JSP or templates. Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file. If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.
Comparison of Struts 1 and Struts 2. Let us see the basic difference between Struts 1 and 2 framework. Unlike Struts 1, Struts 2 does not need to implement Action class.
The Action in Struts 2 is a POJO object. Thus making it easy to unit test the code. Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action.
Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation.
Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. Struts 1 integrates with JSTL, so it uses the JSTL EL.
The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called “Object Graph Notation Language” (OGNL). Struts 1 uses the standard JSP mechanism for binding objects into the page context for access. Struts 2 uses a “ValueStack” technology so that the taglibs can access values without coupling your view to the object type it is rendering. Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle. Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.
Before we starts with our first Hello World Struts 2 Example, we will need few tools. JDK 1.5.
Tomcat 5.x above or any other container (Glassfish, JBoss, Websphere, Weblogic etc). Eclipse 3.2.x.
Apache Struts2 JAR files:. Following are the list of JAR files required for this application. commons-logging-1.0.4.jar. freemarker-2.3.8.jar. ognl-2.6.11.jar. struts2-core-2.0.12.jar.
xwork-2.0.6.jar Note that depending on the current version of Struts2, the version number of above jar files may change. Login Page Create a basic Struts2 application with a Login page. User will enter login credential and if authenticated successfully she will be redirected to a Welcome page which will display message ” Howdy,!“. If user is not authenticated, she will be redirected back to the login page. Validation Framework Tutorial with Example Struts Action 2 relies on a validation framework provided by XWork to enable the application of input validation rules to your Actions before they are executed.
Struts2 Validation Framework allows us to separate the validation logic from actual Java/JSP code, where it can be reviewed and easily modified later. The Struts2 Validation Framework alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data. Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic by implementing java interface com.opensymphony.xwork2.Validator and plug it into validation framework as a re-usable component. Validator uses XML configuration files to determine which validation routines should be installed and how they should be applied for a given application. Validators.xml file contains all common validators declaration.
If validators.xml file is not present in classpath, a default validation file is loaded from path com/opensymphony/xwork2/validator/validators/default.xml. The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.
Validators Scope There are two types of Validators in Struts2 Validation Framework. Field Validators. Non-field validators Field validators, as the name indicate, act on single fields accessible through an action.
A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view. Note that we are mapping the CustomerAction class with name customer. Also on success user will be redirected to SuccessCustomer.jsp page. Notice that there is another result tag with name input.
Whenever the validation logic encounter some validation error, it redirects the user back to page specified as input. Thus in our example, user will be redirected back to Customer.jsp in case of any errors. Create two new JSPs Customer.jsp (which will contain Customer form) and SuccessCustomer.jsp (which will be displayed on success). That’s All Folks Execute the application and test the Customer form with different values. Customer page Customer page with errors Customer page on success Download Source Code Interceptors Tutorial with Example Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing.
They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc. Request is generated by user and sent to Servlet container. Servlet container invokes FilterDispatcher filter which in turn determines appropriate action. One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.
Action is executed and the Result is generated by Action. The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.
Thus the Struts2 Interceptors removes cross cutting tasks such as logging from action components and create cleaner separation of MVC. Struts2 comes with default list of Interceptors already configured in the application in struts-default.xml file. We can create our own custom Interceptors and plugin into a Struts2 based web application. Framework creates an object of ActionInvocation that encapsulates the action and all the interceptors configured for that action. Each interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in reverse order to perform post processing work. Interceptors can alter the workflow of action.
It may prevent the execution of action. Our Goal Our goal will be to create a customer interceptor MyLoggingInterceptor, which will log the request before any action is called. Also it will prints the Action class name and execution time of action in milliseconds. Create Logging Interceptor Create a java class MyLoggingInterceptor in package net.viralpatel.struts2.interceptors and copy following content into it. This code has to be added after tag in Here we have configured a new interceptor mylogging with tag. Also note that we have defined an interceptor-stack with name loggingStack. This is to make sure Sturts2 calls all the default interceptors as well while calling our custom interceptor.
This is very important as the validation logic will not work in our struts2 application if we ignore the default stack of interceptors. We can make the new loggingStack as default interceptor stack or can configure it at each action level. In order to make it default stack, we should add following in struts.xml.
Destroying MyLoggingInterceptor. Download Source Code Tiles Plugin Tutorial with Example in Eclipse Nowadays, website are generally divided into pieces of reusable template that are being rendered among different web pages. For example a site containing header, footer, menu etc. This items remains same through out the website and give it a common look and feel.
It is very difficult to hard code this in each and every webpage and if later a change is needed than all the pages needs to be modified. Hence we use templatization mechanism. We create a common Header, Footer, Menu page and include this in each page. Tiles Plugin allow both templating and componentization. In fact, both mechanisms are similar: you define parts of page (a “Tile”) that you assemble to build another part or a full page.
A part can take parameters, allowing dynamic content, and can be seen as a method in JAVA language. Tiles is a templating system used to maintain a consistent look and feel across all the web pages of a web application. It increase the reusability of template and reduce code duplication.
A common layout of website is defined in a central configuration file and this layout can be extended across all the webpages of the web application. Our Application Layout Our goal is to add Header, Footer and Menu to our StrutsHelloWorld application.
Following will be the layout of the same. Required JAR files In order to add Tiles support to our Struts2 application, we will need few jar files. Following is the list of JARs in our example. Add these JARs in WEB-INF/lib folder. Configuring Tiles in web.xml To configure Tiles, an entry for listener has to be made in web.xml. Open the web.xml from WEB-INF folder and add following code into it. Here in tiles.xml we have define a template baseLayout.
This layout contains attributes such as Header, Title, Body, Menu and Footer. The layout is then extended and new definitions for Welcome page and Customer page is defined. We have override the default layout and changed the content for Body and Title.
Creating JSPs We will define the template for our webapplication in a JSP file called BaseLayout.jsp. This template will contain different segments of web page (Header, Footer, Menu etc). Create 4 new JSP files BaseLayout.jsp, Header.jsp, Menu.jsp and Footer.jsp and copy following content in each of them. The struts.xml now defines a new Result type for Tiles.
This result type is used in tag for different actions. Also note that we have define a new action customer-form. This is just an empty declaration to redirect user to Customer form page when she clicks Customer link from menu. That’s All Folks Compile and Execute the application in Eclipse and see that the header, menu and footer are properly applied.
Welcome Page with Tiles Customer Page with Tiles Customer Success Page with Tiles Download Source Code File Upload and Save Tutorial with Example. We will use Struts2 built-in FileUploadInterceptor in our example to upload the file. The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element. Required JAR file Before we start, we need to make sure commons-io.jar file is present in the classpath. Following are the list of required Jar files.
Getting Started In order to add file upload functionality we will add an action class FileUploadAction to our project. Create file FileUploadAction.java in package net.viralpatel.struts2. In above class file we have declared few attributes:. private File userImage; - This will store actual uploaded File.
private String userImageContentType; - This string will contain the Content Type of uploaded file. private String userImageFileName; - This string will contain the file name of uploaded file.
The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also follow the naming standard if you providing the content type and file name string.
The name should be ContentType and FileName. For example if the file attribute in action file is private File uploadedFile, the content type will be uploadedFileContentType and file name uploadedFileFileName. Also note in above action class, we have implemented interface org.apache.struts2.interceptor.ServletRequestAware. This is to get servletRequest object. We are using this path to save the uploaded file in execute method. We have used FileUtil.copyFile method of commons-io package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user.
The JSPs Create two JSP file in WebContent folder. UserImage.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server.
User will be sent to SuccessUserImage.jsp file where File details will be displayed. Copy following code into it. Note that in above entry we have specified two parameter to fileUpload interceptor, maximumSize and allowedTypes. These are optional parameters that we can specify to interceptor. The maximumSize param will set the maximum file size that can be uploaded.
By default this is 2MB. And the allowedTypes param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file (image/png,image/gif,image/jpeg,image/pjpeg). 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 That’s All Folks Compile and Execute the project in eclipse and goto link Download Source Code Action Chaining example sometimes you may want to process another action when one action completes. For example on successfully submitting a form you want to render output from other action. This is called Action chaining in Struts 2. One action leads to another one and so on.
Request Action 1 Action 2 Response In Struts 2, this can be achieved by Chain Result. The Chain Result is a result type that invokes an Action with its own Interceptor Stack and Result.
This Interceptor allows an Action to forward requests to a target Action, while propagating the state of the source Action. Below is an example of how to define this sequence. In above code we define three actions: createUserAccount, login and showDashboard. Notice how each action is chained to the next one using tag. Thus when user logs in first time in system, the createAccount action will be used.
Once account is created user is forwarded to login action. Disadvantage of Action Chaining The Action chaining must be used with precaution.
Struts2 documentation too doesn’t support this feature. Experience shows that chaining should be used with care. If chaining is overused, an application can turn into “spaghetti code”.
Actions should be treated as a Transaction Script, rather than as methods in a Business Facade. Be sure to ask yourself why you need to chain from one Action to another. Is a navigational issue, or could the logic in Action2 be pushed back to a support class or business facade so that Action1 can call it too? Alternative: Redirect After Post You can use Redirect After Post mechanism in cases where you cannot avoid chaining other actions. This is more or less similar to Action chaining with a major difference. The response is told to redirect the browser to the specified location (a new request from the client).
The consequence of doing this means that the action (action instance, action errors, field errors, etc) that was just executed is lost and no longer available. This is because actions are built on a single-thread model. The only way to pass data is through the session or with web parameters (url?name=value) which can be OGNL expressions. Ajax Tutorial with Example Struts 2 provides built-in support to AJAX using Dojo Toolkit library. If you are new to Dojo, you may want to go through the Introduction of DOJO Toolkit. Struts 2 comes with powerful set of Dojo AJAX APIs which you can use to add Ajax support. In order to add Ajax support, you need to add following JAR file in your classpath: struts2-dojo-plugin.jar Also once we add this JAR file, we need to add following code snippet in whatever JSP file we need to add AJAX support.
Add this head tag in your JSP between tags. This sx:head tag will include required javascript and css files to implement Ajax. AJAX Example: Struts2 Ajax Drop Down Let us add simple AJAX support in our StrutsHelloWorld web application. We will use the base code that we used in previous articles and add Ajax on top of it. We will create a drop down which will Autocomplete and suggest the input.
For this we will add Dojo support to our webapp. Step 1: Adding JAR file As discussed earlier we will add struts2-dojo-plugin.jar in classpath (WEB-INF/lib). Thus, following is the list of required jar files. Note that these jars are needed to run full application including all the samples of previous parts of this tutorial series. Step 2: Create AJAX Action class We will create an action class which will get called for our Ajax example. Create a file AjaxAutocomplete.java in net.viralpatel.struts2 package and copy following content into it.