Struts 2 Annotation Login Application Example

In this demo you will see how to create annotation based login application using Struts 2 framework.

Tools needed:

  • JDK 1.6
  • Tomcat server 7 (Please configure tomcat server in eclipse using this tutorial)
  • Eclipse (Kepler has been used for this tutorial)

Steps:

  • Create Maven project name: StrutsUsingAnnotation in your eclipse workspace. Final project structure will look as below:

Struts 2 Annotation Login Application Example

  • pom.xml:
<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>com.javahonk</groupId>
    <artifactId>StrutsUsingAnnotation</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>StrutsUsingAnnotation Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.16.3</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>2.3.16.3</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>StrutsUsingAnnotation</finalName>
    </build>
</project>

  • web.xml:
<!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>
        <init-param>
            <param-name>struts.devMode</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>struts.custom.i18n.resources</param-name>
            <param-value>ApplicationResources</param-value>
        </init-param>
        
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
</web-app>

  • LoginAction.java
package com.javahonk.action;

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

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;

@Results({
        @Result(name = "success", location = "/WEB-INF/jsp/welcome.jsp"),
        @Result(name = "error", location = "/index.jsp"),
        @Result(name = "input", location = "/index.jsp") })
public class LoginAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String loginid;
    private String password;
    
    @Override
    @Action(value="/loginAction")
    public String execute() throws Exception {
        
        if (null == loginid || loginid.length() == 0){
            addActionError(getText("error.login.required"));
            return ActionSupport.ERROR;
        }
        if (null == password || password.length() == 0){
            addActionError(getText("error.password.required"));
            return ActionSupport.ERROR;
        }
        if (!(loginid.equalsIgnoreCase("Java") 
                && password.equalsIgnoreCase("Honk"))){
            addActionError(getText("error.loginid_OR_password.incorrect"));
            return ActionSupport.ERROR;
        }
        
        return ActionSupport.SUCCESS;       
        
    }   

    public String getLoginid() {
        return loginid;
    }
    
    @RequiredStringValidator(message = "Please enter your Login Id!")
    public void setLoginid(String loginid) {
        this.loginid = loginid;
    }

    public String getPassword() {
        return password;
    }

    @RequiredStringValidator(message = "Please enter your password!")
    public void setPassword(String password) {
        this.password = password;
    }


}

  • StrutsAction.java
package com.javahonk.action;

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

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;

@Results({
       @Result(name="success", location="/WEB-INF/jsp/success.jsp"),
       @Result(name="input", location="/WEB-INF/jsp/welcome.jsp"),
       @Result(name="error", location="/WEB-INF/jsp/welcome.jsp")
    })
public class StrutsAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String firstName;
    private String lastName;
    private String message;

    @Override
    @Action(value="/strutsAction")
    public String execute() throws Exception {
        message = "Your entered input values are:";
        return ActionSupport.SUCCESS;
    }

    public String getFirstName() {
        return firstName;
    }

    @RequiredStringValidator(message = "First Name is required!")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @RequiredStringValidator(message = "Last Name is required!")
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

  • ApplicationResources.properties
label.welcome = Struts 2 Annotation Login Application!!!
label.login.successful = Login Successful. Enter data below:
label.loginid =  Login Id
label.password =  Password
label.firstName =  First Name
label.lastName =  Last Name

error.login.required = Login Id is required!
error.password.required = Password is required!
error.loginid_OR_password.incorrect = Login Id OR Password is incorrect!

error.firstName.required = First Name is required!
error.lastName.required = Last Name is required!
error.location.required = Location is required!
  • index.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Struts 2 Annotation Login Application</title>
        <s:head/>
    </head>
 
    <body>
        <h1 style="color: green"><s:text name="label.welcome" /></h1>
        <h3 style="color: green"><s:text name="Login Id: Java" /></h3>
        <h3 style="color: green"><s:text name="Password: Honk" /></h3>
        <s:if test="hasActionErrors()">
            <div id="fieldErrors">
                <s:actionerror/>
            </div>
        </s:if>               
        <s:form action="loginAction" namespace="/" method="post" name="strutsForm">
            <s:textfield name="loginid" size="30" maxlength="50" key="label.loginid"/>
            <s:password name="password" size="30" maxlength="50" key="label.password"/>            
            <s:submit type="button" key="submit" label="Submit" align="right"/>            
        </s:form>
    </body> 
</html>  
  • success.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Struts 2 Annotation Login Application</title>
        <s:head/>
    </head>
 
    <body>
        <h1 style="color: green"><s:text name="label.login.successful" /></h1>
        <s:if test="hasActionErrors()">
            <div id="fieldErrors">
                <s:actionerror/>
            </div>
        </s:if>
        
        <s:form action="strutsAction" namespace="/" method="post" name="strutsForm">
            <s:textfield name="firstName" size="30" maxlength="50" key="label.firstName"/>
            <s:textfield name="lastName" size="30" maxlength="50" key="label.lastName"/>
            <s:submit key="submit" align="right"/>
        </s:form>
    </body> 
</html>  
  • welcome.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Struts 2 Annotation Login Application</title>
    </head>
    <body>
        <h2 style="color: green"><s:property value="message"/></h2>
        <p>
            First Name: <s:property value="firstName" />
        </p>
        <p>
            Last Name: <s:property value="lastName" />
        </p>       
    </body>
</html>
  • I believe you have already setup eclipse with tomcat server. To run: Right click project (StrutsUsingAnnotation) –> Run As –> Run on Server. You will see below login page:

Struts 2 Annotation Login Application Example

 

  • On login page please enter login Id and Password given on page otherwise you will see validation exception shown below:

 

 

Struts 2 Annotation Login Application Example

 

  • Now enter correct Login Id and Password:

Struts 2 Annotation Login Application Example

 

  • Enter First name and Last name then click Submit:

Struts 2 Annotation Login Application Example

  • Once you click Submit you will see your entered data as below:

struts26

For more information please read this struts tutorial

download2 Download Project: StrutsUsingAnnotation

Leave a Reply

Your email address will not be published. Required fields are marked *