
本站地址:http://www.bajiao123.com

JSF+Spring+Hibernate的实例讲解

public String createAction() {
try {
Product product = ProductBeanBuilder.createProduct(this);
//Save the product.
this.serviceLocator.getCatalogService().saveProduct(product);
//Store the current product id inside the session bean.
//For the use of image uploader.
FacesUtils.getSessionBean().setCurrentProductId(this.id);
//Remove the productList inside the cache.
this.logger.debug("remove ProductListBean from cache");
FacesUtils.resetManagedBean(BeanNames.PRODUCT_LIST_BEAN);
} catch (DuplicateProductIdException de) {
String msg = "Product id already exists";
this.logger.info(msg);
FacesUtils.addErrorMessage(msg);
return NavigationResults.RETRY;
} catch (Exception e) {
String msg = "Could not save product";
this.logger.error(msg, e);
FacesUtils.addErrorMessage(msg + ": Internal Error");
return NavigationResults.FAILURE;
}
String msg = "Product with id of " + this.id + " was created successfully.";
this.logger.debug(msg);
FacesUtils.addInfoMessage(msg);
return NavigationResults.SUCCESS;
}
在这个action里面,基于ProductBean的一个Product业务对象被建立。ServiceLocator查询CatalogService。最后,createProduct的请求被委派给业务逻辑层的CatalogService。
Managed-bean declaration: ProductBean必须在JSF的配置资源文件faces-managed-bean.xml中配置:
<managed-bean>
<description>
Backing bean that contains product information.
</description>
<managed-bean-name>productBean</managed-bean-name>
<managed-bean-class>catalog.view.bean.ProductBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>id</property-name>
<value>#{param.productId}</value>
</managed-property>
<managed-property>
<property-name>serviceLocator</property-name>
<value>#{serviceLocatorBean}</value>
</managed-property>
</managed-bean>
ProductBean有一个请求的范围,这意味着如果ProductBean在JSP页面内引用JSF执行为每一个请求创建ProductBean实例的任务。被管理的ID属性与productId这个请求参数组装。JSF从请求得到参数,设置managed property。
Integration between presentation and business-logic tiers: ServiceLocator抽象了查询服务的逻辑。在例子应用程序中,ServiceLocator被定义成一个一个接口。接口被JSF managed bean实现为ServiceLocatorBean,它从Spring application context查询服务:
ServletContext context = FacesUtils.getServletContext();
this.appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
this.catalogService = (CatalogService)this.lookupService(CATALOG_SERVICE_BEAN_NAME);
this.userService = (UserService)this.lookupService(USER_SERVICE_BEAN_NAME);
ServiceLocator被定义为BaseBean中的一个属性。JSF managed bean容易连接ServiceLocator执行必须访问ServiceLocator的那些managed beans。使用了Inversion of control(IOC,控制反转)
业务逻辑层
定义业务对象,创建服务接口和实现,在Spring中配置这些对象组成了这一层的任务。
Business objects: 因为Hibernate提供了持久化,Product和Category业务对象需要为它们包含的所有属性提供getter和setter方法。
Business services:CatalogService接口定义了所有与目录管理有关的服务:
public interface CatalogService {
p
本站地址:http://www.bajiao123.com

