Struts 2 Results Types

Struts 2 Results Types with Example

In this article, I am going to discuss Struts 2 Results Types with Examples. Please read our previous article where we discussed Struts 2 Custom Interceptors.

What are the Results Types in Struts 2?

In the Struts2 MVC framework, the <results> tag serves as the view component. The responsibility of the action is to execute the business logic. Once the business logic is executed, the next step is to display the view using the <results> tag.

However, Struts2 doesn’t restrict you to using JSP as the view technology. The whole purpose of the MVC paradigm is to maintain separate and highly configurable layers. For instance, if you have a Web 2.0 client, you might want to return XML or JSON as the output. In that case, you can create a new result type for XML or JSON and achieve this flexibility.

Struts2 provides a variety of predefined result types. The default result type dispatcher, which dispatches to JSP pages, is what we have seen so far. Struts2 also allows the use of other markup languages for the view technology to present the results. Some popular choices include Velocity, FreeMaker, XSLT, and Tiles.

In this article, we will cover three types of result types, which are:

  1. Dispatcher Result type
  2. Freemarker Result type
  3. Redirect Result type
Dispatcher Result Type in Struts 2

In Struts 2, the Dispatcher result type is used to dispatch control to another action or URL. This is the type of result we have been using up until now in our projects. It is one of the result types that can be configured in the struts.xml file to define the outcome of an action execution. The Dispatcher result type allows you to forward or redirect the control flow to another action or URL. It provides flexibility in controlling the flow of the application by allowing you to chain actions or redirect to different URLs based on certain conditions. To use the Dispatcher result type, you need to define it in your struts.xml configuration file. Here’s an example:

Dispatcher Result Type in Struts 2

In this example, when the action executes successfully and returns the successful result, the Dispatcher result type is used. It forwards the control to another action (results.jsp or error.jsp) by default. You can also specify a URL instead of an action name as the location parameter.

struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
 <constant name="struts.devmode" value="true"/>
 
 <package name="default" extends="struts-default">
  <action name="hello" class="com.dotnet.HelloAction" method="execute">
   <result name="success">/results.jsp</result>
   <result name="error">/error.jsp</result>
  </action>
 </package>
</struts>
results.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>

 <head>
  <title>Results page</title>
 </head>

 <body>
  <p>Hello <s:property value="userName"/>!</p>
 </body>
</html>
error.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>
Freemarker Result Type in Struts 2

In Struts 2, the “freemarker” result type is used to render the output using the FreeMarker template engine. The FreeMarker template engine is a popular open-source template engine written in Java. It provides a powerful and flexible way to generate dynamic content by combining templates with data. Here are some key features and concepts of the FreeMarker template engine:

  • Templates: FreeMarker templates are plain text files that contain a mixture of static content and placeholders (also known as directives or tags) for dynamic data. Templates can be written in various formats such as HTML, XML, or plain text.
  • Data Model: The FreeMarker template engine relies on a data model to provide dynamic values for the placeholders in the templates. The data model is typically a Java object (e.g., a Map, a JavaBean, or a custom object) that holds the data to be displayed in the template.
  • Expressions: FreeMarker templates use expressions to retrieve values from the data model and insert them into the template. Expressions are enclosed in double curly braces (e.g., {{ expression }}) and can contain variables, method calls, and other operators.
  • Directives: FreeMarker provides various directives that allow conditional logic, loops, and other control structures within the templates. Directives are enclosed in {% %} tags and enable you to perform operations like conditional rendering, iteration, and template inclusion.
  • Macros: Macros in FreeMarker are reusable chunks of template code that can be defined and called from within templates. They are similar to functions or methods in programming languages and provide a way to modularize template logic.
  • Template Configuration: The FreeMarker template engine allows configuration options to be set programmatically or through configuration files. Configuration options include things like template loading paths, cache settings, and error handling.

The FreeMarker template engine is widely used in web development frameworks and content generation systems to separate the presentation logic from the data and produce dynamic output. It provides a clean and flexible approach to generating dynamic content, making it easier to maintain and update templates without modifying the underlying Java code.

The result type is responsible for generating the final response by merging the specified FreeMarker template with the data provided by the action. When you configure a result type as “freemarker” in your Struts 2 application, it means that the framework will use the FreeMarker template engine to process and render the response. The FreeMarker templates typically contain a mixture of static content and placeholders (variables) that are replaced with actual values at runtime. Here is how you can use the freemarker result type in Struts2:

Freemarker Result Type in Struts 2

In the above example, the “freemarker” result type is used for the “hello” action, and it will render the output using the FreeMarker template. The action class (com.dotnet.HelloAction) will populate the data model that is used by the FreeMarker template for rendering the output.

The results.fm and error.fm needs to be created in the src/main/webapp directory. They should contain the following content:

results.fm:

Struts 2 Results Types with Example

error.fm:

Struts 2 Results Types with Example

By using the “freemarker” result type in Struts 2, you can leverage the power and flexibility of the FreeMarker template engine to generate dynamic content for your application’s responses. The output and websites will be the same as before, but the code is much simpler, as we do not have to type HTML/JSP files.

struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
 <constant name="struts.devmode" value="true"/>
  
 <package name="default" extends="struts-default">
  <action name="hello" class="com.dotnet.HelloAction" method="execute">
   <result name="success" type="freemarker">/results.fm</result>
   <result name="error" type="freemarker">/error.fm</result>
  </action>
 </package>
</struts>
results.fm

Hello World ${name}

error.fm

You are not authorized to view this page.

Redirect Result Type in Struts 2

In Struts 2, the “redirect” result type is used to perform a redirect to a different URL or action after the execution of an action. It is commonly used when you want to redirect the user to a different page or execute another action as a result of the current action. When you configure a result type as “redirect” in your Struts 2 application, it means that the framework will redirect the user’s browser to the specified URL or action. The redirect can be either a client-side redirect (HTTP 302 redirect) or a server-side redirect (HTTP 301 redirect), depending on the configuration. Here is how you can use the redirect result type in Struts2:

Redirect Result Type in Struts 2

In the above example, the “redirect” result type is used for the “hello” action, and it will redirect the user to the URL or action. When the “redirect” result type is executed, the Struts 2 framework will handle the redirect by sending the appropriate HTTP response to the browser, instructing it to navigate to the specified URL or execute the specified action. The browser will make a new request to the target URL or action, and the control flow will continue from there. Using the “redirect” result type in Struts 2, you can easily redirect users to different pages or execute other actions, allowing you to control the flow and navigation of your application.

struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>
 <constant name="struts.devmode" value="true"/>
  
 <package name="default" extends="struts-default">
  <action name="hello" class="com.dotnet.HelloAction" method="execute">
   <result name="success" type="redirect">/results.jsp</result>
   <result name="error" type="redirect">/error.jsp</result>
  </action>
 </package>
</struts>
results.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>

 <head>
  <title>Results page</title>
 </head>

 <body>
  <p>Hello <s:property value="userName"/>!</p>
 </body>
</html>
error.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>

In the next article, I am going to discuss Struts 2 Value Stack and OGNL with Examples. Here, in this article, I try to explain Struts 2 Result Types with Examples and I hope you enjoy this Struts 2 Result Types article.

Leave a Reply

Your email address will not be published. Required fields are marked *