2、导入Spring和Struts2的jar包。
其中,struts2-spring-plugin-2.1.8.jar是struts2、spring整合的关键。
3、首先新建一个业务代码LoginAction,演示登录处理。
package action;
import server.MyServer;
import server.MyServerImpl;
import com.opensymphony.xwork2.Action;
public class LoginAction implements Action {
private String username;
private String password;
private String tip;
private MyServer ms;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public void setMs(MyServer ms) {
this.ms = ms;
}
public String execute() throws Exception {
//setMs(new MyServerImpl());
if (ms.valid(getUsername(), getPassword())) {
setTip("登录成功");
return "success";
} else {
return "error";
}
}
}
4、然后新建一个接口MyServer,如下:
package server;
public interface MyServer {
public boolean valid(String username,String password);
}
5、然后新建一个实现类,如下:(这里为了演示方便,没有分包)
package server;
public class MyServerImpl implements MyServer {
public boolean valid(String username, String password) {
if(username.equals("cat")&&password.equals("123")){
return true;
}
return false;
}
}
6、在web.xml文件中对struts2和spring进行配置,如下:
< xml version="1.0" encoding="UTF-8" >
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
7、在WebRoot中的WEB-INF下新建一个applicationContext.xml文件,配置spring,如下:
(注意,这个文件不能直接在src下配置,必须在这里配置,不然web容器找不到)
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
8、然后在src下新建一个struts.xml,配置struts2,如下:
(注意文件中action的class属性,不是一个类,而是spring配置中bean的id,属性由spring来注入)
< xml version="1.0" encoding="UTF-8" >