摘要:ZK使用Spring Bean
ZK 使用 Spring Bean
其實重點只在 ZK 中怎麼取得 Spring Bean 而已,程式碼如下:
ServletContext sc = (ServletContext) Sessions.getCurrent().getWebApp().getNativeContext();
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
HelloBean helloBean = (HelloBean) ctx.getBean("helloBean");
String word = helloBean.sayHello();
底下是一個簡單的demo,示範如何在ZK中使用Spring Framework.
一、寫一個HelloBean,將利用Spring注入name的值
package demo.composer;
public class HelloBean {
private String name;
public String sayHello() {
return "Hello " + name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
二、在web.xml中加入Spring的設定
<!--
spring context listener, this is necessary
-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!--
spring config location
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
三、設定applicationContext.xml,注入name的值
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloBean" class="demo.composer.HelloBean">
<property name="name" value="Rocky Wang" />
</bean>
</beans>
四、為求簡化,不考慮MVC架構,寫一個hello.zul當主頁面demo
<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="new page title" border="normal">
<zscript>
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import demo.composer.*;
ServletContext sc = (ServletContext) Sessions.getCurrent().getWebApp().getNativeContext();
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
HelloBean helloBean = (HelloBean) ctx.getBean("helloBean");
String word = helloBean.sayHello();
</zscript>
<label value="${word }" />
</window>
</zk>
打完收工。
Rocky Wang. OCUP, NCLP, SCJP, SCWCD, SCBCD