1 web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 通过上下文参数指定spring配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
<!-- 配置spring的上下文载入器监听器 ,项目启动时加载spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置struts2的前端控制器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
2 struts.xml设置
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts> <constant name="struts.devMode" value="true" /> <!-- 将对象工厂指定为spring --> <constant name="struts.objectFactory" value="spring"/> <!-- struts的Action访问后缀 --> <constant name="struts.action.extension" value="do"/>
<package name="default" namespace="/" extends="struts-default"> <action name="bookAction" class="bookAction"></action> </package> </struts>
3beans
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 读取属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="initialPoolSize" value="${initialPoolSize}"></property>
<property name="minPoolSize" value="${minPoolSize}"></property>
<property name="maxPoolSize" value="${maxPoolSize}"></property>
</bean>
<!-- 本地会话工厂bean -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 注入hibernate属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<!-- hibernate映射文件的位置 -->
<property name="mappingDirectoryLocations">
<list>
<value>classpath:cn/itcast/oa/domain</value>
</list>
</property>
</bean>
<!-- Hibernate事务管理器 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 对注解提供支持 -->
<context:annotation-config/>
<!-- 组件扫描 -->
<context:component-scan base-package="cn.itcast.oa"/>
<!-- 注解驱动 -->
<tx:annotation-driven transaction-manager="txManager"/>
</beans>
4 action 层
package cn.itcast.oa.action;
import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller;
import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.util.ValueStack;
import cn.itcast.oa.base.BaseAction; import cn.itcast.oa.domain.Book;
@Controller @Scope("prototype")
public class BookAction extends BaseAction<Book>{ public String execute() throws Exception{
System.out.println(model);
bookService.save(model);
return NONE; } }
// @Scope("prototype"): 每次请求都创建一个实例
5 action层继承了BaseAction<Book>
看下 BaseAction<Book>
public class BaseAction<T> extends ActionSupport implements ModelDriven<T>{ @Resource protected IBookService bookService; //在构造方法中获得model类型 public BaseAction(){ ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();//父类Action类型 Type[] types = type.getActualTypeArguments(); Class<T> clazz = (Class<T>) types[0]; try { model = clazz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } protected T model;
public T getModel() { return model; } }
6 servic层
package cn.itcast.oa.service;
import java.util.List;
import cn.itcast.oa.domain.Book;
public interface IBookService {
/** * 添加 */ public void save(Book book); /** * 根据id删除 */ public void delete(Long id); /** * 根据id修改 */ public void update(Book book); /** * 根据id查询 */ public Book getById(Long id); /** * 一次查询多个对象 */ public List<Book> getByIds(Long[] ids); /** * 查询所有 */ public List<Book> findAll();
}
7service Impl层
package cn.itcast.oa.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
import cn.itcast.oa.dao.IBookDao; import cn.itcast.oa.domain.Book; import cn.itcast.oa.service.IBookService; @Service @Transactional public class BookServiceImpl implements IBookService { @Resource private IBookDao bookDao; public void delete(Long id) { // TODO Auto-generated method stub bookDao.delete(id); }
public List<Book> findAll() { // TODO Auto-generated method stub return bookDao.findAll(); }
public Book getById(Long id) { // TODO Auto-generated method stub return bookDao.getById(id); }
public List<Book> getByIds(Long[] ids) { // TODO Auto-generated method stub return bookDao.getByIds(ids); }
public void save(Book book) { // TODO Auto-generated method stub bookDao.save(book); }
public void update(Book book) { // TODO Auto-generated method stub bookDao.update(book); }
}
8dao 层
package cn.itcast.oa.base;
import java.util.List;
/** * 通用Dao接口 * @author zhaoqx * */ public interface IBaseDao<T> { /** * 添加 */ public void save(T entity); /** * 根据id删除 */ public void delete(Long id); /** * 根据id修改 */ public void update(T entity); /** * 根据id查询 */ public T getById(Long id); /** * 一次查询多个对象 */ public List<T> getByIds(Long[] ids); /** * 查询所有 */ public List<T> findAll(); }
9dao层实现层
package cn.itcast.oa.base;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List;
import javax.annotation.Resource;
import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate;
import cn.itcast.oa.domain.Book; /** * 通用Dao实现 * @author zhaoqx * * @param <T> */ @SuppressWarnings("unchecked") public class BaseDaoImpl<T> implements IBaseDao<T> { @Resource private SessionFactory sessionFactory; private Class<T> clazz; public BaseDaoImpl() { //获得实体类型 ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();//获得真正的父类 Type[] types = genericSuperclass.getActualTypeArguments(); clazz = (Class<T>) types[0]; } public void save(T entity) { getSession().save(entity); } public void delete(Long id) { getSession().delete(getSession().get(clazz, id)); } public void update(T entity) { getSession().update(entity); }
public List<T> findAll() { String hql = "FROM " + clazz.getSimpleName(); return getSession().createQuery(hql).list(); }
public T getById(Long id) { return (T) getSession().get(clazz, id); } public List<T> getByIds(Long[] ids) { String hql = "FROM " + clazz.getSimpleName() + " WHERE id in (:ids)"; Query query = getSession().createQuery(hql); query.setParameterList("ids", ids);//一次赋值多个 return query.list(); } public Session getSession(){ return sessionFactory.getCurrentSession(); } }
10 book dao
public interface IBookDao extends IBaseDao<Book> {
}
11 book dao impl
package cn.itcast.oa.dao.impl;
import org.springframework.stereotype.Repository;
import cn.itcast.oa.base.BaseDaoImpl; import cn.itcast.oa.dao.IBookDao; import cn.itcast.oa.domain.Book; /** * BookDao锛岀户鎵緽aseDaoImpl * @author zhaoqx * */ @Repository public class BookDaoImpl extends BaseDaoImpl<Book> implements IBookDao {
}
12
package cn.itcast.oa.domain;
public class Book { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Book [id=" + id + ", name=" + name + "]"; } }
13
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.itcast.oa.domain.Book" table="itcast_book">
<id name="id">
<generator class="native"/>
</id>
<property name="name" length="32"/>
</class>
</hibernate-mapping>
14 test
package cn.itcast.test;
import java.util.List;
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.oa.domain.Book; import cn.itcast.oa.service.IBookService;
/** * 测试basedao * @author zhaoqx * */ public class TestBaseDao { /** * 测试findAll操作 */ @Test public void test6(){ //初始化spring ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); IBookService bookService = (IBookService) ctx.getBean("bookServiceImpl"); List<Book> list = bookService.findAll(); for(Book book : list){ System.out.println(book); } } /** * 测试getByIds操作 */ @Test public void test5(){ //初始化spring ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); IBookService bookService = (IBookService) ctx.getBean("bookServiceImpl"); Long[] ids = new Long[]{2L,3L,4L}; List<Book> list = bookService.getByIds(ids); for(Book book : list){ System.out.println(book); } } /** * 测试getById操作 */ @Test public void test4(){ //初始化spring ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); IBookService bookService = (IBookService) ctx.getBean("bookServiceImpl"); Book book = bookService.getById(2L); System.out.println(book); } /** * 测试update操作 */ @Test public void test3(){ //初始化spring ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); IBookService bookService = (IBookService) ctx.getBean("bookServiceImpl"); Book book = new Book(); book.setId(2L); book.setName("php"); bookService.update(book); } /** * 测试delete操作 */ @Test public void test2(){ //初始化spring ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); IBookService bookService = (IBookService) ctx.getBean("bookServiceImpl"); bookService.delete(1L); } /** * 测试save操作 */ @Test public void test1(){ //初始化spring ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); IBookService bookService = (IBookService) ctx.getBean("bookServiceImpl"); Book book = new Book(); book.setName("c"); bookService.save(book); } }\