Struts Login Application in Eclipse

In this example we will see how to create a login application using Struts. The following files are required for the login application.I have used Eclipse Indigo and Tomcat 6 for developing the example set.The following files are required for the login application.

  • login.jsp
  • success.jsp
  • failure.jsp
  • LoginForm.java
  • LoginAction.java
  • ApplicationResource.properties
  • struts-config.xml
  • web.xml




Tools used :

In order to create an application we are going to use the following tools.

Step 1 : Create Dynamic Web Project

Open Eclipse and goto File -> New -> Project and select Dynamic Web Project in the New Project wizard screen.

Struts Application in Eclipse

After selecting Dynamic Web Project, press Next Then Eclipse will ask you for name of the project. Enter the name of the project as StrutsLoginExample and click on Finish.

Struts Application in Eclipse

Step 3 : Add Jar files to the project

Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder.The following jar files should be added to the project for successful deployment of struts project :

Struts Application in Eclipse

Copy all the tld files to WEB-INF folder and make the entry of these tld files in web.xml file.

After that we have to configure ActionServlet of struts with web.xml.The first page that will be called in the login application is the login.jsp page. This configuration should be done in web.xml as <welcome-file-list> . The following xml shows how to configure struts in web.xml.



Step 4 : Configure web.xml

Now we have to configure ActionServlet of struts with web.xml. The following xml shows how to configure struts in web.xml.

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:jsp="http://java.sun.com/xml/ns/javaee/jsp" 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" version="2.5">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>

Step 5 : Create FormBean Class :


LoginForm.java
package com.jwt.struts.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class LoginForm extends org.apache.struts.action.ActionForm {

	private String userName;

	private String password;

	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {
		ActionErrors errors = new ActionErrors();
		if (userName == null || userName.length() < 1) {
			errors.add("userName", new ActionMessage("error.userName.required"));

		}
		if (password == null || password.length() < 1) {
			errors.add("password", new ActionMessage("error.password.required"));

		}
		return errors;
	}

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

The validate method in the LoginForm class is called when the Form is submitted. If any errors are found then the control is returned back to the input page where the errors are displayed to the user. The input page is configured in the action tag of strut-config file. <html:errors/> tag is used to display the errors in the jsp page.

Inside the validate method, we will check whether the username and password is entered, If not the corresponding error message is displayed to the user. The error messages are configured in the ApplicationResource.properties file.

Step 6 : Create Action Class :

Following is our controller helper class named as "LoginAction" :

LoginAction.java
package com.jwt.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

import com.jwt.struts.form.LoginForm;

public class LoginAction extends Action {

    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";
    
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        LoginForm loginForm = (LoginForm) form;
        if (loginForm.getUserName().equals(loginForm.getPassword())) {
            return mapping.findForward(SUCCESS);
        } else {
            return mapping.findForward(FAILURE);
        }
    }
}

The execute method contains the business logic of the application. Here first we typecast the ActionForm object to LoginForm, so that we can access the form variables using the getter and setter methods. If the user name and password is same then we forward the user to the success.jsp page else we forward to the failure.jsp page.

These configuration has been done in struts-config.xml file

All the configuration regarding the action will be made as in the file struts-config.xml mentioned bellow.

Step 7 : Create struts-config.xml file

Create struts-config.xml inside WEB-INF directory of project and add below line of code in this file.

struts-config.xml
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
<form-beans>
<form-bean name="LoginForm" type="com.jwt.struts.form.LoginForm" />
</form-beans>

<global-forwards>
<forward name="welcome" path="/Welcome.do" />
</global-forwards>

<action-mappings>
<action input="/login.jsp" name="LoginForm" path="/Login"
scope="session" type="com.jwt.struts.action.LoginAction">
<forward name="success" path="/success.jsp" />
<forward name="failure" path="/failure.jsp" />
</action>
<action path="/Welcome" forward="/welcomeStruts.jsp" />
</action-mappings>

<message-resources parameter="com/jwt/resources/ApplicationResource" />

</struts-config>

The validate method in the LoginForm class is called when the Form is submitted. If any errors are found then the control is returned back to the input page where the errors are displayed to the user. The input page is configured in the action tag of strut-config file. <html:errors/> tag is used to display the errors in the jsp page.

Step 8 : Create jsp files

create jsp file login.jsp inside WebContent directory of your project with following contents.

login.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div style="color:red">
<html:errors />
</div>
<html:form action="/Login" >
User Name : <html:text name="LoginForm" property="userName"/> <br>
Password  : <html:password name="LoginForm" property="password"/> <br>
<html:submit value="Login" />
</html:form>
</body>
</html>

In login.jsp, We used Struts HTML Tags to create login page. The form has two text field to get the user name and password. The form also has one submit button, which when clicked calls the login action. <html:errors /> tag is used to display the error messages to the user.

Now create jsp file success.jsp inside WebContent directory of your project with following contents

success.jsp
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>
Login Success. Welcome
<bean:write name="LoginForm" property="userName"></bean:write>
</h1>
</body>
</html>

User will navigate to success.jsp page after successful login.

Now create jsp file failure.jsp inside WebContent directory of your project with following contents

failure.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div style="color: red">
<h1>
Invalid user name
<bean:write name="LoginForm" property="userName"></bean:write>
</h1>
</div>
</body>
</html>

Once the authentication will fail, user will be redirected to failure.jsp page

Step 9 : Create properties file :

Create ApplicationResource.properties inside com.jwt.resources package and add below line of code into this file.

error.userName.required = User Name is required.
error.password.required = Password is required.

The ApplicationResource.properties file contains the error messages. The key "error.userName.required" is used in the validate function to add a new error. Since the error messages are configured in a seperate properties file they can be changed anytime without making any changes to the java files or the jsp pages.So no need to restart server if we are changing any values to these keys.

Step 10 : Run the application :

To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server (Shortcut: Alt+Shift+X, R)

Login Page :

Struts Application in Eclipse

Validation Error :

Struts Application in Eclipse

Success Page :

Struts Application in Eclipse

Error Page :

Struts Application in Eclipse

Directory Structure Of the Project

Directory Structure of the project is given below.

Struts Application in Eclipse

You can download the source code of the example by clicking on the Download link below.

Download this example(src+lib) developed in eclipse



comments powered by Disqus