Login form in Struts2 version 2.3.16

In this section we will explain you how to create login form in Struts 2 version 2.3.16. We have used the hard coded values to validate the user.

Login form in Struts2 version 2.3.16

How to create Login Form in Struts2?

In this video tutorial I am explaining you about the source code of the program to create the Login form in Struts2 framework. The Struts2 version 2.3.16 and Eclipse based Maven tool is used for this project.

In this project you will also learn how to use the Maven plugin of the Eclipse. We have used the Eclipse Lunar IDE for this project as it support the Maven tool. If you don't know how to use the Eclipse Lunar IDE, then check the tutorial Download Eclipse with Maven Plugin support.

This application presents a login form to the user and asks the user to enter "User Name" and "Password". There is button "Login" to login to the system.

When user enters the invalid user name and password and presses the login button, application displays the error message.

When user enters "Admin" and "Admin" both in the user name and password fields and presses the "Login" button, Login success screen is displayed.

This application is build using the Struts 2.3.16 and uses the Eclipse IDE to build the project. Applications can be run on the Tomcat server from the Eclipse IDE. Check the tutorial Tomcat 7 in Eclipse Helios for more details on running applications from Eclipse on the Tomcat Server.

Here is the video tutorial of "Login Form in Struts2 version 2.3.16":

In the above video you will find all the steps necessary to create the login form in Struts 2. This application is not validated against database, but you can easily add the database validation code.

Advertisement

Apache Struts 2 is the famous MVC framework and it is used by the developers to write enterprise applications for their clients. Login and user management is the main requirement of any enterprise application. Here you will learn how to make simple login screen and add validation code for validating the user.

Struts 2 Login Form with validation

You can run the application in the Tomcat it self. Check the above video for the complete details.

Download the source code of the Struts 2 Login form.

Let's understand the code of the application.

Maven Project management file (pom.xml)

The Maven 3 is used to manage the dependency of the project. Here is the code of the pom.xml file used in login application:

<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>net.roseindia</groupId>
  <artifactId>firstwebapp</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>firstwebapp Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <dependencies>
	
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.11</version>
	</dependency>

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

	<dependency>
		<groupId>com.opensymphony</groupId>
		<artifactId>xwork</artifactId>
		<version>2.1.3</version>
	</dependency>
	
  </dependencies>
  <build>
    <finalName>firstwebapp</finalName>
  </build>
</project>

We have used the Struts 2 version 2.3.16.3, which is the latest version of Struts 2 at the time of writing of this tutorial.

Action Class (Login.java)

The action class contains the code to be executed when a particular action is called. In our example execute() of the Login.java class is executed. This class contains two variables username and password for receiving the values entered by user.

Here is the code of Login.java action class:

package net.roseindia;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;

 
/**
 * <p> Validate a user login. </p>
 */
public  class Login  extends ActionSupport {


  public String execute() throws Exception {
  System.out.println("Validating login");
  if(!getUsername().equals("Admin") || !getPassword().equals("Admin")){
  addActionError("Invalid user name or password! Please try again!");
  return ERROR;
  }else{
  return SUCCESS;
  }
  }


  // ---- Username property ----

  /**
 * <p>Field to store User username.</p>
 * <p/>
 */
  private String username = null;


  /**
 * <p>Provide User username.</p>
 *
 * @return Returns the User username.
 */
  public String getUsername() {
  return username;
  }

  /**
 * <p>Store new User username</p>
 *
 * @param value The username to set.
 */
  public void setUsername(String value) {
  username = value;
  }

  // ---- Username property ----

  /**
 * <p>Field to store User password.</p>
 * <p/>
 */
  private String password = null;


  /**
 * <p>Provide User password.</p>
 *
 * @return Returns the User password.
 */
  public String getPassword() {
  return password;
  }

  /**
 * <p>Store new User password</p>
 *
 * @param value The password to set.
 */
  public void setPassword(String value) {
  password = value;
  }

}

In the above action class the execute() is used to validate the user. Here you can add the database code for validating the user against database.

Struts 2 action configuration file (struts.xml)

In this file we are configuring our action class Login.java. Here is the code of the struts.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />

    <package name="default" namespace="/" extends="struts-default">

        <default-action-ref name="index" />

        <global-results>
            <result name="error">/error.jsp</result>
        </global-results>

        <global-exception-mappings>
            <exception-mapping exception="java.lang.Exception" result="error"/>
        </global-exception-mappings>

        
		<action name="showLogin">
		<result>/pages/login.jsp</result>
		</action>
		
		<action name="doLogin" class="net.roseindia.Login">
		<result name="input">/pages/login.jsp</result>
		<result name="error">/pages/login.jsp</result>
		<result>/pages/loginsuccess.jsp</result>
		</action>
		        
    </package>

    

    <!-- Add packages here -->

</struts>

The code <action name="doLogin" class="net.roseindia.Login"> is used to configure the action to handle the "doLogin" request.

JSP form file

The JSP form file is used to generate the login form and during the login validation if any error comes is also displays the error message.

Here is the code of login.jsp file:

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts 2 Login Application!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>

</head>
<body>
<s:form action="/login/doLogin" method="POST">
<tr>
<td colspan="2">
Login
</td>

</tr>

  <tr>
   <td colspan="2">
   <s:actionerror />
   <s:fielderror />
   </td>
  </tr>

<s:textfield name="username" label="Login name"/>
<s:password name="password" label="Password"/>
<s:submit value="Login" align="center"/>

</s:form>
<p>Enter User name: Admin  and Password: Admin for checking the login sucess!!</p>
</body>

</html>

Login success page

Here is the code of the loginsuccess.jsp file which is used to display the welcome message once login is successful:

<html>
<head>

<title>Login Success</title>

</head>

<body>

<p align="center"><font color="#000080" size="5">Login Successful</font></p>

</body>

</html>

Struts configuration file 0

The struts.xml file is used to configure the struts2 filter. Here is the code:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
    <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>/login/*</url-pattern>
    </filter-mapping>

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

So, today you learned at roseindia.net how to make a login form in Struts2. Check more Struts 2 tutorials.

Download the source code of the Struts 2 Login form. 1