创建项目之前:我们需要导入我们需要的Hibernate和Struts2和Spring的相关架包。(博客自创,如有问题请留言博主,拒绝盗版,支持正版http://www.cnblogs.com/WuXuanKun/)
项目架构图:
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
我们需要搭建各个层:层次如上右图
1.搭建beans层:
①创建一个实体类Stock。
/** * 股票类 */ public class Stock { private int sid; //股票编号 private String sname;//股票名称 private int scount; //股数 public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getScount() { return scount; } public void setScount(int scount) { this.scount = scount; } }
②我们创建小配置。Stock.hbm.xml
<?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 package="cn.happy.beans"> <class name="Stock" table="Stock"> <id name="sid"> <generator class="native"></generator> </id> <property name="sname"/> <property name="scount" column="COUNT"/> </class> </hibernate-mapping>
2.搭建DAO层:
①创建Stock接口
/** * Stock接口 */ public interface IStockDAO { public int addStock(Stock stock); }
②实现接口
import java.io.Serializable; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.springframework.jdbc.core.support.JdbcDaoSupport; import cn.happy.beans.Stock; import cn.happy.dao.IStockDAO; public class StockDAOImpl implements IStockDAO{ //在这里定义一个SessionFactory变量 private SessionFactory sessionFactory; @Override public int addStock(Stock stock) { Session session = sessionFactory.getCurrentSession(); Serializable count=session.save(stock); Integer cc=(Integer)count; return cc.intValue(); } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
3.搭建Service服务层:
①创建接口StockService
public interface IStockService { public int saveStock(Stock stock); }
②实现上面的接口
public class StockServiceImpl implements IStockService { //服务层 需要一个dao的对象 private IStockDAO dao; @Override public int saveStock(Stock stock) { return dao.addStock(stock); } public IStockDAO getDao() { return dao; } public void setDao(IStockDAO dao) { this.dao = dao; } }
4.搭建action层
public class StockAction extends ActionSupport implements ModelDriven<Stock>{ private Stock stock; private IStockService service; //重点代码:在无参构造中new一个Stock对象。 private StockAction(){ stock=new Stock(); } //execute()方法是ActionSupport的一个方法。save()一条数据;判断是否插入一条记录。要是count大于0,证明页面有一条数据插入。成功跳入index.jsp页面。否则跳入add.jsp页面。 public String execute(){ int count = service.saveStock(stock); if (count>0) { return SUCCESS; }else { return INPUT; } } //getModel是ModelDriven<Stock>的一个方法 @Override public Stock getModel() { return stock; } public Stock getStock() { return stock; } public void setStock(Stock stock) { this.stock = stock; } public IStockService getService() { return service; } public void setService(IStockService service) { this.service = service; } }
5.搭建两个jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> </head> <body> <form action="addStock" method="post"> 股票名称:<input type="text" name="sname"/> 股票股数:<input type="text" name="scount"/> <input type="submit" value="提交"/> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> </head> <body> 成功页面 </body> </html>
6.创建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> <package name="default" namespace="/" extends="struts-default"> <action name="addStock" class="stockAction"> <result name="success">/index.jsp</result> <result name="input">/add.jsp</result> </action> </package> </struts>
7.创建连接具体数据库:本案例用Mysql数据库为例:搭建jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///test jdbc.username=wu jdbc.password=xuan
8.创建大配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- 01.C3p0 数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 设值注入,本质上使用的是类的set方法 --> <property name="driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 方式二:找到jdbc.peroperties文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 1.1 SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" ></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</prop> </props> </property> <property name="mappingLocations" value="classpath:cn/happy/beans/Stock.hbm.xml"></property> </bean> <!-- dao --> <bean id="stockDao" class="cn.happy.dao.impl.StockDAOImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- service --> <bean id="stockService" class="cn.happy.service.impl.StockServiceImpl"> <property name="dao" ref="stockDao"></property> </bean> <!-- action --> <bean id="stockAction" class="cn.happy.action.StockAction"> <property name="service" ref="stockService"></property> </bean> <!-- 事务;能让多个操作做为一个整体,同生共死 荣辱与共 DataSourceTransactionManager--> <!-- 01.事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <!-- 必须配置数据源 --> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 第三种:AspectJ AOP 配置事务 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- 具体的AOP --> <aop:config> <aop:pointcut expression="execution(* *..service.*.*(..))" id="pointCut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/> </aop:config> </beans>
9.该项目已经成功搭建完毕。可以做一个单测。(该步骤可以省略)
//购买股票测试 @Test public void addStockTest() { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); IStockService service=(IStockService)ctx.getBean("stockService"); Stock stock=new Stock(); stock.setSname("Y2162基金"); stock.setScount(23); service.saveStock(stock); System.out.println("OK!"); }
10.启动项目:
成功插入数据: