Spring and Struts 2 Integration
Spring framework provides an easy way to manage the dependency. It can be easily integrated with struts 2 framework.
The ContextLoaderListener class is used to communicate spring application with struts 2. It must be specified in the web.xml file.
You need to follow following steps:
- Create struts2 application and add spring jar files.
- In web.xml file, define ContextLoaderListener class.
- In struts.xml file, define bean name for the action class.
- In applicationContext.xml file, create the bean. Its class name should be action class name e.g. com.javatpoint.Login and id should match with the action class of struts.xml file (e.g. login).
- In the action class, define extra property e.g. message.
Example of Spring and Struts 2 Integration
You need to create following files for simple spring and struts 2 application:
- index.jsp
- web.xml
- struts.xml
- applicationContext.xml
- Login.java
- welcome.jsp
- error.jsp
1) index.jsp
This page gets the name from the user.
2) web.xml
It defines controller class for struts 2 and ContextLoaderListener listener class to make connection between struts2 and spring application.
3) struts.xml
It defines the package with action and result. Here, the action class name is login which will be searched in the applicationContext.xml file.
4) applicationContext.xml
It defines a bean with id login. This beans corresponds to the mypack.Login class. It will be considered as the action class here.
It should be located inside the WEB-INF directory.
5) Login.java
It defines two property userName and message with execute method where success is returned.
6) welcome.jsp
It prints values of userName and message properties.
7) error.jsp
It is the error page. But it is not required in this example because we are not defining any logic in the execute method of action class.
Output
|