一.
1.用到的jar包
2.现将hibernate和spring整合测试
src目录下beans.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: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-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:annotation-config/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/> <property name="url" value="jdbc:mysql://localhost:3307/gjl?useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="wodemima"/> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingResources"> <list> <value>cn/itcast/bean/Person.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.format_sql=false hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=false hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider </value> </property> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:annotation-driven transaction-manager="txManager"/> <bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"/> <bean id="personList" class="cn.itcast.web.PersonAction"/> </beans>
3.web.xml 这个web.xml是把struts2内容也集成进来了,如果不用可把struts部分删掉,里面还有hibernate内容OpenSessionInViewFilter不做解释,自己查吧。暂时没有用到可以删掉。这里我就不删了,后面集成struts要用到,先放在这里。
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <!-- 对Spring容器进行实例化 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
4.准备数据
4.1 Person.java
package cn.itcast.bean; public class Person { private Integer id; private String name; public Person() { super(); } public Person(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
4.2 Person.hbm.xml 它和Person.java在同目录下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.bean"> <class name="Person" table="person"> <cache usage="read-write" region="cn.itcast.bean.Person"/> <id name="id"> <generator class="native"/> </id> <property name="name" length="10" not-null="true"/> </class> </hibernate-mapping>
4.3PersonService.java 面向接口编程
package cn.itcast.service; import java.util.List; import cn.itcast.bean.Person; public interface PersonService { public void save(Person person); public void update(Person person); public Person getPerson(Integer personid); public void delete(Integer personid); public List<Person> getPersons(); }
4.4PersonServiceBean.java继承PersonService接口实现对数据库的操作
package cn.itcast.service.impl; import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import cn.itcast.bean.Person; import cn.itcast.service.PersonService; @Transactional public class PersonServiceBean implements PersonService { @Resource private SessionFactory sessionFactory; public void save(Person person){ sessionFactory.getCurrentSession().persist(person); } public void update(Person person){ sessionFactory.getCurrentSession().merge(person); } @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public Person getPerson(Integer personid){ return (Person)sessionFactory.getCurrentSession().get(Person.class, personid); } public void delete(Integer personid){ sessionFactory.getCurrentSession().delete( sessionFactory.getCurrentSession().load(Person.class, personid)); } @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) @SuppressWarnings("unchecked") public List<Person> getPersons(){ return sessionFactory.getCurrentSession().createQuery("from Person").list(); } }
5.进行测试 使用junit4
PersonServiceTest.java 运行观察数据库。
package junit.test; import static org.junit.Assert.*; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.bean.Person; import cn.itcast.service.PersonService; public class PersonServiceTest { private static PersonService personService; @BeforeClass public static void setUpBeforeClass() throws Exception { try { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); personService = (PersonService)applicationContext.getBean("personService"); } catch (RuntimeException e) { e.printStackTrace(); } } @Test public void testSave() { personService.save(new Person("呵呵")); } @Test public void testUpdate() { Person person = personService.getPerson(1); //.... person.setName("嘻嘻"); personService.update(person); } @Test public void testGetPerson() { Person person = personService.getPerson(2); System.out.println(person.getName()); try { System.out.println("请关闭数据库"); Thread.sleep(1000*15); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("第二次开始获取"); person = personService.getPerson(2); System.out.println(person.getName()); } @Test public void testDelete() { personService.delete(1); } @Test public void testGetPersons() { List<Person> persons = personService.getPersons(); for(Person person : persons){ System.out.println(person.getName()); } } }
二.以上测试成功后,开始集成struts2
1.struts.xml中<constant name="struts.objectFactory" value="spring" />把action的创建交给spring管理,需导入struts2-spring-plugin-2.1.8.jar。
2.struts.xml中class="personList
<action name="action_*" class="personList" method="{1}">
<result name="list">/WEB-INF/page/personlist.jsp</result>
<result name="add">/WEB-INF/page/addperson.jsp</result>风格
</action>
beans.xml中id="personList"
<bean id="personList" class="cn.itcast.web.PersonAction"/>
他们的class和id中都一样是personList
上面这个要注意
struts.xml也放在src目录下
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 指定Web应用的默认编码集,相当于调用HttpServletRequest的setCharacterEncoding方法 --> <!-- <constant name="struts.i18n.encoding" value="UTF-8"/> --> <!-- 该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。 如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 --> <constant name="struts.action.extension" value="do"/> <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 --> <constant name="struts.serve.static.browserCache" value="false"/> <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 --> <constant name="struts.configuration.xml.reload" value="true"/> <!-- 开发模式下使用,这样可以打印出更详细的错误信息 --> <constant name="struts.devMode" value="true" /> <!-- 默认的视图主题 --> <constant name="struts.ui.theme" value="simple" /> <constant name="struts.objectFactory" value="spring" /> <package name="person" namespace="/person" extends="struts-default"> <global-results> <result name="message">/WEB-INF/page/message.jsp</result> </global-results> <action name="action_*" class="personList" method="{1}"> <result name="list">/WEB-INF/page/personlist.jsp</result> <result name="add">/WEB-INF/page/addperson.jsp</result> </action> </package> </struts>
2.编写action
PersonAction.java
package cn.itcast.web; import java.util.List; import javax.annotation.Resource; import cn.itcast.bean.Person; import cn.itcast.service.PersonService; public class PersonAction { @Resource PersonService personService; private String message; private List<Person> persons; private Person person; private String name; public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } /** * 人员列表显示 */ public String list(){ //this.persons = personService.getPersons(); this.persons=personService.getPersons(); return "list"; } /** * 人员添加界面 */ public String addUI(){ return "add"; } /** * 人员添加 */ public String add(){ this.personService.save(this.person); this.message="添加成功"; return "message"; } public List<Person> getPersons() { return persons; } public void setPersons(List<Person> persons) { this.persons = persons; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
3.测试页面
hello.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> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"> --> </head> <body> <form action="<%=request.getContextPath()%>/person/action_list.do" method="post"> 用户名<input type="text" name="name"> <input type="submit" value="提交"> </form> </body> </html>
personlist.jsp显示页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>人员列表</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"> --> </head> <body> <s:iterator value="persons"> id=<s:property value="id"/>,name=<s:property value="name"/><br> </s:iterator> ${name} </body> </html>