Struts - SPLessons

Chapter 9

Struts 2 Control Tags

Struts 2 Control Tags

Struts 2 Control Tags, While developing on the projects, developer needs to write the code, then some tags will help to reduce the code where each and every tag will have its own functionality but all the tags functionality is same but their usage may be different in technologies. Struts 2 have some set of tags. Using these tags, user can easily execute the flow of page execution. Struts 2 has the great feature that can integrate with other frameworks such as hibernate, tiles, spring, tiles, Ajax. Following are the different tags available in Struts 2 will help to reduce the programming length.

Control Tags

The if and else tags

By using the if and else tag in struts 2 application, one will have multiple options in home page, but select only single option at a time. The most useful options are “ if ” or “else” or ” if-else “.

Write the below tag for if and else in JSP page.

<s:if text="”%{false}”">
</s:if>
<div>Will Not be executed</div>
<s:elseif text="”%{true}”">
</s:elseif>
<div>Will be executed</div>
<s:else>
</s:else>
<div>Will Not be executed</div>

In this example, let’s take three fields, select any one field and the selected option will be displayed as output.

1. Create the project directory structure.

2. Create the View page and get the input values from the user.

index.jsp

<%@ 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>
       <font color="green">
<h1>
     SPLessons Register Form
    </h1>
    </font>
<form action="login">
         <s:textfield name="uname" label="Enter your Name" />
        
         <s:textfield name="email" label="Enter Email Id"/>
        
         <label for="name">
         Please select any one course
         </label>
         <select name="name">
<option name="java">
             Java
            </option>
<option name=".Net">
             .Net
            </option>
<option name="C ">
             C
            </option>
         </select>
        </br>
       <input type="submit" value="Register"/>
      </form>
   </body>
</html>

Here just created the text boxes to enter Name and Email and also created option tags to select the required element.
3. Create the Action class.
ControlTagsAction.java

package com.splessons;

public class ControlTagsAction
{
  private String uname;
  private String email;
  private String name;

  public String getUname()
  {
   return uname;
   }
  public void setUname(String uname) 
  {
   this.uname = uname;
    }
  public String getEmail()
  {
   return email;
    }
  public void setEmail(String email) 
  {
   this.email = email;
   }
  public String getName() 
  {
   return name;
   }
  public void setName(String name)
  {
   this.name = name;
   }

  public String execute() throws Exception
  {
    return "success";
    }
}

Here just given the data members uname, email, name and also performed SET and GET methods on the data members.
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>
  <package name="chinna" extends="struts-default">
     <action name="login" class="com.splessons.ControlTagsAction"> 
        <result name="success">
         /success.jsp
        </result>
     </action> 
   </package> 
</struts>

Where success is a predefined result type. action element is the sub component of package. It speaks to an activity to be conjured for the approaching request. It has name, class and method attributes. In the event that you don’t determine name property as a matter of course execute() technique will be summoned for the predetermined actiion class.
success.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
   <head>
      <title>
       Example of If and Else using control tags.
      </title>
   </head>
   <body>
      <b>
       Example of If and Else using control tags.
      </b>   
      <s:if test="name=='Java'">
           You have selected 'Java'. 
      </s:if>
          <s:elseif test="name=='.Net'">
               You have selected '.Net'
          </s:elseif>
             <s:else>
                 You have selected 'C '.
            </s:else>
    </body>
</html>

Here used the if and else logic that like if an user select Java then it displays You have selected Java.
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
   <filter>
    <filter-name>
      struts2
    </filter-name>
    <filter-class>
     org.apache.struts2.dispatcher.FilterDispatcher
    </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>
     struts2
</filter-name>
    <url-pattern>
     /*&
     </url-pattern>
  </filter-mapping>
</web-app>

4. Deploy the application in server, then the output is as shown in the below image.

5. Enter all the required fields and select any one course, click on submit button. If the selected course is java, then the output will be as shown in the below image.
If the selected course is .Net, then the output will be as shown in the below image.
If the selected course is C language, then the output will be as shown in the below image.

Data Tags

The Struts 2 data tags are mostly used to display the manipulate data on a page. Struts 2 contain multiple data tags.

The action tag is used to call the JSP to Action class directly, using action name and action class. The action tag contain result tag and is written on the struts.xml file.

<action name =” action name” class= ” Action class name”>
<result name=” success”>index.jsp</result>
</action>

Example of action tag

1. In this example, let’s create one view page and get the input values from the user and those values will be displayed into the browser.

2. Create the directory structure.

3. Create the view pages and get the input values.

index.jsp

<%@ 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>
<form action="action">
           <s:textfield name="name" label="Enter your Name" />      
           <input type="submit" value="submit"/>
       </form>
    </body>
</html>

4. Create the action class and get the request from browser. Then, the response is forwarded to result page.
MyActionClass.java

package com.splessons;

 public class MyActionClass 
  {
    private String name;

    public String getName()
    {
      return name;
     }
    public void setName(String name) 
     {
     this.name = name;
      }
    public String execute()
     {
      return "success";
      }
  }

5. Create the struts 2 configuration file and configure the action class in XML file by using <action > tag.
struts.xnl

<?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>
    <package name="default" extends="struts-default"> 
        <action name="action" class="com.splessons.MyActionClass"> 
             <result name="success">
             /success.jsp
         </result>
        </action> 
    </package> 
</struts> 

6. Print the result into browser through success page and include the index.jsp page using the tag.
success.jsp

<%@ 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>
      <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   </head>
   <body>
      <font color="green">
<h1>
     Welcome to SPLessons
    </h1>
    </font>
<h2>
       Hai
    <s:property value="name">
    This is include tag example
    </h2>
    </br>
     <script type="text/javascript">
         alert("Enter another person name");
     </script> 
    <s:include value="index.jsp"/>
   </body>
 </html>

Here code will be compiled from the index.jsp page.
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <filter>
    <filter-name>
     struts2
    </filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.FilterDispatcher
    </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>
     struts2
     </filter-name>
    <url-pattern>
     /*
</url-pattern>
</filter-mapping>
</web-app>

Output

7. Output

Enter the required field and click on submit button.

These include tag is used to include a JSP file in another page.For example, let’s take two JSP pages, but both JSP pages output will be displayed on one browser.These include tag can be written in different types.

<!– First syntax –>

<s: include value=” Another jsp file name”/>

<!– Second syntax –>

<s:include value=” Another jsp file name”>

<param name=” key1″ value=”value1″/>

<param name=”key2″ value=”value2″/>

</s:include>

<!– Third syntax –>

<s:include value=” Another jsp file name”>

<param name=” key1″ >value1</param>

<param name=”key2″ >value2</param>

</s:include>

Example of include tag:

1. In this example, let’s create one Register form, so that if user submits the details, the second page should be displayed on the first page.

2. Create the directory structure.

3. Create the view pages and get the input values.

index.jsp

<%@ 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>
<form action="include">
         <s:textfield name="name" label="Enter Name" >    
        <input type="submit" value="submit">
      </form>
   </body>
</html>

4. Create the action class and get the request from browser. Forward the response to result page.
MyActionClass.java

package com.splessons;

 public class MyActionClass 
  {
    private String name;

    public String getName()
    {
      return name;
     }

    public void setName(String name) 
     {
     this.name = name;
      }
    public String execute()
     {
      return "success";
      }
  }

5. Create the struts 2 configuration file and configure the action class in XML file by using
tag.
struts.xnl

<?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>
    <package name="default" extends="struts-default"> 
        <action name="include" class="com.splessons.MyActionClass"> 
            <result name="success">
             /success.jsp
        </result>
        </action> 
   </package> 
</struts> 

6. Print the result into browser through success page and include the index.jsp page using the tag.
success.jsp

<%@ 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>
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
   </head>
   <body>
      <font color="green">
<h1>
      Welcome to SPLessons
      </h1>
     </font>
<h2>
       Hai
      <s:property value="name">
      This is include tag example
      </h2>
      </br>
      <script type="text/javascript">
          alert("Enter another person name");
      </script>
      <s:include value="index.jsp">
   </body>
 </html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <filter>
    <filter-name>
     struts2
    </filter-name>
    <filter-class>
    org.apache.struts2.dispatcher.FilterDispatcher
    </filter-class>
  </filter>
  <filter-mapping>
    <filter-name>
     struts2
    </filter-name>
    <url-pattern>
     /*
</url-pattern>
</filter-mapping>
</web-app>

Output

7. Deploy the application into the server and run the application.

8. Enter the required field and click on submit button.
9. An alert message will be displayed, proceed by clicking OK button, then the output will be as shown in the below image.

These property tag is used to get the property of a value, which is by default defined in stack.


<s:property value=”name”/>

Following is an example which describes more about the property tag and how it works functionally.
Person.java

public class Person {
	
	private String name = "Name from Person.java"; 
	
	public String getName() {
		return name;
	}

}

Here just declared the text by using String and Get method has been performed to get the data.
PropertyTagAction.java

import com.opensymphony.xwork2.ActionSupport;
 
public class PropertyTagAction extends ActionSupport{
	
	private String name = "Name from PropertyTagAction.java"; 
	
	public String getName() {
		return name;
	}

	public String execute() throws Exception {
		
		return SUCCESS;
	}
}

execute() will execute the String and returns the success.
property.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 property tag example</h1>

<h2>1. Call getName() from propertyTagAction.java</h2> 
<s:property value="name" />

<h2>2. Call getName() from Person.java</h2> 
<s:bean name="com.splessons.Person" var="personBean" />
<s:property value="#personBean.name" />

</body>
</html>

getName() is used to get the name from propertyTagAction.java and Person.java.
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.devMode" value="false" />
	<package name="default" namespace="/" extends="struts-default">
	
		<action name="propertyTagAction" 
			class="com.splessons.PropertyTagAction" >
			<result name="success">pages/property.jsp</result>
		</action>
		
	</package>
</struts>

By default, the development mode is disabled, because it has a significant impact on performance, since the entire configuration will be reloaded on every request.
The development mode is only suitable in a development or debugging environment. In a production environment, you have to disable it. It will cause significant impact on performance, because the entire application configuration and properties files will be reloaded on every request and extra logging and debugging information will also be provided.
web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Struts 2 Web Application</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>
 
</web-app>

Output
When compile the program output will be as follows.

This push tag is used to push the value in the property. If one defined the push tag in an application, then need to write the property tag inside push tag.


<s:push value =”student”>

<s:property value =” Current address “/>

<s:property value =”Permanent address”/>

<s:push>

Following is an example which describes more about push tag.
Person.java

public class Person{

	private String firstName = "This is firstName";
	private String lastName = "This is lastName";
	
	public String getFirstName() {
		return firstName;
	}
	public String getLastName() {
		return lastName;
	}
}

Here only declared the data members and performed encapsulation theory.
PushTagAction.java

import com.opensymphony.xwork2.ActionSupport;
 
public class PushTagAction extends ActionSupport{

	public String execute() throws Exception {
		
		return SUCCESS;
	}
}

Struts 2 comes with an optional action interface (com.opensymphony.xwork2.Action). By implements this interface, it bring some convenient benefits.
push.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 push tag example</h1>

<h2>1. Normal way</h2>
<s:bean name="com.splessons.Person" var="personBean" />
First name : <s:property value="#personBean.firstName" /><br/>
Last name: <s:property value="#personBean.lastName" /><br/>

<h2>2. Push way</h2>
<s:push value="#personBean" >
First name : <s:property value="firstName" /><br/>
Last name: <s:property value="lastName" /><br/>
</s:push>

</body>
</html>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Struts 2 Web Application</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>
 
</web-app>

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.devMode" value="false" />
	<package name="default" namespace="/" extends="struts-default">
	
		<action name="pushTagAction" 
			class="com.splessons.PushTagAction" >
			<result name="success">pages/push.jsp</result>
		</action>
		
	</package>
</struts>

Output
When compile the program following is the output will be displayed.

This set tag assigns a value to a variable in a specified scope. It is useful to assign a variable to a complex expression and then simply refer that variable each and every time. Struts 2 as different type of scopes.


<s:set name= “myaddress” value =”environment.address”/>

<s:property value =”myaddress”/>

Following is an example which describes more about the set tag.
SetTagAction.java

import com.opensymphony.xwork2.ActionSupport;
 
public class SetTagAction extends ActionSupport{

	private String msg = "Struts 2 is a funny framework";
	
	public String getMsg() {
		return msg;
	}

	public String execute() throws Exception {
		
		return SUCCESS;
	}
}
	

set.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 set tag example</h1>
<h2>1. <s:set var="varMsg" value="msg" /></h2>

<s:set var="varMsg" value="msg" />
<s:property value="varMsg" />

<h2>2. <s:set var="varUrl" value="%{'http://www.splesson.com'}" /></h2> 

<s:set var="varUrl" value="%{'http://www.splesson.com'}" />
<s:property value="varUrl" />


</body>
</html>

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.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
	
		<action name="setTagAction" 
			class="com.splessons.SetTagAction" >
			<result name="success">pages/set.jsp</result>
		</action>
			
	</package>
</struts>

web.xml
Where success is a predefined result type. action element is the sub component of package. It speaks to an activity to be conjured for the approaching request. It has name, class and method attributes. In the event that you don’t determine name property as a matter of course execute() technique will be summoned for the predetermined actiion class.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Struts 2 Web Application</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>
 
</web-app>

Output
When compile the program following is the output will be displayed.

This text tag is used to display the text messages in a browser.


<!– syntax 1 –>

<s:i18n name = ” action class name ” >

<s:text name = “student.currentAddress”/>

</s:i18n>

<!– syntax 2 –>

<s:text name = “student.companyAddress”> value </s:text>

<!– syntax 3 –>

<s:text name=”student.permanentAddress”>

<param >value</param>

</s:text>

Following is an example which describes more about the text tag.
TextTagAction.java

import com.opensymphony.xwork2.ActionSupport;
 
public class TextTagAction extends ActionSupport{

	public String execute() throws Exception {
		
		return SUCCESS;
	}
}

Struts 2 comes with an optional action interface (com.opensymphony.xwork2.Action). By implements this interface, it bring some convenient benefits.

TextTagAction.properties

name.msg = "This is a message from properties file"
name.msg.param = "This is a message from properties file - param : {0}"

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.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
	
		<action name="textTagAction" 
			class="com.splessons.TextTagAction" >
			<result name="success">pages/text.jsp</result>
		</action>
		
	</package>
</struts>

text.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>
 
<body>
<h1>Struts 2 text tag example</h1>

<h2>1.<s:text name="name.msg" /></h2> 
Output : <s:text name="name.msg" />

<h2>2. <s:text name="name.msg.unknow">message doesn't exists</s:text></h2> 
Output : <s:text name="name.msg.unknow">message doesn't exists</s:text>

<h2>3. <s:text name="name.msg.unknow" /></h2> 
Output : <s:text name="name.msg.unknow" />

<h2>4. <s:text name="name.msg.param" ><s:param >splesson</s:param>
</s:text></h2> 
Output :
<s:text name="name.msg.param" >
	<s:param >splesson</s:param>
</s:text>

</body>
</html>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Struts 2 Web Application</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>
 
</web-app>

Output
When compile the program following output will be displayed.

Struts 2 URL tag is used to create an URL and output it as a text format. It’s never work by itself, but it can provides URL to other tags like to create a hyperlink or to render an image. In this tutorials, it shows 5 common use cases of the Struts 2 URL tag.


<!– syntax 1 –>

<s:url value=”loginname.action”>

<s:param name=”id” value=”%{selected}”/>

</s:url>

<!– syntax 2 — >

<s:url action=”login”>

<s:param name=”id” value=”%{selected}”/>

</s:url>

Following is an example which describes more about URL tag.
URLTagAction.java

import com.opensymphony.xwork2.ActionSupport;
 
public class URLTagAction extends ActionSupport{
	
	public String execute() {
		return SUCCESS;
	}
	
}

Struts 2 comes with an optional action interface (com.opensymphony.xwork2.Action). By implements this interface, it bring some convenient benefits.
url.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
<head>
</head>
 
<body>
<h1>Struts 2 URL tag example</h1>

<ol>


<li>
<a href="<s:url value="http://www.itoolsinfo.com/"  />" target="_blank">iTools info</a>
</li>

<li>
<s:url action="urlTagAction.action" >
    <s:param name="id">123</s:param>
</s:url>
</li>

<li>
<s:url action="urlTagAction.action" var="urlTag" >
    <s:param name="name">mkyong</s:param>
</s:url>
<a href="<s:property value="#urlTag" />" >URL Tag Action (via property)</a>
</li>

<li>
<s:url action="urlTagAction.action" var="urlTag" >
    <s:param name="age">99</s:param>
</s:url>
<s:a href="%{urlTag}">URL Tag Action (via %)</s:a>
</li>

</ol>

</body>
</html>

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.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">
	
	<action name="urlTagAction" 
		class="com.splessons.URLTagAction" >
		<result name="success">pages/url.jsp</result>
	</action>
		
    </package>		
</struts>

The development mode is only suitable in a development or debugging environment. In a production environment, you have to disable it. It will cause significant impact on performance, because the entire application configuration and properties files will be reloaded on every request and extra logging and debugging information will also be provided.
web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Struts 2 Web Application</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>
 
</web-app>

output
When compile the program following is the result will be displayed.

Form Tags

In Struts 2, form tags are defined in different places. Form tags are the subset of Struts UI tags. In Struts 2 UI tags are defined in different ways. Following are the different types UI tags.

Simple UI tags are used to display the text in the browser or user have to create a text fields like text area, label, forms, submit.

For example, create a login page


<s:div>Login Form</s:div>

<s:text name=”Enter all required fields:” />

<s:form action=”login” enctype=”multipart/formdata”>

<s:textfield key=”login.form” name=”username”/>

<s:password key=”login.password” name=”password”/>

<s:label for=”attached resume” value=”Upload resume”/>

<s:file name=”attached resume” accept =”text/html, text/plain”/>

<s:token/>

<s:submit key=”submit”/>

</s:form>

The group UI tags are used to create radio button and the checkbox. For example,let’s design one login page and that login page contain different fields.


<%@ page contenttype=”text/html”; charset=UTF-8″%>

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

<s:html>

<head> Itoolsinfo Login page</head>

<body>

<s:form action=”login” method=”post”>

<s:radio label=”Gender” name=”gender” list=”{‘male’,’female’}”/>

<s:checkboxlist label=”Java Types” name=”Java types” list=3. Selected UI tags.”]

In Struts 2, select tags are used to select the multiple options. For example.


<%@ page contenttype=”text/html”; charset=UTF-8″%>

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

<s:html>

<head> Itoolsinfo Login page</head>

<body>

<s:form action=”login” method=”post”>

<s:select name=”username” label=”Username” list=”{‘John’, ‘Joshaf’, ‘Smith’}”/>

<s:select name=”languages” label=”Languages” list=”{‘Java’, ‘.Net’, ‘Oracle’,’Testing’}”/>

<s:doubleselect label=”Occupation” name=”occupation” list=”{‘Techinical’,’Other’}” doubleName=”occupations2″ doubleList=”top==’Techincal’?{‘I.T’, ‘Hardware’}:{‘Accounting’,’H.R’}”/>

</s:form>

</s:body>

</s:html>

In this example, select the username, language and occupation. First select single user from multiple users and select the tags like Jhon, Joshaf, Smith. Now, select any one language in multiple languages like Java, .Net, Oracle.

Then, select the user category like Technical or other. If the user is from Technical, then select the user position like I.T or Hardware, else select the Non-technical and the user position like Accounting or H.R.


While developing the web applications developer supposed to insert select tag to select the single element from the multiple elements and this type of elements regularly used in html. Following is an example which describes more selected tag.

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Hello World</title>
<s:head />
</head>
<body>
   <s:form action="login.action">
      <s:select name="username" label="Username"
         list="{'Mike','John','Smith'}" />

      <s:select label="Company Office" name="mySelection"
         value="%{'America'}"
         list="%{#{'America':'America'}}">
      <s:optgroup label="Asia" 
         list="%{#{'India':'India','China':'China'}}" />
      <s:optgroup label="Europe"
         list="%{#{'UK':'UK','Sweden':'Sweden','Italy':'Italy'}}" />
      </s:select>

      <s:combobox label="My Sign" name="mySign"
         list="#{'aries':'aries','capricorn':'capricorn'}"
         headerKey="-1" 
         headerValue="--- Please Select ---" emptyOption="true"
         value="capricorn" />
      <s:doubleselect label="Occupation" name="occupation"
         list="{'Technical','Other'}" doubleName="occupations2"
         doubleList="top == 'Technical' ? 
         {'I.T', 'Hardware'} : {'Accounting', 'H.R'}" />

   </s:form>
</body>
</html>


Ajax Tags

Struts 2 has the great ability that is to integrate with different frame works , here struts 2uses DOJO plugin while working with Ajax following is the an example which describes more about Ajax tags before that developer has to add DOJO plug in to the project.

FormTagAction.java

import com.opensymphony.xwork2.ActionSupport;

public class FormTagAction extends ActionSupport {

 private static final long serialVersionUID = 1L;
 
 public String execute(){
  return SUCCESS;
 }
 public String tab1(){
  return SUCCESS;
 }
 public String tab2(){
  return SUCCESS;
 }
 public String tab3(){
  return SUCCESS;
 }
}

Struts 2 comes with an optional action interface (com.opensymphony.xwork2.Action). By implements this interface, it bring some convenient benefits.
The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If no match is found, then an InvalidClassException is thrown.
ajax.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
<html>
<head>
<title>Ajax Tag Struts2 | splessons.com</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="url1" value="/count1" />
      <s:url id="url2" value="/count2" />
      <s:url id="url3" value="/count3" />
      <sx:div href="%{#url3}" delay="2000">
           Initial Content
      </sx:div>
      <br/>
      <sx:tabbedpanel id="tabContainer">
         <sx:div label="Tab 1" href="%{#url1}">Tab 1</sx:div>
         <sx:div label="Tab 2" href="%{#url2}">Tab 2</sx:div>
      </sx:tabbedpanel>
   </s:form>
</body>
</html>

The autocompleter tag is a combo box that will automatic prompt drop down suggestion lists while user typing on the text box.
The dojo datetimepicker ajax tag will render a text box and append a calender icon behind, click on the calender icon will prompt a date time picker component.
select.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Form Tag Struts2 | splesson.com</title>
<s:head />
</head>
<body>
   <s:form action="login.action">
      <s:select name="username" label="Username"
         list="{'Mike','enni','Smith'}" />

      <s:select label="Company Office" name="mySelection"
         value="%{'America'}"
         list="%{#{'America':'America'}}">
      <s:optgroup label="Asia" 
         list="%{#{'India':'India','China':'China'}}" />
      <s:optgroup label="Europe"
         list="%{#{'UK':'UK','Sweden':'Sweden','Italy':'Italy'}}" />
      </s:select>

      <s:combobox label="My Sign" name="mySign"
         list="#{'aries':'aries','capricorn':'capricorn'}"
         headerKey="-1" 
         headerValue="--- Please Select ---" emptyOption="true"
         value="capricorn" />
      <s:doubleselect label="Occupation" name="occupation"
         list="{'Technical','Other'}" doubleName="occupations2"
         doubleList="top == 'Technical' ? 
         {'I.T', 'Hardware'} : {'Accounting', 'H.R'}" />

   </s:form>
</body>
</html>

The Combo tag is basically a drop down list grouped together with a single-line text box, allowing the user to either type a value directly into the text box or choose the value from the drop down list.

The doubleselect label tag is used to create two HTML drop down boxes, once the first drop down list is selected, the second drop down list will be change accordingly

success.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

   <s:form action="employee">
   <s:radio label="Gender" name="gender" list="{'male','female'}" />
   <s:checkboxlist label="Job Types" name="jobtypes"
   list="{'Software','Hardware','Networking','Marketing'}" />
   </s:form>

The radio label tag is utilized to create a HTML radio button.
welcome.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>Form Tag Struts2 | dineshonjava.com</title>
</head>
<body>
<b>Welcome to Ajax Call in Struts2</b>
</body>
</html>

The Content-Type is utilized for message content that is basically in comprehensible content character position. The more perplexing content substance sorts are characterized and distinguished so that a fitting device can be utilized to show that body part.
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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="myapp" />
 
 <package name="default" extends="struts-default" namespace="/">
        <action name="ajaxtag" class="com.dineshonjava.struts2.action.FormTagAction">
            <result name="success">/ajax.jsp</result>
        </action>
        <action name="count1" class="com.dineshonjava.struts2.action.FormTagAction" method="tab1">
            <result name="success">/select.jsp</result>
        </action>
        <action name="count2" class="com.dineshonjava.struts2.action.FormTagAction" method="tab2">
            <result name="success">/success.jsp</result>
        </action>
         <action name="count3" class="com.dineshonjava.struts2.action.FormTagAction" method="tab3">
            <result name="success">/welcome.jsp</result>
        </action>
    </package>
 </struts>

Where success is a predefined result type. action element is the sub component of package. It speaks to an activity to be conjured for the approaching request. It has name, class and method attributes. In the event that you don’t determine name property as a matter of course execute() technique will be summoned for the predetermined actiion class.
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ajaxtag</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.FilterDispatcher
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Output
When compile the program following result will be displayed.



Summary

  • Struts 2 Control Tags – The Struts 2 framework has the feature to integrate with other technologies such as Ajax.
  • Struts 2 Control Tags – AJAX stands for Asynchronous JavaScript and XML.
  • DOJO plug in should be added to the project while working with Ajax.
  • The text tag is used expose the text alerts.