Developing Your First Struts2 Application

To demonstrate development of a Struts2 project, I will build a sample use case involving user login. This will involve two screens – initial login page and a home page which will be displayed only after successful login. In order to keep the sample simple, no business layer or data access layer is implemented. In a real project, you need to have separate layers for business logic processing and data access.

When user enters a valid user id and password (in this case “admin” and “admin”), he is taken to the home page. If user id or password is invalid or they are not entered, login page is redisplayed. Field validations and error handling is not implemented in this sample. We will add those features as we progress through the book.

Step 1 – Create a dynamic Web project in Eclipse

From the Eclipse File->New->Other menu, select Dynamic Web Project as shown below. In the next screen, enter the project name as “struts2demo” and then select the target runtime as “Tomcat” which was configured in the previous section. On clicking “Finish” you will get a fully configured Web application in Eclipse.

Creating your first struts2 project

Creating your first struts2 project

Creating your first struts2 project

Step 2 - Add required minimum set of Struts2 libraries to the Web project

Struts2 libraries required for the sample application are commons-logging-1.0.4.jar, commons-logging-api-1.1.jar, freemarker-2.3.8.jar, ognl-2.6.11.jar, struts2-core-2.0.11.jar and xwork-2.0.4.jar. In the later examples in this book, if any additional library is needed I will mention it specifically.

Copy the above jars to WEB-INF/lib in the struts2demo Eclipse Project.

Step 3 – Write the sample application code

Following are the files we need in struts2demo project and the purpose of each of them is also given.

Struts configuration file in src folder – struts.xml

Web application configuration which also configures Struts2 filter (inside WEB-INF folder) – web.xml

Login page which asks for UserId and Password (under WebContent folder) – login.jsp

Home page displayed after successful authentication(under WebContent folder) – home.jsp

A controller class to process submission of login form. In Struts2 this is called an Action class (under package struts2demo.login.action) – Login.java

Step 4 – Run sample application from Eclipse

Right click on the project “struts2demo” from the project explorer and click on Run As -> Run on Server. This will run the project in Tomcat server. To access the login page, from browser window type in the URL : http://localhost:8080/struts2demo. You should see the sample application up and running. Play with it for a while to get a hang of what you have built!

Struts2 in Action