Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create a Login Application with Struts Framework in Java

In this article we will see the step by step on how to create a Login Application with Struts Framework in Java.

Struts Login Application

Struts framework helps keep the application clean by segregating View, Controller and Model. Making the segregation clear makes the application easy to develop and maintain. Change control is enhanced and defect fixing time is reduced. Creating a struts application is easy and saves a lot of time as a project progresses into maintenance phases. In this tutorial, a simple struts based login application will be presented, covering basic features and end to end project creation.

Login Application

The application will show a login page with username and password fields. A login button will be available. On click of the login button, username and password will be validated by checking the field length. Upon success, a welcome page will be displayed. If the login fails, an error message will be displayed in the login page.

UserAction.java

packagecom.src.loginapp.action;
importjava.util.ArrayList;
importjava.util.List;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importcom.src.loginapp.form.UserInformationForm;
public class UserAction extends Action{
	publicActionForward execute(ActionMappingmapping,ActionForm form,
			HttpServletRequestrequest,HttpServletResponse response) throws Exception {
		UserInformationFormuserInformationForm = (UserInformationForm) form;
		List errorList = new ArrayList();
		// check if username is empty
		if (userInformationForm.getUsername() == null || "".equals(userInformationForm.getUsername().trim())){
		
			// set error message
			errorList.add(new String("Please enter Username"));
			request.getSession().setAttribute("errorList", errorList);
			//stay in login page 
			returnmapping.findForward("failure");
		}
		// check if password is empty
		else if (userInformationForm.getPassword() == null || "".equals(userInformationForm.getPassword().trim())) {
			// set error message
			errorList.add(new String("Please enter Password"));
			request.getSession().setAttribute("errorList", errorList);	
			// stay in login page
			returnmapping.findForward("failure");
		}
	
		// forward to welcome page
		returnmapping.findForward("success");
	}	
}

The code above is a simple Action class that is invoked upon clicking the “Login” button. The class does a simple validation of the username and password. If the username and/or password are empty, the request is forwarded to the failure URL, in this case, login.jsp. In this case, a corresponding error message is set to an ArrayList and stored in the session scope. If the username and password are not empty, then the request is forwarded to the “success” URL, in this case, the welcome.jsp page.

UserInformationForm.java

packagecom.src.loginapp.form;
importjavax.servlet.http.HttpServletRequest;
importorg.apache.struts.action.ActionErrors;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionMapping;
importorg.apache.struts.action.ActionMessage;
publicclassUserInformationFormextendsActionForm{
 	String username;
	String password;
 	publicStringgetUsername(){
		return username;
	}
 	publicvoidsetUsername(String username){
		this.username= username;
	}
	publicStringgetPassword(){
		return password;
	}
 	publicvoidsetPassword(String password){
		this.password= password;
	}
}

The UserInformationForm.java class contains the properties required for the login application. Since this is going to be a simple struts application, none of the properties are validated here. The validations are carried out in the Action class instead.

login.jsp

<%@tagliburi="http://struts.apache.org/tags-html" prefix="html"%>
<%@tagliburi="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ tagliburi="http://struts.apache.org/tags-logic" prefix="logic" %>

<html>
<head>
</head>
<body>
<h1>Struts Login Application</h1>

<html:form action="/Login">

<div style="padding:16px">
<logic:present name="errorList">
<logic:iterate id="error" name="errorList">
	<p style="color:red"><bean:write name="error"/></p>
</logic:iterate>
</logic:present>
</div>
<div style="padding:16px">
	User Name  :
	<html:text property="username" size="20" maxlength="20"/>
	<br></br>
	Password  :
	<html:password property="password" size="20" maxlength="20"/>
</div>
<div style="padding:16px">
	<div style="float:left;padding-right:8px;">
		<html:submit></html:submit>
	</div>
</div>
</html:form>
</body>
</html>

In this application, the login.jsp acts as the landing page as soon as the application starts. The page has many struts specific features. Here is a brief description of each of the features found in the login.jsp file.

<html:form action="/Login">

This line ensures that any submit action performed on this page is forwarded to the URL “/Login”

<html:text property="username" size="20" maxlength="20"/>

The above code renders a text box that is linked to the ActionForm’s username property. The textbox can accept 20 characters at the maximum and the size attribute determines the maximum number of characters visibly shown in the text box while keying in the data. In this case, since the size attribute is 20, the last 20 characters will be shown at any given point in time.

<html:password property="password" size="20" maxlength="20"/>

The html:password tag renders a password text box (characters entered are masked for security purposes) that is tied to the ActionForm’s password property. The size and maxlength attributes are similar to the html:text size and maxlength.

<html:submit></html:submit>

html:submit renders a simple html submit button. Here, on click of the submit button, the request is forwarded to “/Login”.

<logic:present name="errorList">

The logic:present tag looks into the request, session and application scope to find an attribute by the name “errorList”. The highest priority is given to request scope, followed by session scope, and finally the application scope. If the attribute is present in any one of the three scopes, the execution continues with the block enclosed by the logic:present tag. If the attribute is not present in any of the three scopes, the block is skipped and execution jumps to the line after the logic:present endtag.

<logic:iterate id="error" name="errorList">
	<p style="color:red"><bean:write name="error"/></p>
</logic:iterate>

The logic:iterate is a looping tag. The tag loops through a collection specified in the name attribute, in this case, “errorList”. The tag searches for the collection in request, session and application scopes, and uses the collection to loop through. The highest priority is given to request scope, followed by session scope, and finally the application scope. If the collection is not found in any scope, an exception occurs. The logic:present tag above the logic:iterate tag ensures that such exceptions do not occur. The “Id” attribute provides a handle to the current collection element. The tag uses the handle “error” to print the error message.

welcome.jsp

<%@tagliburi="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
</head>
<body>
<h1>
	Welcome <bean:write name="userInformationForm" property="username" />
</h1>
</body>
</html>

The welcome.jsp simply renders the message “Welcome” followed by the username value submitted from the login screen. The username is displayed using the bean:writetag that can access the ActionForm bean’s username attribute that is populated by the username field in the login.jsp

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>
	<form-beans>
		<form-bean
			name="userInformationForm"
			type="com.src.loginapp.form.UserInformationForm"/>
	</form-beans>
	<action-mappings>
		<action
			path="/Login"
			type="com.src.loginapp.action.UserAction"
			name="userInformationForm"
			input="/pages/login.jsp">	
			<forward name="success" path="/pages/welcome.jsp"/>
			<forward name="failure" path="/pages/login.jsp"/>
		</action>
	</action-mappings>
</struts-config>

The struts-config.xml file ties all the files together. The form-beans section has one ActionForm by the name UserInformationForm. The action-mapping has one Action class configuration for the UserActionclass, that uses the userInformationForm bean. The action has two forwards, one for successful validation that takes the user to the welcome screen and another for failure in validation that makes the user stay in the login screen.

web.xml

Finally, configure the deployment descriptor to include the Struts controller (ActionServlet) and welcome pages.

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>S Struts Examples</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>pages/login.jsp</welcome-file>
	</welcome-file-list>
</web-app>

The welcome page is configured to take the user to the login.jsp page.

Once all the files are in place and the build path for the application is configured to include all necessary library files, run the application on server. The end result should appear as follows:

Click the submit button without entering the password. An error message should appear and the user should remain in the login page.

Making validation

Figure 1: Making validation

Login Application

Figure 2: Login Application

Enter both user name and password fields, and the user should be taken to the welcome screen with the username displayed after “Welcome”

Page after login

Figure 3: Page after login

Conclusion

In this article we saw how to create login application with Struts Framework in Java. Hope you liked, see you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login