Forms Handling in Struts 2

On the Eclipse, create a Maven project

Click Next button and select Workspace location for project

Click Next button and select maven-archetype-webapp

Click Next button and enter Project Information:

  • GroupId: LearnStrutsFrameworkWithRealApps
  • Artifact Id: LearnStrutsFrameworkWithRealApps
  • Package: com.demo

Click Finish button to finish create Maven project




Select current project, Right click and select Properties menu. In Properties dialog, select Targeted Runtime in left side after select Tomcat server from server list in right side

Click Ok button to finish

Select current project, Right click and select Build Path\Configure Build Path menu Select JRE System Library in Libraries tab:

Click Edit button and select JRE System Library you need use as below:

Click Finish button to finish




Open pom.xml file and add configurations for Struts 2 as below:

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>LearnStrutsFrameworkWithRealApps</groupId>
	<artifactId>LearnStrutsFrameworkWithRealApps</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>LearnStrutsFrameworkWithRealApps Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp.jstl</groupId>
			<artifactId>javax.servlet.jsp.jstl-api</artifactId>
			<version>1.2.1</version>
		</dependency>

		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- Struts 2 Framework -->

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>2.5.20</version>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-convention-plugin</artifactId>
			<version>2.5.20</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>LearnStrutsFrameworkWithRealApps</finalName>
	</build>

</project>




Open web.xml file in src\main\webapp\WEB-INF folder and add configurations for Struts 2 as below:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
		 http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Learn Struts 2 Framework with Real Apps</display-name>

	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
		<init-param>
			<param-name>struts.devMode</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>struts.action.extension</param-name>
			<param-value>html</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>INCLUDE</dispatcher>
	</filter-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

Create new package named entities. In this package, create new java classes as below:

In entities package, create new java class named Account.java as below:

package entities;

public class Account {

	private int id;
	private String username;
	private String password;
	private String description;
	private boolean status;
	private String[] languages;
	private String gender;
	private String degree;
	private String role;
	private String[] hobbies;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getDegree() {
		return degree;
	}

	public void setDegree(String degree) {
		this.degree = degree;
	}

	public String getRole() {
		return role;
	}

	public void setRole(String role) {
		this.role = role;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String[] getLanguages() {
		return languages;
	}

	public void setLanguages(String[] languages) {
		this.languages = languages;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String[] getHobbies() {
		return hobbies;
	}

	public void setHobbies(String[] hobbies) {
		this.hobbies = hobbies;
	}

}




In entities package, create new java class named Degree.java as below:

package entities;

public class Degree {

	private String id;
	private String name;

	public Degree() {
	}

	public Degree(String id, String name) {
		this.id = id;
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

In entities package, create new java class named Hobby.java as below:

package entities;

public class Hobby {

	private String id;
	private String name;

	public Hobby() {
	}

	public Hobby(String id, String name) {
		this.id = id;
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

In entities package, create new java class named Language.java as below:

package entities;

public class Language {

	private String id;
	private String name;

	public Language() {
	}

	public Language(String id, String name) {
		this.id = id;
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

In entities package, create new java class named Role.java as below:

package entities;

public class Role {

	private String id;
	private String name;

	public Role() {
	}

	public Role(String id, String name) {
		this.id = id;
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}




Create new package named models. In this package, create new java classes as below:

In models package, create new java class named DegreeModel.java as below:

package models;

import java.util.ArrayList;
import java.util.List;

import entities.Degree;

public class DegreeModel {

	public List<Degree> findAll() {
		List<Degree> degrees = new ArrayList<Degree>();
		degrees.add(new Degree("deg1", "Degree 1"));
		degrees.add(new Degree("deg2", "Degree 2"));
		degrees.add(new Degree("deg3", "Degree 3"));
		degrees.add(new Degree("deg4", "Degree 4"));
		degrees.add(new Degree("deg5", "Degree 5"));
		return degrees;
	}

}

In models package, create new java class named HobbyModel.java as below:

package models;

import java.util.ArrayList;
import java.util.List;

import entities.Hobby;

public class HobbyModel {

	public List<Hobby> findAll() {
		List<Hobby> hobbies = new ArrayList<Hobby>();
		hobbies.add(new Hobby("r1", "Hobby 1"));
		hobbies.add(new Hobby("r2", "Hobby 2"));
		hobbies.add(new Hobby("r3", "Hobby 3"));
		hobbies.add(new Hobby("r4", "Hobby 4"));
		hobbies.add(new Hobby("r5", "Hobby 5"));
		return hobbies;
	}

}

In models package, create new java class named LanguageModel.java as below:

package models;

import java.util.ArrayList;
import java.util.List;

import entities.Language;

public class LanguageModel {

	public List<Language> findAll() {
		List<Language> languages = new ArrayList<Language>();
		languages.add(new Language("lang1", "Language 1"));
		languages.add(new Language("lang2", "Language 2"));
		languages.add(new Language("lang3", "Language 3"));
		languages.add(new Language("lang4", "Language 4"));
		languages.add(new Language("lang5", "Language 5"));
		return languages;
	}

}




In models package, create new java class named RoleModel.java as below:

package models;

import java.util.ArrayList;
import java.util.List;
import entities.Role;

public class RoleModel {

	public List<Role> findAll() {
		List<Role> roles = new ArrayList<Role>();
		roles.add(new Role("r1", "Role 1"));
		roles.add(new Role("r2", "Role 2"));
		roles.add(new Role("r3", "Role 3"));
		roles.add(new Role("r4", "Role 4"));
		roles.add(new Role("r5", "Role 5"));
		return roles;
	}

}

Create new package named controllers.action in src/main/java folder. The action class in Struts 2 must be put in a package named action. In this package, create new java class named AccountAction.java as below:

package controllers.action;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;

import entities.Account;
import entities.Degree;
import entities.Hobby;
import entities.Language;
import entities.Role;

import models.DegreeModel;
import models.HobbyModel;
import models.LanguageModel;
import models.RoleModel;

@Namespace("/account")
public class AccountAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private Account account;
	private List<Language> languages;
	private List<Role> roles;
	private List<Hobby> hobbies;
	private List<Degree> degrees;

	public List<Degree> getDegrees() {
		return degrees;
	}

	public void setDegrees(List<Degree> degrees) {
		this.degrees = degrees;
	}

	public List<Hobby> getHobbies() {
		return hobbies;
	}

	public void setHobbies(List<Hobby> hobbies) {
		this.hobbies = hobbies;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}

	public List<Language> getLanguages() {
		return languages;
	}

	public void setLanguages(List<Language> languages) {
		this.languages = languages;
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	@Action(value = "index", results = {
		@Result(name = SUCCESS, location = "/WEB-INF/views/account/index.jsp")
	})
	public String index() {
		RoleModel roleModel = new RoleModel();
		HobbyModel hobbyModel = new HobbyModel();
		LanguageModel languageModel = new LanguageModel();
		DegreeModel degreeModel = new DegreeModel();
		this.languages = languageModel.findAll();
		this.roles = roleModel.findAll();
		this.hobbies = hobbyModel.findAll();
		this.degrees = degreeModel.findAll();

		this.account = new Account();
		this.account.setId(123);
		this.account.setStatus(true);
		this.account.setDegree("deg1");
		this.account.setLanguages(new String[] { "lang1", "lang3" });
		this.account.setGender("m");
		return SUCCESS;
	}

	@Action(value = "save", results = {
		@Result(name = SUCCESS, location = "/WEB-INF/views/account/success.jsp")
	})
	public String save() {
		System.out.println("Account Info");
		System.out.println("Id: " + account.getId());
		System.out.println("Username: " + account.getUsername());
		System.out.println("Password: " + account.getPassword());
		System.out.println("Description: " + account.getDescription());
		System.out.println("Status: " + account.isStatus());
		System.out.println("Languages");
		for (String language : account.getLanguages()) {
			System.out.println("\t" + language);
		}
		System.out.println("Gender: " + account.getGender());
		System.out.println("Degree: " + account.getDegree());
		System.out.println("Role: " + account.getRole());
		System.out.println("Hobbies");
		for (String hobby : account.getHobbies()) {
			System.out.println("\t" + hobby);
		}
		return SUCCESS;
	}

}




Create new folder named views in src\main\webapp\WEB-INF folder. In views folder, create new folder named account. In account folder create new views as below:

In account folder, create new JSP file named index.jsp as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Struts 2 with Real Apps</title>
</head>
<body>

	<h3>Register</h3>
	<s:form method="post" namespace="/account" action="save">
		<s:textfield label="Username" name="account.username"></s:textfield>
		<s:password label="Password" name="account.password"></s:password>
		<s:textarea label="Description" name="account.description" rows="5" cols="20"></s:textarea>
		<s:checkbox label="Status" name="account.status"></s:checkbox>
		<s:checkboxlist label="Languages" list="languages" listKey="id" listValue="name" name="account.languages"></s:checkboxlist>
		<s:radio label="Gender" list="#{'m':'male', 'f':'female' }" name="account.gender"></s:radio>
		<s:radio label="Degree" list="degrees" listKey="id" listValue="name" name="account.degree"></s:radio>
		<s:select label="Role" list="roles" listKey="id" listValue="name" name="account.role"></s:select>
		<s:select label="Hobbies" list="hobbies" listKey="id" listValue="name" name="account.hobbies" multiple="true"></s:select>
		<s:hidden name="account.id"></s:hidden>
		<s:submit value="Save" align="left"></s:submit>
	</s:form>

</body>
</html>

In account folder create new JSP file named success.jsp as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Struts 2 with Real Apps</title>
</head>
<body>

	<h3>Account Information</h3>
	<table border="1">
		<tr>
			<td>Id</td>
			<td>${account.id }</td>
		</tr>
		<tr>
			<td>Username</td>
			<td>${account.username }</td>
		</tr>
		<tr>
			<td>Password</td>
			<td>${account.password }</td>
		</tr>
		<tr>
			<td valign="top">Description</td>
			<td>${account.description }</td>
		</tr>
		<tr>
			<td>Status</td>
			<td>${account.status }</td>
		</tr>
		<tr>
			<td valign="top">Gender</td>
			<td>${account.gender }</td>
		</tr>
		<tr>
			<td valign="top">Degree</td>
			<td>${account.degree }</td>
		</tr>
		<tr>
			<td valign="top">Languages</td>
			<td>
				<c:forEach var="language" items="${account.languages }">
					${language } <br>
				</c:forEach>
			</td>
		</tr>
		<tr>
			<td valign="top">Role</td>
			<td>${account.role }</td>
		</tr>
		<tr>
			<td valign="top">Hobbies</td>
			<td>
				<c:forEach var="hobby" items="${account.hobbies }">
					${hobby } <br>
				</c:forEach>
			</td>
		</tr>
	</table>

</body>
</html>




Create new jsp file named index.jsp in src\main\webapp folder as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<jsp:forward page="account/index.html"></jsp:forward>

Select project, right click and select Run on Server menu

Access index method in account action with following url:

http://localhost:8080/LearnStrutsFrameworkWithRealApps/account/index.html