整体结构
1.导入响应的jar包
2.编写Action,使用继承ActionSupport的方式创建Action,并使用模型驱动来封装表单
在Action中编写需要调用的Service层的属性,并提供set方法
public class CustomerAction extends ActionSupport implements ModelDriven{ private CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } //必须手动new private Customer customer=new Customer(); //模型和属性驱动 /** * 保存客户 * @return */ public String add(){ customerService.save(customer); return NONE; } @Override public Object getModel() { return customer; } }
3.编写struts的配置文件,struts.xml中我们主要配置Action,将Action的创建由Spring来管理,在struts.xml主要对bean的引用
(1)将Action的创建由Spring管理
<!--配置Action必须多例--> <bean id="customerAction" class="cn.zqr.action.CustomerAction" scope="prototype"> <property name="customerService" ref="customerService"/> </bean>
(2)在struts.xml主要对bean的引用
<package name="crm" namespace="/" extends="struts-default"> <!--Action由Spring管理,class值为Spring的id--> <action name="customer_*" class="customerAction" method="{1}"> </action> </package>
4.编写service层,service中主要需要对dao层的调用,和开启事务两步
对dao层的调用,采用Spring对bean的管理方法,在类中提供dao层的对象,并提供对应的set方法
@Transactional
public class CustomerServiceImpl implements CustomerService {
private CustomerDao customerDao;
public void setCustomerDao(CustomerDao customerDao) {
this.customerDao = customerDao;
}
/**
* 保存客户信息
* @param customer
*/
@Override
public void save(Customer customer) {
customerDao.add(customer);
}
}
<!--配置service--> <bean id="customerService" class="cn.zqr.service.impl.CustomerServiceImpl"> <property name="customerDao" ref="customerDao"/> </bean> <!--配置sessionFacotry--> <bean class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" id="sessionFactory"> <property name="configLocation" value="classpath:hibernate.cfg.xml"/> </bean> <!--配置事务--> <bean class="org.springframework.orm.hibernate5.HibernateTransactionManager" id="transactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!--开始事务的注解--> <tx:annotation-driven/>
事务的管理和dao层的持久化都依赖于session,使用Spring管理sessionFactory的创建,并开始事务注解