Login page with validation in struts 2

This is 4 of 7 part of struts 2 tutorial.

Tutorial Content:

In this example we will see how we can validate a login page using Struts 2.

In previous post, we have learned  about mapping from client request to action class and rendering appropriate jsp on the basis of returned string of execute() method of action class.

In this post,we will use struts ui tags to create login page so we will learn how to use tags.
Create project named “LoginAppInStruts2”.For configuring struts 2 in your eclipse IDE please refer configuring struts 2 link.


Create web.xml file in under the folder WebContent/WEB-INF.
copy following content in web.xml



Create login page as login.jsp under WebContent.

copy following content into login.jsp
<%@taglib uri="/struts-tags" prefix="s" %> is a directive used in jsp for including struts tag files.

The tag should be placed in the head section of the HTML page. The s:head tag automatically generates links to the css and javascript libraries that are necessary to render the form elements.

The s:form tag contains all the form elements. The action attribute contains the action name to wich the form should be submitted. This action name should be same as the one specified in the XML declarative architecture. In this example we use struts.xml file to do the configuration.

The textfield tag is used create a text box. The label attribute of the textfield tag contains the name to be displayed on the page and the name attribute contains the name of the property in the action class to be mapped. The password tag is same as the textfield tag except that the input value is masked. The submit tag is used to create a submit button, the value “Login” represents the label of the button.

Note that the code is simple without any HTML tables, this is because Struts 2 will automatically create the necessary tables for the page based on the theme selected. By default the XHTML theme is selected.

When user click on login button,Request is forwarded to Login action.


Create Welcome.jsp under WebContent.
copy following content into Welcome.jsp

Action class:

 Our LoginAction class extends ActionSupport. It is good to extend ActionSupport class as it provides default implementation for most common tasks.

 Create LoginAction.java under src

copy following code into LoginAction.java

The ActionSupport class implements Action interface which exposes the execute() method.
The following constants are declared in the Action interface which can be used as return values in the execute() method.
public static final String ERROR = “error”

public static final String INPUT = “input”
public static final String LOGIN = “login”
public static final String NONE = “none”
public static final String SUCCESS = “success” ERROR is returned when the action execution fails.
INPUT is returned when the action requires more input from the user.
LOGIN is returned when the user is not logged into the system.
NONE is returned when the action execution is successfull and there are no views to display.
SUCCESS is returned when the action executed successfully and the corresponding result is displayed to the user.Now in our action class we have two attributes:

private String userName;– It should be same as name of textfield for getting userName as input defined in login.jsp.
private String password;-It should same as name of textfield for getting password as input defined in login.jsp

tag -you can notice that we have used Struts tag .It renders value of attribute of action class.In this case,attribute is userName of loginAction.java.So whatever user entered in userName textfield will appear at that place in Welcome.jsp.


Create struts.xml in src.struts.xml provides mapping between url to action mapping.

copy following code into struts.xml:

Here our “default” package extends “struts-default” package. By extending the “struts-default” package the action will by default inherit the set of interceptors defined in the defaultstack. The “struts-default” package is defined in the struts-default.xml file.

All the common tasks done by the Actions are seperated and placed in different interceptors. You can define an interceptor stack for each action. Most commonly used interceptors are grouped in defaultstack of the struts-default package. The defaultstack will be sufficient in most cases. The inteceptors will be fired in the order in which they are declared in the stack both before and after the action is executed.

Now lets see the roles played by the different interceptors.

The params interceptor helps in transfering the request data onto the action object.

The workflow interceptor controls the flow of cotrol.

The workflow interceptor checks whether the action implements the Validateable interface , if it does, the workflow interceptor will invoke the validate() method of the Action class.

In the validate() method we validate the user name and the password. If the validation fails an error is added using the addFieldError() method.

The validate() method doesn’t return any errors, instead it stores all the errors with the help of the ValidationAware interface.

Now the workflow interceptor will check any validation errors has occured. If any error has occured the workflow interceptor will stop the request processing and transfer the control to the input page with the appropriate error messages.

The ResourceBundle:

ResourceBundle is very useful Java entity that helps in putting the static content away from the source file. Most of the application define a resource bundle file such as ApplicationResources.properties file which contains static messages such as Username or Password and include this with the application.

The properties files should have the same name as the Action class. In our case the properties file name is “LoginAction.properties” and the Action name is “LoginAction.java“. This property file should be present in WEB-INF/classes folders when the source is compiled.

Create LoginAction.properties under src.Copy following content to LoginAction.properties.

Run Project:

right click on project->run as->run on server

so when you paste resultant url(https://localhost:8080/LoginAppInStruts2/) to your browser,you will get some thing like this.

If you directly press login button without entering anything.You will get following.

if you enter userName as “mandliya” .you will get following.

If you enter userName as “arpit” and password also as “arpit”.you will get

Source code:

Now in next post,we will understand concept of interceptors in detail.

Related Posts

  • nvarchar vs varchar
    29 July

    nvarchar vs varchar in SQL Server

    Table of ContentsIntroductionVARCHARNVARCHARExamples to Demonstrate Difference between VARCHAR and NVARCHARVARCHAR vs NVARCHAR Comparison Chart This article will look at the difference between the data types NVARCHAR and VARCHAR in SQL Server. These data types are commonly used for storing textual data or strings for various design purposes. We will look at the description of each […]

  • Stream2watch
    29 July

    Stream2watch alternatives -13 Best Websites Like Streamtowatch in 2021

    Table of ContentsBest Working Proxies of the Stream2watch in 2021Stream2Watch alternativesSport365SportP2PCricFree12th PlayerVIP BoxLiveTVWiziwigStopStreamSport LemonMamaHDLAOLA1Sport RARTime4TVfuboTVFirstRowSportsVIP LeagueFrequently Asked Questions**Is Stream2watch a safe website?What are the best Streamtowatch Alternatives?Do you need an account for Stream2watch?Final Words Are you after the best Stream2watch alternatives? Good News! this article is all about efficient web-based resources for streaming football, baseball, […]

  • 29 July

    AirPod Case not Charging – Common Issues and Fixes

    Table of ContentsBefore you StartWhy Is My AirPod Case Not Charging?Five Easy Solutions for AirPods Case Not Charging1. Reset Your AirPods Case2. Clean the Charging Port 3. Get a new Charger and Cable4. Update the AirPods Firmware5. Replace the CaseTips for Avoid AirPod not Charging IssueFrequently Asked QuestionsWhy isn’t my AirPod case charging, but my AirPods […]

  • Mobdro alternatives
    29 July

    Mobdro Alternatives – 14 Best apps like Mobdro in 2021

    Table of ContentsBest Mobdro Alternatives Working in 2021Cyberflix TVMorph TVTerrarium TVTea TVVisit Thop TVTubi Tv123MoviesMovie BoxVuduOreo TVMegaBox HDFreeFlixYuppTVFrequently Asked QuestionsWhat is Mobdro?Why do you need Mobdro alternatives?Are there free Mobdro alternatives?Wrapping Up Can’t access Mobdro anymore and are worried about watching your favorite movies? Take a breath; you still have a long list of working […]

  • Select rows by multiple conditions using loc in Pandas
    29 July

    Select rows by multiple conditions using loc in Pandas

    The loc() function in a pandas module is used to access values from a DataFrame based on some labels. It returns the rows and columns which match the labels. We can use this function to extract rows from a DataFrame based on some conditions also. First, let us understand what happens when we provide a […]

  • Split dataframe in Pandas
    28 July

    Split dataframe in Pandas

    Table of ContentsUsing the iloc() function to split DataFrame in PythonBy RowsBy ColumnsUsing the sample() function to split DataFrame in PythonUsing the groupby() function to split DataFrame in PythonUsing the columns to split DataFrame in Python In real-life scenarios, we deal with massive datasets with many rows and columns. At times, we may want to […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.