Login Form Example Using Struts :

We are going to implement a web application using Struts framework which will have a login screen. Once the user is authenticated, user will be redirected to a welcome page.This example will take following steps :

  1. Create login.jsp which will contain the form to be displayed to the user.
  2. Create a Form Bean Class (LoginForm.java) that will hold the form values provided by the user.
  3. Create a Controller class (LoginAction.java) that will check for the user input and decide which view to be redirected to the users either success.jsp or failure.jsp
  4. Create a success page (Success.jsp) and failure page (Failure.jsp)
  5. And finally we will configure our form bean and action classes in struts-config.xml.

We are going to implement a web application using Struts framework which will have a login screen. Once the user is authenticated, user will be redirected to a welcome page.This example will take following steps :

  1. Create login.jsp which will contain the form to be displayed to the user.
  2. Create a Form Bean Class (LoginForm.java) that will hold the form values provided by the user.
  3. Create a Controller class (LoginAction.java) that will check for the user input and decide which view to be redirected to the users either success.jsp or failure.jsp
  4. Create a success page (Success.jsp) and failure page (Failure.jsp)
  5. And finally we will configure our form bean and action classes in struts-config.xml.





Files Required

Following files are required for this application.

  • login.jsp
  • success.jsp
  • LoginForm.java
  • LoginAction.java
  • 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 LoginExampleStruts1 and click on Finish.

Step 2 : 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

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 3 : 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: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>LoginFormStruts1</display-name>

	<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>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

</web-app>

Step 4 : Create FormBean Class :


LoginForm.java
package com.example.javawebtutor.form;

import javax.servlet.http.HttpServletRequest;

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

public class LoginForm extends ActionForm {

	private String userName = null;
	private String password = null;

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

	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		this.password = null;
	}

}

There are two fields in this form bean "userName" and "password", that will hold the value of two fields userName and password entered by user. We override the method "reset" in form bean. "reset" method is called at the end of the every request processed by the struts. In reset method we have set the value of password as null which means every time the user will open the login jsp in browser it will show the last entered username and reset the password field.



Step 5 : Create Action Class :

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

LoginAction.java
package com.example.javawebtutor.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.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.example.javawebtutor.form.LoginForm;

public class LoginAction extends Action {
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		LoginForm loginForm = (LoginForm) form;

		if (loginForm.getUserName() == null || loginForm.getPassword() == null
				|| !loginForm.getUserName().equalsIgnoreCase("Mukesh")
				|| !loginForm.getPassword().equals("kumar")) {
			return mapping.findForward("success");
		} else
			return mapping.findForward("failure");
	}

}

In this class ActionForm instance is typecast to LoginForm in the execute method of LoginAction and then logic to verify the username and password will decide which view to be send back to the user. In this case, userName must be "Mukesh" ans password must be "kumar' to go to the view associated with the "success", otherwise view associated with "failure" will be returned.

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 6 : 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.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
		  
<struts-config>
    <form-beans>       
        <form-bean name="loginForm" type="com.example.javawebtutor.form.LoginForm"/>
    </form-beans> 
    <action-mappings>
	    <action name="loginForm" path="/login" type="com.example.javawebtutor.action.LoginAction" scope="request" input="/login.jsp">
	        <forward name="failure" path="/login.jsp" redirect="true"/>
	        <forward name="success" path="/success.jsp" redirect="true"/>
	    </action>
    </action-mappings>
</struts-config>

Step 7 : Create jsp files

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

login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://struts.apache.org/tags-html" 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=ISO-8859-1">
<title>Login Example</title>
</head>
<body>
	<html:form action="/login" focus="userName">
	Username : <html:text property="userName" />
		<br>
	Password : <html:password 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
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Successful Login Page</title>
</head>
<body>
	<h2>Welcome Boss</h2>
</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

index.jsp
<jsp:forward page="/login.jsp"></jsp:forward>

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)

Struts Application in Eclipse

Now, Enter "Mukesh" as username and "Kumar" as password you will be carried out to the success.jsp page :

Struts Application in Eclipse

Now, try with wrong username or password, you will be carried back to the login.jsp 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