日期:2014-05-16  浏览次数:20337 次

JSF和Spring的集成之一
JSF和Spring集成的资料比较少,原理是获得彼此的上下文引用,以此进一步获得各自管理的bean,这是可能的,因为两者是web应用框架都遵循servlet规范,为二者整合提供了可能和基础。
  在 Spring中ApplicationContext是相当重要的类,对于web应用,它还包装了 javax.servlet.ServletContext,为web应用提供了所有可以利用的数据,包括可管理bean,Faces中通过 FacesContext类可以获得所有可以利用的资源,同样包括JSF的可管理支持bean,它们都围绕着ServletContext提供了自己的门面,通过各自的门面在Servlet容器的世界里彼此相通。

  本文介绍两种方式,实现二者集成:

  1. 通过写自己的类来完成二者的连通,实际上只是获得彼此世界里存活的bean,对于JSF中事件处理可能需要更进一步的构思和编码,为了这点,第二个方法介绍了一种框架。

  2. 使用框架完成二者集成。

  一 自己动手,下面的代码以示例为主,其它涉及的类和接口略去。

  这个工具类提供在JSF世界里查找Spring管理的bean。也实现在Spring中查找JSF组件的方法。

package com.skysoft.rbac.dao;  
import org.springframework.context.ApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;  
import javax.faces.context.FacesContext;  
import javax.servlet.ServletContext;  
import javax.faces.el.ValueBinding;  
import javax.faces.FactoryFinder;  
import javax.faces.application.Application;  
import javax.faces.application.ApplicationFactory;  
public final class SpringFacesUtil {  
public SpringFacesUtil() {  
}  
/**  
   * 从Spring中查找bean.  
   * @param beanname String  
   * @return Object  
   */  
public static Object findBean(String beanname) {  
    ServletContext context = (ServletContext) FacesContext.getCurrentInstance().  
        getExternalContext().getContext();  
    ApplicationContext appctx = WebApplicationContextUtils.  
        getRequiredWebApplicationContext(context);  
    return appctx.getBean(beanname);  
}  
/**  
   * 从JSF中查找bean.  
   * @param beanname String  
   * @return Object  
   */  
public static Object lookupBean(String beanname) {  
    Object obj = getValueBinding(getJsfEl(beanname)).getValue(FacesContext.  
        getCurrentInstance());  
    return obj;  
}  
private static ValueBinding getValueBinding(String el) {  
    return getApplication().createValueBinding(el);  
}  
private static Application getApplication() {  
    ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder.  
        getFactory(FactoryFinder.APPLICATION_FACTORY);  
    //FactoryFinder.FACES_CONTEXT_FACTORY  
    //FactoryFinder.RENDER_KIT_FACTORY  
    return appFactory.getApplication();  
}  
private static String getJsfEl(String value) {  
    return "#{" + value + "}";  
}  
}

  下面定义一个由JSF管理的bean:

package com.skysoft.rbac.dao;  
   
import javax.servlet.ServletContext;  
import org.springframework.context.ApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;  
import org.skysoft.struts.jsf.util.FacesUtils;  
public class ServiceLocatorBean  
    implements ServiceLocator {  
private static fina