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 someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  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.

  16. Vineet on 2012-2-26

    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 .

  17. Tarkeshwar on 2012-3-14

    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.

  18. Naveen on 2012-4-19

    great work dude… Please keep on posting!!!

  19. appu on 2012-5-29

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

  20. krishnan on 2012-7-7

    Excellent tutorial

  21. sweety on 2012-7-12

    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

  22. narendra on 2012-8-21

    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

  23. a on 2012-8-31

    Hi I tried this and I am getting 404 error

  24. sathish on 2012-10-4

    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.

  25. nitin on 2013-1-10

    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.

  26. prateek on 2013-10-5

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

  27. John on 2013-10-5

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

  28. tia on 2014-6-22

    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.

  29. Nancy on 2014-12-4

    Hi, How to retrieve multiple files from db using struts

Leave a comment

*