Build a spring environment and integrate it with struts
1. First import the packages required by spring
2. Add the spring listener and the location of the spring configuration file to the web. xml file.
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
/WEB-INF/spring-servlet.xml
3. Compile the business logic component and establish the FirstService interface and implementation class FirstServiceImpl
public interface FirstService {boolean valid(String username);}
public class FirstServiceImpl implements FirstService {public boolean valid(String username) {if (username.equals(kevin)) {System.out.println(spring);return true;} else {return false;}}}
Make a small change in LoginAction, use the business logic component for judgment, introduce the business logic interface, and inject dependencies in the following spring configuration file.
public class LoginAction extends ExampleSupport {private FirstService fs;public void setFs(FirstService fs) {this.fs = fs;}@Overridepublic String execute() throws Exception {if (kevin.equals(getUsername())) {if(fs.valid(getUsername())){
4, spring configuration file named spring-servlet.xml, put under web-inf, (here I named other names have been reported error, web. xml location, name is also corresponding, but still report error, do not know why, had to name back to spring-servlet.xml)
The configuration file contains the bean of the business logic component firstService and the bean of the action. The instantiation of the action is handed over to the IOC container of spring for management, and the service logic component is injected in the bean of the action.
Note: here, the scope of the loginAction bean is prototype, which ensures that a new action is created for processing each request. This avoids the thread security issue of the action, because spring uses the singleton mode by default, in this way, only one action is created, and each access is to access the same action. Data is not secure. struts2 requires that each access is a different action instance.
5. Modify the struts configuration file.
Add
Modify the loginAction configuration. The class points to the bean ID in the spring configuration file.
6. Test
Enter the user name and password on the page. After the verification is correct, the welcome page is displayed. The spring environment is successfully set up and integrated with struts2.