webwork使用spring ioc集成

webwork使用spring ioc集成

在WebWork 2.2.x 之后,它将直接内建支持spring ioc了,所以更加简单了,,
做个例子
第一步:在web-inf下建一个webwork.properties文件,
内容为
webwork.objectFactory = spring
第二步:也就是加载applicationContext.xml,可以采取前面前的两种之一,,这里采用后面那种
<listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
第三步:创建要装载的实例,在applicationContext.xml(采用监听的方式,记住默认的位置是在web-inf下面)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans default-autowire="autodetect"> <!--记注一定要加上-->
  <bean id="userManager" singleton="true" class="helloWorld.UserManager"/>
</beans>
第四步:在修改我原来的例子
HelloWorldAction.java

package helloWorld;
import com.opensymphony.xwork.ActionSupport;
public class HelloWorldAction extends ActionSupport{

    String greeting;
    UserManager userManager;
    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }

    public String getGreeting() {
        return greeting;
    }
    public UserManager getUserManager() {
  return userManager;
 }

 public void setUserManager(UserManager userManager) {
  this.userManager = userManager;
 }

 public String execute() throws Exception {
  userManager.sayHello();
  System.out.println("after userManager.sayHello()");
        if (greeting.equals("") || greeting == null) {
            addFieldError("greeting", getText("greeting"));
            return ERROR;
        }
        return SUCCESS;
    }
}
而UserManager.java类如下
package helloWorld;
public class UserManager {
 public UserManager()
 {
  System.out.println("create instance of UserManger");
 }
 public void sayHello()
 {
  System.out.println("hello zjh");
 }
}
再访问http://localhost:8080/WebWork/index.jsp提交后在tomcat console窗口打印出
hello zjh
after userManager.sayHello()

你可能感兴趣的:(webwork使用spring ioc集成)