Struts 2 If elseif else Tags

Perform basic condition flow. ‘If’ tag could be used by itself or can be followed by zero or more ‘Else if’ Tags followed by zero or one ‘Else’ Tag.

Step 1 – Create New Maven-based Dynamic Web Project

Step 1.1 Create new dynamic web project

Go to File->New->Others… Select Dynamic Web Project under Web category then click Next. Type Struts2Demo for the project name (you can choose your own name). Click Finish.

Step 1.2 Convert the project to Maven Project

Right click to the project; select Configure->Convert to Maven Project. Eclipse will generate Project Object Model (pom.xml) file. Open the file by Eclipse text editor then paste the content below.

Note: you can create normal java project and add jar files to your project build path. But it’s easier & faster using maven as maven is integrated with Eclipse IDE; so you don’t need to manually install it. 

Step 2 Create Web Deployment Descriptor (web.xml)

You can create web.xml when creating project or do it later. Right click to the project; select Java EE Tools -> Generate Deployment Descriptor Stub to generate web.xml.

Step 3 Create Struts Action Class

Right click to the project or src folder; select New->Class. The action class must be inside the package we declared in in-param actionPackages in web.xml.

Step 4 Create JSP Pages

In this example we need 2 JSP files. Right click to the project or WebContent folder; select New -> JSP File

Step 4.1 hello.jsp

Step 4.2 welcome.jsp

Step 5 Configure Tomcat Server

  • In Servers window, add new tomcat server; select Tomcat v7.0 Server then click Next. In case you don’t see the Servers window, you can go to Windows->Show View->Others… Select Servers under Server category.
  • In the next window, click Browse button to select Tomcat installation directory. Select the folder then click Ok.
  • Click Installed JREs, to configure configure runtime environment. Remove existing JRE then click Add button to add new one. Select Standard VM then click Next. Click Directory button to select JDK home folder; select the folder then click Ok.
  • Change the JRE to the JDK then click Finish.

Step 6 Deploy & Run

  • Go to Project -> Clean to clean & build the project. Eclipse will download & add maven dependencies to your project build path; then compile your classes.
  • Right click to the tomcat server; select Add & Remove. Move the application to the right to deploy it to the server.
  • Start the tomcat server
  • Open web browser and run the below URL. We assume that you install tomcat on port 8080 and context path is Struts2Demo. By default project name is same as context path:

http://localhost:8080/Struts2Demo/hello.jsp

Output

A form with a text box & submit button will be displayed. Enter John and click submit

Enter Mike to the text box then click submit

Enter any other name such as Jane to the text box then click submit