Struts 2 - The If and Else Tags


Create Action Class

package com.tutorialspoint.struts2;

public class HelloWorldAction {
   private String name;

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

   public void setName(String name) { = name;

Create Views

Let us have index.jsp file as follows −

<%@ 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" 

      lt;title>Hello World</title>
      <h1>Hello World From Struts2</h1>
      <form action = "hello">
         <label for = "name">Please pick a name</label><br/>
         <select name = "name">
            <option name = "Mike">Mike</option>
            <option name = "Jason">Jason</option>
            <option name = "Mark">Mark</option>
         <input type = "submit" value = "Say Hello"/>

Next let us have HelloWorld.jsp to demonstrate the use of the if, else and elseif tags −

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

      <title>Example of If and Else</title>
      <b>Example of If and Else</b><br/>
      <s:if test = "name=='Mike'">
         You have selected 'Mike'. 
      <s:elseif test = "name=='Jason'">
         You have selected 'Jason'
         You have not selected 'Mike' or 'Jason'.

Here, the “if” tag returns true if the condition specified in the "test" attribute returns true. In our case, we are comparing it against "Mike". If the name is Mike, the tag returns true and we print the string, otherwise the "elseif" block gets executed and if that is not satisfied, then the else block gets executed. This is no different from the conventional if, else if and else available in the Java language.

Configuration Files

Your struts.xml should look like −

<?xml version = "1.0" Encoding = "UTF-8"?>
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   <constant name = "struts.devMode" value = "true" />
   <package name = "helloworld" extends = "struts-default">
      <action name = "hello" 
         class = "com.tutorialspoint.struts2.HelloWorldAction" 
         method = "execute">
         <result name = "success">/HelloWorld.jsp</result>


Your web.xml should look like −

<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = ""
   xmlns = "" 
   xmlns:web = ""
   xsi:schemaLocation = ""
   id = "WebApp_ID" version = "3.0">
   <display-name>Struts 2</display-name>


Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen −

Struts If Tag input

Now select "Mark" and submit the page. You should see the next page.

Struts If Tag output