Integrate struts2 with spring and use spring's core functions to implement dependency injection.
Spring:
The bean that should be configured in the configuration file is responsible for instantiating the object member attributes of the corresponding class:
1: import the basic two packages of spring dependency in the original struts2 project:
Spring-2.5.5.jar and struts2-spring-plugin-2.0.9.jar (because jar is too large, please download it on your own)
2: Add spring features to the project and add them to web. xml.
<Context-param>
<Param-name> contextConfigLocation </param-name>
<Param-value> classpath: applicationContext. xml </param-value>
</Context-param>
<Listener>
<Listener-class> org. springframework. web. context. ContextLoaderListener </listener-class>
</Listener>
3: remove the instantiation operation of several object members in the corresponding class in the struts project and only retain the interface.
Change
Private UserService userservice;
Private UserDao userdao;
And you must create getter and setter for them respectively.
4: add it to the spring configuration file
<Bean id = "loginAction" class = "org. action. CheckLogin">
<Property name = "userservice">
<Ref bean = "userservice"/>
</Property>
</Bean>
<Bean id = "userservice" class = "org. service. impl. UserServiceImpl">
<Property name = "userdao">
<Ref bean = "userdao"/>
</Property>
</Bean>
<Bean id = "userdao" class = "org. dao. impl. UserDaoImpl">
</Bean>
Note that these beans are dependent in sequence. They initialize several attribute members not initialized in the three classes,
This step removes the need to perform UserService userservice = new UserServiceImpl () in the class file.
5: called by action in the struts configuration file
<Action name = "login" class = "loginAction">