Having user entity create it is finally the time to write some code! We are going to create two Spring Beans: Bussiness Object (BO) to providing interface for bussiness operations and Data Access Object (DAO) to communicate with database using entity User. To do so, we create two interfaces (UserBo and UserDao) and their implementations (UserBoImpl and UserDaoImpl) in package com.frogdroid.integration.user. The content of the files is listed below.
Following that we create appropriate bean definitions and put them in src/main/resources/resources/spring/UserBean.xml file.
In addition we include UserBean.xml file in src/main/webapp/WEB-INF/applicationContext.xml file as follows:
Structure of the project after changes is presented in Figure 10.
Figure 10: Project with BOs, DAOs and their configuration.
Integration with Struts2
To use Struts2 in our project we have to add filter to web.xml file. The filter will be mapped, so each request to *.action and struts/* will be executed through StrutsPrepareAndExecuteFilter. The part to be added to web-app section in web.xml is presented below.
Following that we have to create UserAction class that runs appropriate actions and return input to StrutsPrepareAndExecuteFilter. The class is put in src/main/java/com/frogdroid/integration/user/action/UserAction.java and its content is listed below.
We add the following action bean definition to UserBean.xml file, so it can be used in struts action file.
Following that we have to create file with struts actions. The file should be placed in WEB-INF/classes/struts.xml in final war structure, which indicates that it should be created in src/main/resources/struts.xml. If you use different location struts actions will not be mapped. The file mapps actions invoked by the user to appropriate java classes/beans and its content is presented below. Depending on action appropriate methods (listAll, delete, add) from UserAction class are invoked. Our application has the functionality to list, add, and delete users from database.
To show add user form we have to create WEB-INF/content/user/addForm.jsp file and to list all users we have to create WEB-INF/content/user/list.jsp. The content of the files is presented below.
Make sure that the names of the fields correspond to properties in your UserAction class.
Make sure that the names of the properties correspond to properties in your User entity. In addition, iterator uses property (‘users’) that should be defined in UserAction class.
The structure of the project after changes is presented in Figure 11.
Figure 11: Project structure after integration with Struts2″.
Before showing final project structure let’s tidy a little bit up. Remove: