Struts 2 Tutorial Series: Sample Application – Login Module

Welcome to Struts 2 Tutorial series where we will explore how to create a Struts 2 application. In this tutorial, we will first make a very simple Login application, then we expand our application to use Hibernate and Tiles, Ajax, Interceptor, Validator, etc. Finally, there will be a fully functional Struts 2 application – Quick Memo.

Goal of this sample app

We will do a simple Login module in this tutorial, since this is common for all applications. We are going to get the basic knowledge about the framework.

Finally, the login app should like this.

When Login successfully,

When Login fails,

Tools and Libraries we Need
Before we start our example, we need several tools. I’m listing what I’m using. Of course, you can use higher version, but that may caused some problems. If you just start to learn Struts 2, you can save a lot of time by using the following versions. I provide the links for your download.
1. JDK 1.5 or above
2. Tomcat 6.0
3. Eclipse IDE for Java EE Developers
4. Struts 2.0.14 (link). JAR files required for this application. Download Link.

  • commons-logging-1.0.4.jar
  • freemarker-2.3.8.jar
  • ognl-2.6.11.jar
  • struts2-core-2.0.12.jar
  • xwork-2.0.6.jar

Getting Started
Create a Dynamic Web Project.

#notice my project directory is: C:\eclipseworkspace\Struts2Login
Copy the required JAR files to WebContent->WEB-INF->lib folder under project directory. Now, you project should like this.



Config web.xml file

Set Struts2 as filter in web.xml file. If you don’t understand why set it as a filter, check out here.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Struts2 Login</display-name>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
 
	</filter-mapping>
	<welcome-file-list>
		<welcome-file>Login.jsp</welcome-file>
	</welcome-file-list>
</web-app>

Create Login Action Class

Note that, the above action class contains two fields, username and password. They will hold values passed from form, and also contains an authenticate() method that will authenticate users. Normally, this can be setup with LDAP or Database. But here for a simple demonstration, we are simply check if username is “admin” and password is “admin”. The authenticate() method returns a string which determines the result page.

LoginAction.java

package com.programcreek.struts2;
 
import com.opensymphony.xwork2.ActionSupport;
 
public class LoginAction extends ActionSupport{
	private String username;
	private String password;
 
	public String authenticate() {
 
		if (this.username.equals("admin")
				&& this.password.equals("admin")) {
			return "success";
		} else {
			addActionError(getText("error.login"));
                        //a function from ActionSupport, to get properties values from properties file
                        //we will explore this below.
			return "error";
		}
	}
 
	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;
	}
}

Create ResourceBundle

ResourceBundle is a very useful Java entity that helps separating static contents from source code. It can hold some static messages such as names for form elements. We define an ApplicationResources.properties file for our application. This file should be present in WEB-INF/classes folder.

Now we create a source folder called resources like this.

ApplicationResources.properties

label.username= Username
label.password= Password
label.login= Login
error.login= Invalid Username/Password. Please try again.

JSP Pages
Login.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts 2 - Login Application</title>
</head>
<body>
<h2>Struts 2 - Login Application</h2>
<s:actionerror />
<s:form action="login.action" method="post">
	<s:textfield name="username" key="label.username" size="20" />
	<s:password name="password" key="label.password" size="20" />
	<s:submit method="execute" key="label.login" align="center" />
</s:form>
</body>
</html>

Welcome.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
 
<head>
<title>Welcome Page - Struts 2 - Login Application</title>
</head>
 
<body>
	<h2>Congratulations, <s:property value="username" />!</h2>
	Welcome to Struts 2 world.
</body>
</html>

struts.xml file

Create struts.xml file under resources directory like the ApplicationResources.properties 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>
	<constant name="struts.enable.DynamicMethodInvocation"
		value="false" />
	<constant name="struts.devMode" value="false" />
 
	<constant name="struts.custom.i18n.resources"
		value="ApplicationResources" />
 
	<package name="default" extends="struts-default" namespace="/">
 
		<action name="login" method="authenticate"
			class="com.programcreek.struts2.LoginAction">
			<result name="success">Welcome.jsp</result>
			<result name="error">Login.jsp</result>
 
		</action>
	</package>
</struts>

We are done

Run the project now.

Next Step
Once a user is authenticated, the website content will displayed. Normally, the content will from database. Our next step is to make a simple database usage app with Hibernate.

I will make apps based on requirements. Database is the next most important thing to understand, so I make it next step.

References:
Freemarker

You may also like:

  1. JSP Tutorials on 2010-3-14

    Great tutorial, love the print screens!

  2. tara on 2010-4-2

    helpful for the beginners..

  3. praneet on 2010-4-9

    hi,
    Thanks 4 gr8 tutorial with the help of this tutorial i developed a login app with database connectivity and sign up page..its workin fi9 thans for ur support

  4. Phani on 2010-5-3

    such a nice tutorial keep it up

  5. Jagdish on 2010-9-22

    hi
    its a very good tutorial…i never did program on struts 1 or 2 so really helpful. one thin would like to comment is that i tried few other tuts as well bt none work without a bit modification but this one was really working at no change.
    thanks again…

  6. Tom Tshitangano on 2011-2-2

    Hi,

    I have deployed the Application, I am using the following url to access the deployed application

    http://localhost:8080/OnlineGeneralLedger/Login.jsp

    I changed the project name to OnlineGeneralLedger. Where do we put the jsp’s?

    Regards,
    Tom Tshitangano

  7. admin on 2011-2-2

    It should be under WebContent.

  8. w on 2011-8-4

    Hi I am very new ….
    When I tried the following error appeared: error 500–internal server error java.lang.RuntimeException: Cannot find FacesContext

    No idea what the error is and how to resolve the issue.

    If possible then pleas help.

    waiting for reply.
    regards

  9. Admin on 2011-8-4
  10. sandeep on 2011-11-1

    Hi,
    you cannot put struts.xml file in resourse directory
    This example gives error on running because struts.xml should be in class path

  11. kiruthika on 2011-11-16

    hi,
    i followed this tutorial.But when i run it i get 404 requested resource(/strutslogin/) not found. i dont know how to correct this error as i am completely new to struts. please help.

  12. Rajesh on 2011-11-26

    Hi,
    Thanx for the Tutorial,

    It is def.an eyeopener for me in Struts.

    But when i run the app given above it always goes to the success page and not the failure page.

    Can u tell me why.

    Appreciate ur help.

  13. Rajeswari on 2011-12-8

    Thanks for the tutorial. It works for me after changing the struts.xml to the src directory. What ever user id is entered, it shows the welcome page always.

  14. Its is really help full on 2011-12-22

    Hi can you tell me how to diaply list value in jsp using struts-tag without using scriplet
    like if value is hard coded and i want to display those value using loop so how to display

  15. kiran kumar on 2012-1-27

    Hi, thanks for giving this example, this is very use full to me,can u plz suggest me how to connect to DB and need some more example.

Leave a comment