This is 6 of 8 part of struts 2 tutorial.In this tutorial we will learn how to upload file to server in struts 2 and also how save uploaded file on directory of server machine.

Tutorial Content:

Part-1:Introduction to struts 2
Part-2:configuring struts 2 in eclipse
Part-3:Struts 2 hello world example
Part-4:Login page with validation in struts 2
Part-5:Struts 2 interceptors with example
Part-6:File upload in struts 2
Part-7:Struts 2 ajax example
Part-8:Struts 2 spring 3 integration example 


Struts 2 file upload component can be used to upload mulitpart file in struts 2 application.Struts 2 utilizes in built File upload interceptor for uploading files in struts 2 application.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 :
We need to have 1 jar common-io.jar in your classPath.In configuring struts 2 in eclipse post,we have already added jar in classPath.
Create project named "fileUploadInStruts2".For configuring struts 2 in your eclipse ide please refer configuring struts 2 link.

Project stucture:

Action class: 

For adding file uploading functionality in struts 2,We will create action class named FileUploadAction.java.
Create FileUploadAction.java file under src folder in package org.arpit.javaPostsForLearning.

copy following content in FileUploadAction.java

package org.arpit.javaPostsForLearning;
import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;


public class FileUploadAction extends ActionSupport implements ServletRequestAware {

    private File toBeUploaded;
    private String toBeUploadedFileName;
    private String toBeUploadedContentType;
    private HttpServletRequest servletRequest;
    public String execute()
    {
         String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
         File fileToCreate = new File(filePath, this.toBeUploadedFileName);

         try {
            FileUtils.copyFile(this.toBeUploaded, fileToCreate);
        } catch (IOException e) {
            addActionError(e.getMessage());
        }
        return SUCCESS;
    }
    public File getToBeUploaded() {
        return toBeUploaded;
    }
    public void setToBeUploaded(File toBeUploaded) {
        this.toBeUploaded = toBeUploaded;
    }
    public String getToBeUploadedFileName() {
        return toBeUploadedFileName;
    }
    public void setToBeUploadedFileName(String toBeUploadedFileName) {
        this.toBeUploadedFileName = toBeUploadedFileName;
    }
    public String getToBeUploadedContentType() {
        return toBeUploadedContentType;
    }
    public void setToBeUploadedContentType(
            String toBeUploadedFileNameContentType) {
        this.toBeUploadedContentType = toBeUploadedFileNameContentType;
    }
    @Override
    public void setServletRequest(HttpServletRequest servletRequest) {
        this.servletRequest=servletRequest;
        
    }
    
}
Now we have declared three attributes here

 private File toBeUploaded  //Actual file to be uploaded
 private String toBeUploadedFileName // file name of actual file to be uploaded
 private String toVeUploadedContentType  // content type of actual file to be uploaded

We have provided getters and setters for above attributes.So struts 2 automatically set these value according to file being uploaded.
For example if your file name is "sampleFile" then struts 2 interceptor add three parameters to request.
Three parameters are:
[sampleFile]:file
[sampleFile]FileName:String
[sampleFile]ContentType:String

you can notice here that we have given our action class attributes in same format so it will automatically set these attributes according to file being uploaded.

One more thing is that we have implemented "ServletRequestAware" interface in our action class
This is to get ServletRequest object.This request object is required to get path of server machine where file is to be uploaded.

JSPs:

We will create two jsp files here.fileUpload.jsp will display form for uploading file.On clicking on upload button,File will be saved on server machine and request will be forwarded to uploadSucceed.jsp which will render fileName,content type and uploaded image.

fileUpload.jsp:

Create fileUpload.jsp under WebContent folder.
Copy following content to fileUpload.jsp.

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>file upload page</title>
</head>
<body bgColor="lightblue">
<s:form action="fileUpload" method="post" enctype="multipart/form-data">
    <s:file name="toBeUploaded" label="Choose file to upload" />
    <s:submit value="Upload" align="center"/>
</s:form>
</body>
</html>

We have used <s:file> tag for file upload interface.

uploadSucceed.jsp:
Create jsp named "uploadSucceed.jsp" under WebContent folder.
Copy following content into uploadSucceed.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Successful</title>
<s:head />
</head>
<body>
File Name :
<s:property value="toBeUploadedFileName"></s:property>
Content type:
<s:property value="toBeUploadedContentType"></s:property>
User file :
<s:property value="toBeUploaded"></s:property>
Uploaded file:
<img src="<s:property value="toBeUploadedFileName"/>"></img>
</body>
</html>

Struts.xml:

Create struts.xml under src folder.
Copy following content to struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default" extends="struts-default" namespace="/">
        <action name="fileUpload" class="org.arpit.javaPostsForLearning.FileUploadAction">
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">1048576</param>
                <param name="allowedTypes">
                    image/png,image/gif,image/jpeg,image/pjpeg
        </param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">uploadSucceed.jsp</result>
            <result name="input">fileUpload.jsp</result>
        </action>
    </package>
</struts> 

Web.xml:

It is same as in previous posts except that we have changed welcome file to "fileUpload.jsp"
Copy following content into web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">

 <display-name>fileUploadInStruts2</display-name>
 <filter> 
    <filter-name>
      struts2
    </filter-name>
    <filter-class>
      org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class> 
 </filter>

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

 <welcome-file-list>
 <welcome-file>fileUpload.jsp</welcome-file>
 </welcome-file-list>

</web-app>

Run project:

Right click on project ->run as->run on server
copy resultant url(http://localhost:8080/fileUploadInStruts2/) to your browser.


Now we will browse here text file and click upload.Following screen will appear





















Now again copy http://localhost:8080/fileUploadInStruts2/ url to your browser and press enter
you will get first screen again.We will browse image file named "nature.jpeg" and click on upload.
you will get following screen


















Source code:

Source:Download without jars files 
Source + lib: Download with jars files

Now in next post,we will write struts 2 ajax example.

Interceptors : 

Interceptor is an object which intercepts an action dynamically. It executed before and after the action execution. It Allows the developers to write a code which can execute and after the action. It executed before and after the code. It can prevent an action before executing.  

Features like double-submit guards, type conversion, object population, validation, file upload, page preparation, and more, are all implemented with the help of Interceptors. Each and every Interceptor is pluggable, so you can decide exactly which features an Action needs to support.

As we have seen request workflow in Introduction to struts2 part.
  1. Request is generated by user and sent to Servlet container.
  2. Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.
  3. One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.
  4. Action is executed and the Result is generated by Action.
  5. The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.
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.Now Internal workflow is:
  • 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.

Goal :

We will create two interceptor class and one action class to show workflow . We will  also learn how to declare intercpetor and also to do mapping between interceptor and action in struts.xml.

Create project named "InterceptorsWorkflow".For configuring struts 2 in your eclipse ide please refer configuring struts 2 link.

Project structure:

Interceptor classes:

Create class FirstInterceptor.java in src folder.

copy following code in FirstInterceptor.java.

package org.arpit.javapostsForLearning;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class FirstInterceptor implements Interceptor{

    @Override
    public void destroy() {
        
        
    }

    @Override
    public void init() {
            
    }

    @Override
    public String intercept(ActionInvocation actionInvocation) throws Exception {
        
        String startInterceptor="   Start Interceptor 1";
        System.out.println(startInterceptor);
        String result=actionInvocation.invoke();
        String endInterceptor="   End Interceptor 1";
        System.out.println(endInterceptor);
        return result;
    }

}
 
Create one more class SecondInterceptor.java in src folder. copy following code into SecondInterceptor.java
package org.arpit.javapostsForLearning;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;


public class SecondInterceptor implements Interceptor{

 @Override
 public void destroy() {
    
 }

 @Override
 public void init() {
  
 }

 @Override
 public String intercept(ActionInvocation actionInvocation) throws Exception {
  
  String startInterceptor="   Start Interceptor 2";
  System.out.println(startInterceptor);
  String result=actionInvocation.invoke();
  String endInterceptor="   End Interceptor 1";
  System.out.println(endInterceptor);
  return result;
 }

} 
Now both classes implements Interceptor interface. The Interface Interceptor (com.opensymphony.xwork2.interceptor ) extends Serializable interface and is a stateless class. The Interceptor Interface have three methods are as follows-
void destroy( ) - This method is used to clean up resources allocated by the interceptor.
void init( ) - This method is called at the time of intercept creation but before the request processing using intercept, and to initialize any resource needed by the Interceptor.
String intercept(ActionInvocation invocation ) - This method allows the Interceptor to intercept processing and to do some processing before and/or after the processing ActionInvocation.

We will see more about this later.

Struts.xml:

We have seen in previous tutorial that struts.xml defines mapping between request to corresponding action.

How to declare interceptor in Struts.xml:

In <package> tag in struts.xml, we can declare all our interceptors in <interceptors> tag.

<interceptors>
            <interceptor name="name of interceptor" class="fully qualified name of class">
<interceptors>

For attaching interceptors to action,we can use <interceptor-ref> under <action> tag

<interceptor-ref name="name of intercept"/>

so now we will declare two above interceptors in struts.xml

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


    <package name="default" extends="struts-default" namespace="/">
        <interceptors>
            <interceptor name="firstInterceptor"
                class="org.arpit.javapostsForLearning.FirstInterceptor" />
            <interceptor name="secondInterceptor"
                class="org.arpit.javapostsForLearning.SecondInterceptor" />

        </interceptors>
                
        <action name="Dummy" class="org.arpit.javapostsForLearning.DummyAction">
        <interceptor-ref name="firstInterceptor"/>
        <interceptor-ref name="secondInterceptor"/>
            <result name="success">Welcome.jsp</result>
            <result name="input">login.jsp</result>
        </action>
    </package>
</struts>

Action:

We will create one action class named DummyAction.java under src.Action class will be same as created in previous tutorials.

package org.arpit.javapostsForLearning;
import com.opensymphony.xwork2.ActionSupport;

public class DummyAction extends ActionSupport{

    public String execute()
    {
        System.out.println("   In Action");
        return SUCCESS;
    }
}

JSP:


Create one jsp named "ForCallingAction.jsp" in Webcontent.We are creating this jsp just to call action.We will create a button.On clicking of that button an action "Dummy" will be called.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dummy Action</title>
</head>
<body bgColor="lightBlue">
<s:form action="Dummy">
<s:submit value="For calling Dummy Action" align="center"/>
 </s:form>
</body>
</html>

Create another jsp named "Welcome.jsp" As In DummyAction class,execute returns "success" so we will be directed to this page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
Welcome !!!
</body>
</html>

Web.xml:

Web.xml will be same as previous tutorials except that we will change welcomeFile to "ForCallingAction.jsp"
Copy following code into web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>InterceptorsWorkFlow</display-name>

 <filter> 
    <filter-name>
       struts2
    </filter-name>
    <filter-class>
       org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
 </filter>

 <filter-mapping>
     <filter-name>struts2</filter-name>
     <url-pattern>/*</url-pattern>   
 </filter-mapping>
 <welcome-file-list>
 <welcome-file>ForCallingAction.jsp</welcome-file>
 </welcome-file-list>
</web-app>


Run project:

right click on project->run as->run on server
copy resultant url to browser.We will get following page.


 On clicking on button "For calling Dummy Action"  We will get following page


 We got welcome page here but we are more interested in how interceptors worked.So when we will see our console we will get something like this









Request Workflow:

 ActionInvocation object is main part of interceptor.The information of the sequence in which these interceptors are executed for the action is stored in the ActionInvocation object in form of stack.

Action method will only called once the interceptor stack has been called fully.This means that once the first interceptors has been called successfully in the stack it will call next interceptor defined in the stack and there reference being stored in the stack this chain will keep on calling till last interceptor in the stack is called.

  invocation.invoke()

This call is key to call next interceptor  defined in the stack or of this is the last it will call the desired function in action class.

Now in other case suppose some of the interceptor failed say workflow it will return the result as INPUT and will halt the further execution of the interceptor and framework will output corresponding error JSP/template to user.

Then come the post processing in this case interceptors will be called in reverse order i.e. top most or latest executed interceptor will be called first and then so on so.

The idea for the post processing is to do any clean-up work or any other things which needs to be done(like cleaning up resources etc)

For the first interceptor,the invoke() method is called by the ActionProxy object.
so in our example

  • FirstInterceptor is called by ActionProxy object and intercept method is called and "start interceptor 1 " will be printed to console.
  • Now it calls next interceptor in the stack i.e. SecondInterceptor and intercept method is called and "start interceptor 2" will be printed to console.
  • As there are no more interceptors in the stack,so DummyAction's execute method is called and "In Action" will be printed to console.
  • Now as last interceptor i.e. SecondInterceptor will be called first so "end interceptor 2" will be printed to console.
  • Now first interceptor i.e. FirstInterceptor will be called and "end interceptor 1" will be printed to console.

Source code:

Source:Download without jars files 
Source + lib: Download with jars files

Now in next post,we will learn how to upload file on server in struts 2

This is 4 of 7 part of struts 2 tutorial.

Tutorial Content:

    Introduction to struts 2 configuring struts 2 in eclipse Struts 2 hello world example Login page with validation in struts 2 Struts 2 interceptors with example File upload in struts 2 Struts 2 ajax example Struts 2 spring 3 integration example
In this example we will see how we can validate a login page using Struts 2.

In previous post, we have learned  about mapping from client request to action class and rendering appropriate jsp on the basis of returned string of execute() method of action class.

In this post,we will use struts ui tags to create login page so we will learn how to use tags.
Create project named "LoginAppInStruts2".For configuring struts 2 in your eclipse IDE please refer configuring struts 2 link.

Web.xml:

Create web.xml file in under the folder WebContent/WEB-INF.
copy following content in web.xml 

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>LoginAppInStruts2</display-name>
 <filter> 
     <filter-name>
        struts2
     </filter-name>
     <filter-class>
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
     </filter-class>
 </filter>

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

 <welcome-file-list>
     <welcome-file>login.jsp</welcome-file>
 </welcome-file-list>
</web-app>

JSP: 

Login.jsp:

Create login page as login.jsp under WebContent.

copy following content into login.jsp

&<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

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

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>

<s:head />
 </head>
<body bgColor="lightBlue">
<s:form action="Login">
    <s:textfield name="userName" label="User Name" />
    <s:password name="password" label="Password" />
    <s:submit value="Login" />
</s:form>

</body>
</html>


<%@taglib uri="/struts-tags" prefix="s" %> is a directive used in jsp for including struts tag files.

The <s:head /> tag should be placed in the head section 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.

The s:form tag contains all the form elements. The action attribute contains the action name to wich the form should be submitted. This action name should be same as the one specified in the XML declarative architecture. In this example we use struts.xml file to do the configuration.

The textfield tag is used create a text box. The label attribute of the textfield tag contains the name to be displayed on the page and the name attribute contains the name of the property in the action class to be mapped. The password tag is same as the textfield tag except that the input value is masked. The submit tag is used to create a submit button, the value "Login" represents the label of the button.

Note that the code is simple without any HTML tables, this is because Struts 2 will automatically create the necessary tables for the page based on the theme selected. By default the XHTML theme is selected.

When user click on login button,Request is forwarded to Login action.

Welcome.jsp:

Create Welcome.jsp under WebContent.

copy following content into Welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>login Successful</title>
</head>
<body>
Welcome <s:property value="userName"/>!!!
</body>
</html>

Action class:

 Our LoginAction class extends ActionSupport. It is good to extend ActionSupport class as it provides default implementation for most common tasks. 

 Create LoginAction.java under src
copy following code into LoginAction.java

package org.arpit.javapostsForLearning;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {

    private String userName;
    private String password;

    public String execute() {
        return SUCCESS;
    }

   
    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 void validate() {
        if (getUserName().length() == 0) {
            addFieldError("userName", "UserName.required");
        } else if (!getUserName().equals("Arpit")) {
            addFieldError("userName", "Invalid User");
        }
        if (getPassword().length() == 0) {
            addFieldError("password", getText("password.required"));
        }
    }
}

The ActionSupport class implements Action interface which exposes the execute() method.
The following constants are declared in the Action interface which can be used as return values in the execute() method.
public static final String ERROR = "error"
public static final String INPUT = "input" 
public static final String LOGIN = "login" 
public static final String NONE = "none" 
public static final String SUCCESS = "success" ERROR is returned when the action execution fails.
INPUT is returned when the action requires more input from the user.
LOGIN is returned when the user is not logged into the system.
NONE is returned when the action execution is successfull and there are no views to display.
SUCCESS is returned when the action executed successfully and the corresponding result is displayed to the user.

Now in our action class we have two attributes:

private String userName;- It should be same as name of textfield for getting userName as input defined in login.jsp.
private String password;-It should same as name of textfield for getting password as input defined in login.jsp

<s:property> tag -you can notice that we have used Struts tag <s:property>.It renders value of attribute of action class.In this case,attribute is userName of loginAction.java.So whatever user entered in userName textfield will appear at that place in Welcome.jsp.

Struts.xml:

Create struts.xml in src.struts.xml provides mapping between url to action mapping.

copy following code into struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="LoginAction" />
    <package name="default" extends="struts-default" namespace="/">
        <action name="Login" class="org.arpit.javapostsForLearning.LoginAction" >
            <result name="success">Welcome.jsp</result>
            <result name="input">login.jsp</result>
        </action>
    </package>
</struts>
Here our "default" package extends "struts-default" package. By extending the "struts-default" package the action will by default inherit the set of interceptors defined in the defaultstack. The "struts-default" package is defined in the struts-default.xml file.

All the common tasks done by the Actions are seperated and placed in different interceptors. You can define an interceptor stack for each action. Most commonly used interceptors are grouped in defaultstack of the struts-default package. The defaultstack will be sufficient in most cases. The inteceptors will be fired in the order in which they are declared in the stack both before and after the action is executed.

<interceptor-stack name="defaultStack">
     <interceptor-ref name="exception"/>
     <interceptor-ref name="alias"/>
     <interceptor-ref name="servletConfig"/>
     <interceptor-ref name="prepare"/>
     <interceptor-ref name="i18n"/>
     <interceptor-ref name="chain"/>
     <interceptor-ref name="debugging"/>
     <interceptor-ref name="profiling"/>
     <interceptor-ref name="scopedModelDriven"/>
     <interceptor-ref name="modelDriven"/>
     <interceptor-ref name="fileUpload"/>
     <interceptor-ref name="checkbox"/>
     <interceptor-ref name="staticParams"/>
     <interceptor-ref name="actionMappingParams"/>
     <interceptor-ref name="params">
     <param name="excludeParams">dojo\..*,^struts\..*</param>
     </interceptor-ref>
     <interceptor-ref name="conversionError"/>
     <interceptor-ref name="validation">
     <param name="excludeMethods">input,back,cancel,browse</param>
     </interceptor-ref>
     <interceptor-ref name="workflow">
     <param name="excludeMethods">input,back,cancel,browse</param>
     </interceptor-ref>
 </interceptor-stack>
Now lets see the roles played by the different interceptors.

The params interceptor helps in transfering the request data onto the action object.

The workflow interceptor controls the flow of cotrol.

The workflow interceptor checks whether the action implements the Validateable interface , if it does, the workflow interceptor will invoke the validate() method of the Action class.

In the validate() method we validate the user name and the password. If the validation fails an error is added using the addFieldError() method.

The validate() method doesn't return any errors, instead it stores all the errors with the help of the ValidationAware interface.

Now the workflow interceptor will check any validation errors has occured. If any error has occured the workflow interceptor will stop the request processing and transfer the control to the input page with the appropriate error messages.

The ResourceBundle:

ResourceBundle is very useful Java entity that helps in putting the static content away from the source file. Most of the application define a resource bundle file such as ApplicationResources.properties file which contains static messages such as Username or Password and include this with the application.

The properties files should have the same name as the Action class. In our case the properties file name is "LoginAction.properties" and the Action name is "LoginAction.java". This property file should be present in WEB-INF/classes folders when the source is compiled.

Create LoginAction.properties under src.Copy following content to LoginAction.properties.


userName.required=user name is required
password.required=password is required

Run Project:

right click on project->run as->run on server


















so when you paste resultant url(http://localhost:8080/LoginAppInStruts2/) to your browser,you will get some thing like this.


















If you directly press login button without entering anything.You will get following.
















if you enter userName as "mandliya" .you will get following.

















If you enter userName as "arpit" and password also as "arpit".you will get
















Source code:

Source:Download without jars files 
Source + lib: Download with jars files
 
Now in next post,we will understand concept of interceptors in detail.

This is 3 of 8 part of struts 2 tutorial.It provides struts 2 hello world example.

Tutorial Content:

    Introduction to struts 2 configuring struts 2 in eclipse Struts 2 hello world example Login page with validation in struts 2 Struts 2 interceptors with example File upload in struts 2 Struts 2 ajax example Struts 2 spring 3 integration example

lets start with first struts2 application.



We will implement modules described in above diagram in our project.
Create dynamic web project named "Struts2FirstProject".For configuring struts 2 in your eclipse ide please refer configuring struts 2 link.

The web.xml file:

The web.xml configuration file is a J2EE configuration file that determines how elements of the HTTP request are processed by the servlet container. It is not strictly a Struts2 configuration file, but it is a file that needs to be configured for Struts2 to work.
As discussed earlier, this file provides an entry point for any web application. The entry point of Struts2 application will be a filter defined in deployment descriptor (web.xml). Hence we will define an entry of FilterDispatcher class in web.xml. The web.xml file needs to be created under the folder WebContent/WEB-INF.

copy following content in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">

 <display-name>Struts2FirstProject</display-name>
 <filter> 
      <filter-name>
          struts2
     </filter-name>
      <filter-class>
          org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
      </filter-class>
      </filter>

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

 <welcome-file-list>
  <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Action Class:

We will have action class which is simple POJO class having attributes and method.
By default execute() method is called when client request goes to action class.

Create TutorialAction.java under src.Here we have TutorialAction.java as action class in our project.



copy following content into TutorialAction.java
package org.arpit.javapostsForLearning;

public class TutorialAction {

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

JSP:

Create two jsp files named "TutorialView.jsp" and "Error.jsp" under WebContent.




copy following content into TutorialView.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts2 tutorial</title>
</head>
<body bgColor="lightblue">
Hello world!!!This is Struts 2 tutorial
</body>
</html>

copy following content into Error.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Error!!!!
</body>
</html>

The struts.xml file:

strut2.xml provides mapping between url to action mapping.

So if client enters "http://mywebapp/getTutorial" then Tutorial action will be called.

Create strut2.xml under src folder.


copy following content into struts.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
 <package name="default" extends="struts-default" namespace="/">
<action name="getTutorial" class="org.arpit.javapostsForLearning.TutorialAction">
<result name="success">TutorialView.jsp</result>
<result name="error">Error.jsp</result>
</action>
</package>
</struts>




This diagram describes the request workflow :

  1. Request(http://localhost:8080/Strut2FirstProject/getTutorial) is generated by client and sent to Servlet container.
  2. Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.In this project,getTutorial action goes to TutorialAction class.
  3. In tutorialAction,execute() method is executed and returns "success"
  4. As per mapping in struts2.xml,<result> name is matched with returned string "success".
  5. Accordingly,TutorialView.jsp is rendered and returned to user.
Now finally we will run our project.

right click on project->run as->run on server





so when you paste resultant url to your browser,you will get some thing like this.



  We are getting this error because we have declared welcome file as "default.jsp" which do not exist.
  so if you paste "http://localhost:8080/Strut2FirstProject/getTutorial" you will get your output as



as we included action(getTutorial) in url,It rendered "tutorialView.jsp" as output.

Source code:

click to begin

6MB .zip


Now in next post,we will write another example of login page with validation

This is 2 of 8 part of struts 2 tutorial.In this part,we will configure struts 2 in eclipse.

Tutorial Content:

    Introduction to struts 2 configuring struts 2 in eclipse Struts 2 hello world example Login page with validation in struts 2 Struts 2 interceptors with example File upload in struts 2 Struts 2 ajax example Struts 2 spring 3 integration example

First you need to download struts 2 framework from apache website .Click on "Download now" and Struts 2 will be downloaded on your machine.

Now Open your eclipse environment.




Click on Files->New->Other




Click on web->Dynamic web project




Write your project Name in the text box.I have written "Strut2FirstProject"
Now here,I am assuming you have apache tomcat server installed in your machine.If you 
have target runtime as none then you can refer configure Apache Tomcat in Eclipse IDE.
Now click on Finish button.


Now go to location where you have download strut2 package and open lib
folder.you can have all jars but for now you can copy following jars
  • struts2-core-2.3.1.2
  • xwork-core-2.3.1.2
  • ognl-3.4
  • commons-io-2.0.1
  • commons-fileupload-1.2.2
  • javassist-3.11.0.GA
  • freemarker-2.3.18
  • commons-lang-2.5
  • commons-logging-1.1.1
  • commons-logging-api-1.1
  • struts2-dojo-plugin-2.3.1.2.jar
Paste all above copied jars to WebContent->WEB-INF->lib




Add all these jars to eclipse build path.
Right click on project(Strut2FirstProject)->properties


Click on Java Build Path and then Add jars as shown in above diagram.


go to project->WebContent->WEB-INF->lib and select all jars then click on ok.


Click on ok.
Now you are done with configuring strut2 in eclipse.You can create your struts 2 project.
In next post we will write Hello world example in struts 2 .


Target Audience

This tutorial is designed for Java programmers who need to understand the Struts 2.x framework and its application.

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.
This is 1 of 8 parts of tutorial series

Tutorial Content:

    Introduction to struts 2 configuring struts 2 in eclipse Struts 2 hello world example Login page with validation in struts 2 Struts 2 interceptors with example File upload in struts 2 Struts 2 ajax example Struts 2 spring 3 integration example

Introduction:

Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time.

Apache Struts2 was originally known as WebWork 2. After working independently for several years, the WebWork and Struts communities joined forces to create Struts2. This new version of Struts is simpler to use and closer to how Struts was always meant to be.
Struts 2 is a pull-MVC framework. i.e. the data that is to be displayed to user has to be pulled from the Action.

Struts2 supports annotation based configurations which are easy to create and more intuitive. Action class in Struts 2 act as the model in the web application. Unlike Struts 1.X, Struts 2 Action class are plain POJO objects, thus simplifying the testing of the code. Struts2 also comes with power APIs to configure Interceptors that reduce greatly the coupling in application. The view part of Struts 2 is highly configurable and it supports different result-types such as Velocity, FreeMarker, JSP, etc.

Architecture:




       Above diagram describes modules in struts 2 .There are 5 modules:
    1. Client-Client generates request which is processed by webContainer.Example of client can be web browser.
    2. Interceptor-Interceptors can execute code before and after an Action is invoked. Most of the framework's core functionality is implemented as Interceptors. Features like double-submit guards, type conversion, object population, validation, file upload, page preparation, and more  are all implemented with the help of Interceptors. Each and every Interceptor is pluggable, so you can decide exactly which features an Action needs to support.
    3. Strut2 xml- Struts2.xml acts as a router which invokes action class for client request.
    4. Action-Action module considered as a model class which invokes business service and function logic.
    5. JSP-It is view part.According to action,Corresponding JSP files is rendered and result is returned to user.

Request Processing Lifecycle


  1. User generates request which then goes to servlet container.
  2. Servlet container invokes FilterDispatcher filter which in turn directs to appropriate action.
  3. One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.
  4. Action is executed and the Result is generated by Action.
  5. The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.

Comparing between struts 1.x and struts 2.x

  1. Struts1 extends the abstract base class by its action class. The problem with struts1 is that it uses the abstract classes rather than interfaces.  An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.  
  2. 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.
  3. 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.
  4. A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1. Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler. 
  5. ActonForms are used in Struts 1. These classes map with the jsp forms. The Action classes use the data in these ActonForms to populate Data Transfer Objects. But in Struts 2 Acton Forms are not used. The jsp forms direct map to POJO, and there is no need to create DTO, thereby the number of classes decreases leading to less maintenance.
  6. 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.
  7. 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. 
  8. 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 Navigation Language" (OGNL).
Now In next post,we will configure struts 2 in eclipse .

The Decorator design pattern attach additional responsibilities to an object dynamically.It is wrap up at another object.It will extend functionality of object without affecting any other object.Decorators provide a alternative to subclassing for extending functionality.

Also known as:

Wrapper

When to use it:

Use Decoraotor
  • to add responsibilities to individual objects dynamically without affecting other objects.
  • for responsibilities that can be withdrawn,
  • When extension by subclassing is impractical.Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination.Or class definition may be hidden or otherwise unavailable for subclassing.

UML diagram for decorator design pattern:

Elements:

  • Component
    • defines interface for objects that can have additional responsibilities added to them.
  • ConcreteComponent
    • defines an object on which additional responsibilities  can be added
  • Decorator
    • maintains a reference to component object and defines an interface that conforms to component's interface.In simple words,It has a component object to be decorated.
  • ConcreteDecorator
    • add responsibilities to the component object.

Example:

In this example,we will decorate a simple room with color and curtains. 
  • Room(Component)
    • It is an interface which creates a blue print for the class which will have decorators
  • SimpleRoom(ConcreteComponent)
    • Object of SimpleRoom class will be decorated.Additional responsibilities will be attached to it dynamically.
  • RoomDecorator(Decorator)
    • It contains reference to Room class which will be decorated.
  •  ColorDecorator(ConcreteDecorator)
    • ColorDecorator will add additional responsibility i.e.add color to room.
  • CurtainDecorator(ConcreteDecorator)
    • CurtainDecorator will add  additional responsibility i.e. add curtains to room.
Logically,you can think of decorator pattern as shown in above diagram.You will first created SimpleRoom object then decorate it with ColorDecorator object and then decorate resultant object with CuratainDecorator.

Java code for above classes:

The following interface is an interface depicting an room.
Room.java(Component):
package org.arpit.javapostsforlearning.designPattern;

public interface Room{
  public String showRoom();
}
 Following class is a concrete implementation of this interface. This is the base class on which the decorators will be added.
SimpleRoom.java(ConcreteComponent) :
package org.arpit.javapostsforlearning.designPattern;

public class SimpleRoom implements Room {

  @Override
  public String showRoom() {
    return "Normal Room";
  }

}
Following class is the decorator class. It is the core of the decorator design pattern. It contains an attribute for the type of interface. Instance is assigned dynamically at the creation of decorator using its constructor. Once assigned that instance method will be invoked.
RoomDecorator.java(Decorator):
package org.arpit.javapostsforlearning.designpattern;

abstract class RoomDecorator implements Room{

  protected Room specialRoom;

  public RoomDecorator (Room specialRoom) {
    this.specialRoom= specialRoom;
  }

 public String showRoom() {
    return specialRoom.showRoom();
  }
}
Following class is our concrete decorator class.It extends abstract decorator.When this decorator is created,base instance is passed to constructor which calls super class constructor.In showRoom() method, we call base class method followed by its own method addColors.This addColors() adds functionality to base instance i.e. decorating  room with colors.
ColorDecorator.java(ConcreteDecorator):
package org.arpit.javapostsforlearning.designpattern;

public class ColorDecorator extends RoomDecorator {

  public ColorDecorator (Room specialRoom) {
    super(specialRoom);
  }

  public String showRoom() {
    return specialRoom.showRoom() + addColors();
  }

  private String addColors() {
    return " + Blue Color";
  }
}
Following class is also concreteDecorator class similar to above class.here addCurtains() add functionality to room(base instance) i.e. decorating room with curtains.
CurtainDecorator.java(ConcreteDecorator):
package org.arpit.javapostsforlearning.designPattern;

public class CurtainDecorator extends RoomDecorator {

  public CurtainDecorator (Room specialRoom) {
    super(specialRoom);
  }

  public String showRoom() {
    return specialRoom.showRoom() + addCurtains();
  }

  private String addCurtains() {
    return " + Red Curtains";
  }
}
DecoratorDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpattern;  
public class DecoratorDesignPatternMain {  

 public static void main(String args[]) {  
  Room room = new CurtainDecorator(new ColorDecorator(new SimpleRoom()));  
  System.out.println(room.showRoom());  
 }  

}  
I have created a simple Room and decorated that with color and curtains.

Output:
Normal room + Blue Color + Red Curtains

Advantages of decorator design pattern: 

  • It is flexible than inheritance because inheritance adds responsibility at compile time but decorator pattern adds at run time.
  • We can have any number of decorators and also in any order.
  • It extends functionality of object without affecting any other object.

Disadvantage of decorator design pattern:

Main disadvantage of decorator design pattern is code maintainability because this pattern creates lots of similar decorator which are sometimes hard to maintain and distinguish.

Decorator Design Pattern in java API:

java.io.BufferedReader;
java.io.BufferedWriter;
java.io.FileReader;
java.io.Reader;
The above classes of java API are designed using decorator design pattern.

Source code:

Source:Download 
 

Java tutorial for beginners Copyright © 2012