本文代码是传智播客黎活明老师所讲的《Spring2.5视频教程》各种示例的综合,在此把所有框架升级到最新版本整合一下。
所用jar包:
Struts:
struts-2.1.8.1
\lib下除了各种plugin(保留struts2-spring-plugin-2.1.8.1.jar)的所有文件
Spring:
spring-framework-3.0.0.RELEASE
\dist下的所有文件
Hibernate:
hibernate-distribution-3.3.2.GA下的hibernate3.jar
\lib\bytecode\cglib下的cglib-2.2.jar
\lib\optional\ehcache下的ehcache-1.2.3.jar
\lib\required下的所有文件
hibernate-annotations-3.4.0.GA下的hibernate-annotations.jar
\lib下的ejb3-persistence.jar,hibernate-commons-annotations.jar
hibernate-entitymanager-3.4.0.GA下的hibernate-entitymanager.jar
\lib\test下的log4j.jar,slf4j-log4j12.jar
MySQL:mysql-connector-java-5.1.10-bin.jar
JUnit:4
JDK:jdk-6u14-windows-i586.exe
Tomcat:apache-tomcat-6.0.18.zip
项目名:test
Person.java
package com.test.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Person implements Serializable {
private Integer id;
private String name;
public Person(){}
public Person(String name){
this.name = name;
}
@Id @GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length=10,nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Person other = (Person) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
PersonService.java
package com.test.service;
import java.util.List;
import com.test.bean.Person;
public interface PersonService {
public void save(Person person);
public void update(Person person);
public void delete(Integer personid);
public Person getPerson(Integer personid);
@SuppressWarnings("unchecked")
public List<Person> getPersons();
}
PersonServiceBean.java
package com.test.service.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.exception.SQLGrammarException;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.test.bean.Person;
import com.test.service.PersonService;
@Transactional
public class PersonServiceBean implements PersonService {
@PersistenceContext EntityManager em;
public void delete(Integer personid) {
em.remove(em.getReference(Person.class, personid));
}
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
public Person getPerson(Integer personid) {
return em.find(Person.class, personid);
}
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
@SuppressWarnings("unchecked")
public List<Person> getPersons() throws SQLGrammarException {
return em.createQuery("select o from Person o").getResultList();
}
public void save(Person person) {
em.persist(person);
}
public void update(Person person) {
em.merge(person);
}
}
PersonAction.java
package com.test.web.action;
import java.util.List;
import javax.annotation.Resource;
import com.test.bean.Person;
import com.test.service.PersonService;
public class PersonAction {
@Resource PersonService personService;
private String message;
private List<Person> persons;
private Person person;
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
/**
* 人员列表显示
*/
public String list(){
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;
}
}
PersonServiceTest.java
package junit.test;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.test.bean.Person;
import com.test.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());
}
}
}
META-INF\persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="test" transaction-type="RESOURCE_LOCAL"> <properties> <!-- 数据库方言--> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> <!-- 数据库驱动 --> <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/> <!-- 数据库用户名 --> <property name="hibernate.connection.username" value="root"/> <!-- 数据库密码 --> <property name="hibernate.connection.password" value="1234"/> <!-- 数据库连接URL --> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8"/> <!-- 最大抓取深度 --> <property name="hibernate.max_fetch_depth" value="3"/> <!-- 更新方式创建库表 --> <property name="hibernate.hbm2ddl.auto" value="update"/> <!-- 显示SQL --> <property name="hibernate.show_sql" value="true"/> <!-- 格式SQL --> <property name="hibernate.format_sql" value="true"/> <!-- 使用二级缓存 --> <property name="hibernate.cache.use_second_level_cache" value="true"/> <property name="hibernate.cache.use_query_cache" value="false"/> <property name="hibernate.cache.provider_class" value="org.hibernate.cache.EhCacheProvider"/> </properties> </persistence-unit> </persistence>
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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config/> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="test"/> </bean> <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <tx:annotation-driven transaction-manager="txManager"/> <bean id="personService" class="com.test.service.impl.PersonServiceBean"/> <bean id="personAction" scope="prototype" class="com.test.web.action.PersonAction" /> </beans>
src\ehcache.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- defaultCache节点为缺省的缓存策略 maxElementsInMemory 内存中最大允许存在的对象数量 eternal 设置缓存中的对象是否永远不过期 overflowToDisk 把溢出的对象存放到硬盘上 timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉 timeToLiveSeconds 指定缓存对象总的存活时间 diskPersistent 当jvm结束是是否持久化对象 diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间 --> <ehcache> <diskStore path="C:\cache"/> <defaultCache maxElementsInMemory="1000" eternal="false" overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="180" diskPersistent="false" diskExpiryThreadIntervalSeconds="60"/> <cache name="com.test.bean.Person" maxElementsInMemory="100" eternal="false" overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/> </ehcache>
src\struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.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" extends="struts-default"> <global-results> <result name="message">/page/message.jsp</result> </global-results> <action name="action_*" class="personAction" method="{1}"> <result name="list">page/personlist.jsp</result> <result name="add">page/addperson.jsp</result> </action> </package> </struts>
WebContent\page\addperson.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"> --> </head> <body> <s:form action="action_add" namespace="/person"> 名称:<s:textfield name="person.name"/> <input type="submit" value="提交"/> </s:form> </body> </html>
WebContent\page\message.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>My JSP 'message.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"> --> </head> <body> <s:property value="message"/> <br> <a href="../index.jsp">返回</a> </body> </html>
WebContent\page\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"> --> </head> <body> <s:iterator value="persons"> id=<s:property value="id"/>,name=<s:property value="name"/><br> </s:iterator> <a href="page/addperson.jsp">添加</a> </body> </html>
WebContent\WEB-INF\web.xml
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>test</display-name> <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>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>Spring OpenEntityManagerInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Struts2 Configuration Begin --> <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> <!-- Struts2 Configuration End --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
WebContent\index.jsp
<% response.sendRedirect("action_list.do"); %>