Struts 2 Tutorial Series: Sample Application – Login Module


Welcome to Struts 2 Tutorial series where we will explore how to create web application by using Struts 2.

In this tutorial, we will first make a very simple Login module, then add features of Hibernate and Tiles, Ajax, Interceptor, Validator, etc. Finally, it will be a fully functional Struts 2 web application - "Quick Memo".

Before you get started, you may want to watch a 10-minute video to get a basic idea of how to use Struts 2.

1. Goal of this sample app

Goal: login module.

Finally, it looks like this.

When Login successfully, it shows:

When Login fails, it shows:

2. Tools and Libraries required

Before we start our example, we need several tools and libraries. The following are what I’m using. Of course, you can use higher version. 1) JDK 1.5 or above. 2) Tomcat 6.0 3) Eclipse IDE for Java EE Developers. 4) Struts 2.0.14. JAR files required for this application.

  • 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

3. 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.

4. 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>

5. 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;
	}
}

6. 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.

7. JSP Pages

JSP files should be put under the WebContent directory.

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>

8. 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>

9. Done

Run the project now.

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

-> Back to Index.

References:
Freemarker

Category >> Struts 2  
If you want to post code, please put the code inside <pre> and </pre> tags.
  • tia

    Thanks you for sharing this, very clear for beginners like me.

    There are two small mistake: one in login.jsp page, the method name should be “authenticate”, “execute” is the method name in video tutorial. :))

    second, in struts.xml file, if I add namespace=”/” in package tag, it can not find the action, I don’t know why.

  • John

    jsp should be put under WebContent directory. You can take a look at the following short video to see how to run the project: http://www.programcreek.com/2012/03/struts-2-video-tutorial-hello-world/.

  • prateek

    Where to put the jsp ?? how to run the project ?? Please elaborate.

  • nitin

    Hi, I am getting FreeMarker template error, whenever i do validate=true in my jsp and i am having FirstAction-validation.xml file. Please help me.

  • sathish

    Hi

    I tried this and i’m get the http status 404 error
    The requested resource is not available.

    I’m using apache tomcat 7.

  • a

    Hi I tried this and I am getting 404 error

  • narendra

    thanks buddy it was of great help, i done a struts 2 simple hello world example but now after doing this tutorial i am grabbing the struts2 workflow in a very convinient manner. Thanks for ur help buddy and do come back wioth similar tutorials especially the validations one

  • sweety

    I tried the above example but I got the following error help me ro resolve this error:

    HTTP Status 500 –

    ——————————————————————————–

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    There is no Action mapped for namespace / and action name login. – [unknown location]
    com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:186)
    org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:41)
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:497)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:421)

    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.14 logs.

    ——————————————————————————–

    Apache Tomcat/6.0.14

  • krishnan

    Excellent tutorial

  • appu

    its not at all a good tut. ther is nothing in this.

  • Naveen

    great work dude… Please keep on posting!!!

  • Tarkeshwar

    This application is very helpful. In this program very simple mistakes are there place the struts.xml in src and in login.jsp page <s:submit method="execute"is given please change is to method="authenticate" it will work properly.Changing the method="authenticate" because in LoginAction class he has used authenticate method.

  • http://vin_slade@yahoo.co.in Vineet

    Connection to DB is same as in any DAO ,jus call a method from the action which will take care of the dtabase activity and then capture the returned data in an bean onject .You can then use this bean in you JSP to display the required data using the tag .

  • kiran kumar

    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.

  • http://www.programcreek.com/2010/03/struts-2-tutorials-sample-application-login-module/ Its is really help full

    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

  • Rajeswari

    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.

  • Rajesh

    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.

  • kiruthika

    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.

  • sandeep

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

  • Admin
  • w

    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

  • admin

    It should be under WebContent.

  • Tom Tshitangano

    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

  • Jagdish

    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…

  • Phani

    such a nice tutorial keep it up

  • praneet

    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

  • tara

    helpful for the beginners..

  • http://www.free-jsp-tutorials.com/ JSP Tutorials

    Great tutorial, love the print screens!