Struts Login

In this tutorial I will show you how to write a Login Module using Struts.

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
  
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts-core</artifactId>
      <version>1.3.10</version>
    </dependency>
  
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts-taglib</artifactId>
      <version>1.3.10</version>
    </dependency>
  
</dependencies>

1. Action Form

Create a Action Form class and name it Login.java that contains the following code.

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

LoginForm.java

package com.kruders.form;
 
import javax.servlet.http.HttpServletRequest;
 
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
 
public class LoginForm extends ActionForm{
    private static final long serialVersionUID = 1L;
    private String userName;
    private String password;
    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;
    }
     
    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;
    }
 
}

2. Action Class (Controller)

Let us create an Action class that will handle the request. Here Action Class contains the business logic.

LoginAction.java

package com.kruders.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.kruders.form.LoginForm;
 
public class LoginAction extends Action{
    public ActionForward execute(ActionMapping mapping,ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            LoginForm loginForm = (LoginForm) form;
            if(loginForm.getUserName().equals("test") && loginForm.getPassword().equals("test")){
                return mapping.findForward("success");
            } else {
                return mapping.findForward("fail");
            }
 
    }
}

3. View

Create following JSP files, login.jsp, success.jsp and fail.jsp with the following content in your WebContent folder.

login.jsp

<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<html>
<head>
<title>Login Page</title>
</head>
<body>
    
    <html:form action="/login" >
        User Name :<html:text name="LoginForm" property="userName" />  <html:errors property="userName" />
         
        Password  :<html:password name="LoginForm" property="password" /> <html:errors property="password" />
        <html:submit value="Login" />
    </html:form>
     
</body>
</html>
<logic:redirect forward="helloWorld"/>


The view login.jsp is to provide user to enter login details and submitting for Login. <html:errors property=”userName” /> and <html:errors property=”password” /> tags are used to display the error messages to the user.

success.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" 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>Success Page</title>
    </head>
    <body>
        Login Success. Welcome <bean:write name="LoginForm" property="userName"></bean:write>
    </body>
</html>


The view success.jsp is to show success message.

fail.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>Failure Page</title>
    </head>
    <body>
            Invalid User Name or Password 
    </body>
</html>

The view fail.jsp is to show failure message.

4. Struts Config

Create a struts-config.xml file in WEB-INF folder.

<?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.kruders.form.LoginForm"/>
    </form-beans>
 
     
    <global-forwards>
        <forward name="login" path="/login.do"/>
    </global-forwards>
     
    <action-mappings>
        <action input="/login.jsp" name="LoginForm" path="/login"  validate="true" scope="request" type="com.kruders.action.LoginAction">
            <forward name="success" path="/success.jsp" />
            <forward name="fail" path="/fail.jsp" />
        </action>
    </action-mappings>
 
    <message-resources parameter="ApplicationResources" />
</struts-config>

5. Deployment Descriptor

Now configure the deployment descriptor. Here, we have asked the container to give our ActionServlet any request that matches the pattern *.do

Add the following configuration information in the web.xml file

<welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
</welcome-file-list>
 
<servlet>
    <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>

6. Run Project

Now when you run the project, following screen will be displayed as shown in Figure 2.1

Figure 2.1 Figure 2.1


On failure, following screen will be displayed as shown in Figure 2.2

Figure 2.2 Figure 2.2

The folder structure of the example is shown below in Figure 2.3

Figure 2.3 Figure 2.3

You can download the source code of this example here.

No comments yet.

Leave a Reply