Result Types Demo
Struts2 supports various view technologies such as JSP, Tiles, Velocity and Freemarker.
It comes with lot of built in result types implementing com.opensymphony.xwork2.Result interface.
We can customize the rendering logic by providing our own implementation.
This example shows integrating various result types such as,
dispatcher - Useful for JSP integration.
chain - Useful to chain the request processing to another action.
redirect - Useful to redirect to another URL.
redirectAction - Useful to redirect to another action in same or different namespace.
freemarker - Useful for Freemarker integration.
The struts.xml file is shown below,
Actions are listing below,
package demo;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.Action;
public class Action1 implements Action,ServletRequestAware {
HttpServletRequest request;
String message;
public String getMessage () {
return message;
}
public void setMessage ( String message ) {
this .message = message;
}
public void setServletRequest ( HttpServletRequest request ) {
this .request = request;
}
public String execute () throws Exception
{
System.out.println ( "In Action1.execute()" ) ;
setMessage ( "Welcome from Action1" ) ;
request.setAttribute ( "name" , "Name_Action1" ) ;
return SUCCESS;
}
}
package demo;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.Action;
public class Action2 implements Action,ServletRequestAware {
HttpServletRequest request;
public void setServletRequest ( HttpServletRequest request ) {
this .request = request;
}
public String execute () throws Exception
{
System.out.println ( "In Action2.execute() " ) ;
request.setAttribute ( "company" , "Company_Action2" ) ;
return SUCCESS;
}
}
The Home and result JSP are shown below,
The result screens are shown below,
dispatcher result screen (message & name from Action1 and company with default value)
chain result screen (message & name from Action1 and company from Action2. In chaining
it retains the values set in each action of chain.)
redirect result screen (As its redirect we loose values set in Action1, so it shows default values)
redirectAction result screen (As its redirect from Action2 to Action1, we loose the values set in
Action2. So it shows only the values from Action1)
freemarker result screen
Result Type Demo Project Download (5 KB)
Result Type Demo Libs Download (3 MB)