How to create Struts2 web application

Follow us
This article will help you to understand how to create a login example in Struts2 with Bootstrap.

First, take a look at the project structure.

1. Create Project Structure:
How to create Struts2 web application
a] Struts Project Structure
2. Include the following libraries:

A] Struts2 Libraries:

How to create Struts2 web application
A] Struts Libraries

Download libraries from here

B] Bootstrap Libraries: Include the below libraries in the header.

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
3. Create JSP view pages

A JSP index page to use the Struts 2 tags to display the username and password input fields and submit button.

File: 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>CodesVila: Login</title>
<link rel="stylesheet" href="style.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
	<style>
		.padding-top-20{
			padding-top:20px;
		}
		.errorMessage {
			color:#ff0000;
		}
	</style>
</head>
<body>
	<div class="container padding-top-20">
		<div class="row">
			<div class="col-lg-6">
			<s:textfield style="display:none;"  name="errorField"/>
				<s:form action="loginAction" method="post">
					<div class="form-group">
						<s:textfield name="username" id="username" cssClass="form-control" placeholder="Enter Username" label="Username" />
					</div>
					<div class="form-group">
						<s:password name="passwd" id ="passwd" cssClass="form-control" placeholder="Enter Password" label="Password" />
					</div>
					<s:submit cssClass="btn btn-primary" value="Login"></s:submit>
				</s:form>
			</div>
		</div>
	</div>              
</body>
</html>

A JSP welcome page to display a welcome message to the user.

File: welcome.jsp

<div class="container padding-top-20">
		<div class="breadcrumb">
			<div class="text-center">
				<span>Welcome to CodesVila</span>
			</div>
		</div>
</div>
4. Struts configuration file

File: 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>
	<package name="loginExample" extends="struts-default">
		<action name="loginAction" class="com.codesvila.action.LoginAction" method="execute">
			<result name="success">/welcome.jsp</result>
			<result name="error">/index.jsp</result>
			<result name="input">/index.jsp</result>
		</action>
	</package>
</struts>	

Struts XML file is the configuration file where the appropriate view is populated on the basis of the result passed by the action controller. 

5. Configure the Web Application Deployment Descriptor (web.xml) file to integrate Struts2 to your web project.

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>StrutsLoginExample</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
   <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>
6. Action Class
An Action class where all the business logic is written. 
File: LoginAction.java
package com.codesvila.action;
import java.util.Map;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction  extends ActionSupport{
	private String username;
	private String passwd;
	private Map<String, Object> sessionMap;
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String INPUT = "input";
	public Map<String, Object> getSessionMap() {
		return sessionMap;
	}
	public void setSessionMap(Map<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String execute() throws Exception {
		if("admin".equals(getUsername()) && "123".equals(getPasswd())){
			return SUCCESS;
		}
		return ERROR;
	}
	public void validate() {
		if("".equals(username) || "".equals(passwd)) {
			addFieldError("errorField", "Missing username or password!!");
		}
		else if( !("".equals(username)) && !("".equals(passwd))) {
			if(! "admin".equals(username) || ! "123".equals(passwd)) {
				addFieldError("errorField", "Incorrect username or password!!");
			}
		}
	}
}

The validate() method executes before the execute() method and returns the INPUT result by default if the validation fails. The addFiledError method adds the errors to the view by specifying the targeted field where the error message can be shown on invalid input.

7. Run the project
Index page

How to create Struts2 web application
a] index.jsp

On using invalid credentials 

How to create Struts2 web application
b] validating username and password

On missing username or password field

How to create Struts2 web application
c] validating the missed username and password

Filling the valid credentials 

How to create Struts2 web application
d] valid credentials
How to create Struts2 web application
e] Successful Login
Download this project