Login Example using Struts2 and JDBC

Follow us

In this article, we are going to show you how to create a simple login page with the help of JDBC using Struts2.

Following Tools are being used:
  1. Eclipse IDE
  2. Bootstrap Framework Libraries
  3. Struts2 Libraries
  4. MySQL Connector [Library]

First of all, we will take a look at the project structure that we are going to use.

Project Structure:
Login Example using Struts2 and JDBC
Project Structure

Following libraries are used

A] Struts2 and MySql Connector: 

Login Example using Struts2 and JDBC

These libraries should be put into the lib folder under the WebContent/WEB-INF/lib. To create the JDBC connection, mysq.jar is used.

B] For Bootstrap

<!-- 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>
View JSP Pages:

In order to use the struts2 tags in the JSP views, you will need to include the struts taglib prefix <%@ taglib prefix=”s” uri=”/struts-tags”%> on top of the file.

A] Index page. [login page] 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;
}
.successmsg {
	color: green;
}
</style>
</head>
<body>
	<div class="container padding-top-20">
		<s:if test="hasActionErrors()">
			<div class="errorDiv">
				<s:actionerror />
			</div>
		</s:if>
		<s:if test="hasActionMessages()">
			<div class="successmsg">
				<s:actionmessage />
			</div>
		</s:if>
		<div class="row">
			<div class="col-lg-3">
				<h4 class="text-center">Login</h4>
				<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>
				<a href="registerPage">Regiter here</a>
			</div>
		</div>
	</div>
</body>
</html>

B] Register page File : register.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: Register</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;
}
.successmsg {
	color: green;
}
</style>
</head>
<body>
	<div class="container padding-top-20">
		<s:if test="hasActionErrors()">
			<div class="errorDiv">
				<s:actionerror />
			</div>
		</s:if>
		<s:if test="hasActionMessages()">
			<div class="successmsg">
				<s:actionmessage />
			</div>
		</s:if>
		<div class="row">
			<div class="col-lg-3">
				<h4 class="text-center">Register</h4>
				<s:form action="registerUser" method="post" onsubmit="return validateForm()">
					<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="password" id="password" cssClass="form-control"
							placeholder="Enter Password" label="Password" />
					</div>
					<div class="form-group">
						<s:password name="cpassword" id="cpassword"
							cssClass="form-control" placeholder="Confirm Password"
							label="Confirm Password" />
					</div>
					<s:submit cssClass="btn btn-primary" value="Register"></s:submit>
				</s:form>
				<a href="loginPage"> Go back </a>
			</div>
		</div>
	</div>
</body>
</html>

Handle the form input validation at the client-side using javascript/jquery for registering process. Add the following script in the header section.

Jquery script:

<script>
function validateForm(){
	var username = $('#username').val();
	var password = $('#password').val();
	var cpassword = $('#cpassword').val();
	if(username == ""){
		alert("Enter Username");
		return false;
	}
	else if(username != "" && username.length < 4){
		alert('Username must be greater than 4');
		return false;
	}
	else if(password == "" || cpassword == ""){
		alert("Please enter password");
		return false;
	}
	else if(password != "" && cpassword != ""){
		if(!(password).match(cpassword)){
			alert("Your password doesn't match. Try again?");
			return false;
		}else if( (password.length) < 4 || (cpassword.length) < 4 ){
			alert("Password length must be greater than 4");
			return false;
		}
	}
	return true;
}
</script>

C] Welcome Page [after successful login] File : 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>Welcome to CodesVila</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 type="text/css">
.padding-top-20 {
	padding-top: 20px;
}
</style>
</head>
<body>
	<div class="container padding-top-20">
		<div class="breadcrumb">
			<div class="text-center">
				<span>Welcome to CodesVila</span>
			</div>
		</div>
	</div>
</body>
</html>
Struts configuration file :

File: struts.xml. Make sure that this struts file is in classes folder under /WebContent/WEB-INF/classes

<?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>
		<action name="registerPage" class="com.codesvila.action.RegisterAction" method="display">
			<result name="success">/register.jsp</result>
		</action>
		<action name="registerUser" class="com.codesvila.action.RegisterAction" method="execute">
			<result name="success">/register.jsp</result>
			<result name="error">/register.jsp</result>
		</action>
		<action name="loginPage" class="com.codesvila.action.RegisterAction" method="goToLoginPage">
			<result name="success">/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.

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>
Action Classes :

An Action class where the actual business logic is written. 

A] File: RegisterAction.java

While creating the action classes, make sure that you have mentioned the package. The Action classpath must be defined struts.xml in order to map the appropriate action controller for the action request. 

package com.codesvila.action;
import java.sql.*;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
	private static final long serialVersionUID = 1L;
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	private String username;
	private String password;
	private String cpassword;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getCpassword() {
		return cpassword;
	}

	public void setCpassword(String cpassword) {
		this.cpassword = cpassword;
	}
	public String display(){
		return SUCCESS;
	}
	public String execute() throws Exception {
		String host = "jdbc:mysql://localhost:3306/";
		String dbName = "codesvila";
		String dbusername = "root";
		String pass = "";
		String url = host + dbName + "?user=" + dbusername + "&password=" + pass;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(url);
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("select username from codesvila_users");
			int flag = 0;
			while (rs.next()) {
				if (username.equalsIgnoreCase(rs.getString(1)) || username == rs.getString(1)) {
					 flag = 1;
				}
			}
			if(flag == 1){
				addActionError("User is already registered!!!"); //user is already registered
				return ERROR;
			}
			else{
				if (password.equals(cpassword)) {
					PreparedStatement st = con
							.prepareStatement("insert into codesvila_users(username,password) values(?,?)");
					st.setString(1, getUsername());
					st.setString(2, getPassword());	
					int i = st.executeUpdate();
					if (i > 0) {
						addActionMessage("User is registerd successfully!!");
						return SUCCESS;
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		return ERROR;
	}
	public String goToLoginPage() {
		return SUCCESS;
	}
}

B] File: LoginAction 

package com.codesvila.action;
import java.util.Map;
import java.sql.*;
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 {
		String host = "jdbc:mysql://localhost:3306/";
		String dbName = "codesvila";
		String dbusername = "root";
		String pass = "";
		String url = host + dbName + "?user=" + dbusername + "&password=" + pass;
		String loggedUserName = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(url);
			Statement stmt = con.createStatement();

			ResultSet rs = stmt.executeQuery("select username, password from codesvila_users");
			int flag = 0;
			while (rs.next()) {
				if ((username.equals(rs.getString(1)) || username == rs.getString(1))
						&& ((passwd.equals(rs.getString(2)) || passwd == rs.getString(2)))) {
					flag = 1;
					return SUCCESS;
				}
			}
			if (flag == 0) {
				addActionError("No such User!!");
				return ERROR;
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		return ERROR;
	}
	public void validate() {
		if("".equals(username) || "".equals(passwd)) {
			addActionError("Missing username or password!!");
		}
	}
}

In the above action classes, the JDBC connection is made with Host URL, DB username and password. 

In order to connect this web app to MySQL, you will need to create the database and the table. Here you can refer my database structure 

Database name: codesvila

Table Name: codesvila_users
Use the following query to create database Or import the DB from file:

CREATE DATABASE codesvila;
	CREATE TABLE `codesvila_users` (
  `id` int(4) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
);

Now it’s time to start the server and run this web application. Allocate the server and run it. 

Index login page

Login Example using Struts2 and JDBC
login page

Register page

Login Example using Struts2 and JDBC
Register page

Form validation at client side using javascript

Login Example using Struts2 and JDBC
client-side javascript validation

User registered successfully

Login Example using Struts2 and JDBC
Registered Successfully

User already exists Error from server 

Login Example using Struts2 and JDBC
User exists error

Login using with invalid user

Login Example using Struts2 and JDBC
No such user error

Login valid-user

Login Example using Struts2 and JDBC
Valid Credentials

After valid login successful redirects to the welcome page

Login Example using Struts2 and JDBC
Welcome Page