1、搭建spring3MVC
2、整合hiebernate4
【搭建spring3MVC】
(1)放入sping3所需的库、commons-logging-1.0.4.jar、jstl.jar
(2)配置web.xml,启动spring和mvc
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>spring3hibernate4</display-name> <!-- Spring配置文件开始 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-config.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- Spring配置文件结束 --> <!-- Spring MVC配置开始 --> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Spring MVC配置开始 --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd "> <!-- 扫描注解Bean --> <context:component-scan base-package="com.it.app"> <!-- 通过exclude-filter 把所有 @Controller注解的表现层控制器组件排除 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>spring-servlet.xml
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd" > <!-- 开启controller注解支持 --> <!-- 注:如果base-package=com.it.app 则注解事务不起作用 TODO 读源码 --> <context:component-scan base-package="com.it.app.web.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- --> <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:order="3"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="contentType" value="text/html"/> <property name="prefix" value="/WEB-INF/views/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
/** * */ package com.it.app.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author cwd * */ @Controller @RequestMapping(value="/goods") public class GoodsController { @RequestMapping(value="list") public String list(){ System.out.println("GoodsController.list:Passing through..."); return "goods_list"; } }goods_list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> goods list! </body> </html>【测试效果】
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/shop?characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="xyz" /> </bean> <!-- 可追加配置二级缓存 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" > <property name="dataSource" ref="dataSource"/> <property name="packagesToScan"> <list> <value>com.it.app</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop> <prop key="hibernate.hbm2ddl.auto">create</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.query.substitutions">true 1, false 0</prop> <prop key="hibernate.default_batch_fetch_size">16</prop> <prop key="hibernate.max_fetch_depth">2</prop> <prop key="hibernate.generate_statistics">true</prop> <prop key="hibernate.bytecode.use_reflection_optimizer">true</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> </bean>
/** * */ package com.it.app.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * @author cwd * */ @Entity @Table(name="goods") public class Goods implements Serializable { //商品编号id,商品名称name,商品类型type,商品价格price @Id @Column(name="id",length=32,nullable=false,unique=true) @GenericGenerator(name="generator",strategy="uuid.hex") @GeneratedValue(generator="generator") private String id; @Column private String name; @Column private String type; @Column private double price; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }GoodsDao.java
package com.it.app.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import com.it.app.domain.Goods; @Repository public class GoodsDao { @Autowired @Qualifier("sessionFactory") private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void save(){ Session session = this.getSessionFactory().getCurrentSession(); Transaction tr = session.beginTransaction(); Goods goods = new Goods(); goods.setName("spring touch"); goods.setType("book"); goods.setPrice(40.5); session.save(goods); tr.commit(); } }GoodsService.java
/** * */ package com.it.app.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.it.app.dao.GoodsDao; /** * @author cwd * */ @Service public class GoodsService { @Autowired private GoodsDao goodsDao; public GoodsDao getGoodsDao() { return goodsDao; } public void setGoodsDao(GoodsDao goodsDao) { this.goodsDao = goodsDao; } public void save(){ this.goodsDao.save(); } }修改GoodsController.java,操作数据库,修改后如下:
/** * */ package com.it.app.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.it.app.service.GoodsService; /** * @author cwd * */ @Controller @RequestMapping(value="/goods") public class GoodsController { @Autowired private GoodsService goodsService; @RequestMapping(value="list") public String list(){ System.out.println("GoodsController.list:Passing through..."); this.goodsService.save(); return "goods_list"; } public GoodsService getGoodsService() { return goodsService; } public void setGoodsService(GoodsService goodsService) { this.goodsService = goodsService; } }
【Spring集成测试】
(1)加入JUnit4测试库
(2)创建一个测试类用来测试sping+hibernate
创建商品服务测试类GoodsServiceTest.java
/** * */ package com.it.app.service; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author cwd * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-config.xml"}) public class GoodsServiceTest { @Autowired private GoodsService goodsService; @Test public void testSave(){ goodsService.save(); } }最后测试类测试和web测试方式都成功,框架搭建成功!