Create your first login application using Struts

Introduction

Struts2 is one of the most popular Web Application Framework based on MVC design pattern. Struts2 is the latest version that is being used these days and is a complete remod over the earlier Struts version and is based on “OpenSymphony Webwork” framework.

To note, Struts 1.0 got merged with Webwork 2.0 to form Struts 2.0


Create your first login application using Struts 2

To start building your first login Application in Struts 2.0, create a new Dynamic Web project in Eclipse. Make sure the build path is setup with all the required JARs, which can be downloaded from http://struts.apache.org/download.cgi

Copy all the JAR files in the downloaded ZIP, to /WEB-INF/lib directory of the project.

Inside the /Web Content directory, create a new JSP file named, say login.jsp
All you need is to create a form inside the JSP file as:

Create a new package as com.jcombat.action and create LoginAction.java as the action class for Login

Since  in Struts 2.0, we can use any POJO to receive the form input and the same POJO class acts as an Action class, so we go ahead as follows.

Now let’s create a mapping in struts.xml that would be deciding the navigations on the basis on actions we invoke. Make sure, struts.xml lies inside the /src directory of our project

There are several points to be noticed here. ‘struts.devMode’ is made to true, since we want some logs to be created in the development process. It is always better to create the separate packages to group the actions. Here, I am using the package as ‘default‘.

On the login page, when I click the login button, the corresponding ‘Login‘ action get fired, as we named it in the struts.xml. The application searches for this action in the struts.xml file. On finding the respective action, it finds the action class mapped to it (com.jcombat.action.LoginAction) and method to invoke (loginCheck) in the action class. Now, if the method loginCheck returns

user, then the user is taken to home.jsp

admin, then the user is taken to admin.jsp

error, then the user is taken to login.jsp

As the method loginCheck  returns user, so it will take the user to home.jsp. So, let’s create a jsp page as home.jsp as:

Before you run the application, the last thing that need to be done is to configure the /WebContent/WEB-INF/web.xml, as it is the entry point for any request to Struts 2, which needs to have the FilterDispatcher defined. So make sure, the web.xml has something like the following:

Filter mapping for the URL pattern /* assures the Struts2 filter to run on all matching URLs.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.