您的位置:首页 > 编程语言 > Java开发

Struts2 + Spring + hibernate 框架搭成实例

2016-12-01 00:00 309 查看
1、准备Jar包:

struts
2
、hibernate、spring所需jar包

struts-core
-2
.x.x.jar----struts核心包

xwork-core
-2
.x.x.jar

ognl
-2.6
.x.jar----对象导航语言

freemarker
-2.3
.x.jar------struts
2
的ui标签的模板使用

commons-fileupload
-1.2
.x.jar----文件上传组件
2.1
.
6
版本后需加入此文件

struts-spring-plugin
-2
.x.x.jar---用于struts
2
继承spring的插件

hibernate核心安装包下的(下载路径:http://www.hibernate.org/,点击HibernateCore右边的download)

hibernate
2
.jar

lib\bytecode\hibernate-cglib-repack
-2.1
_
3
.jar

lib\required\*.jar

hibernate安装包下的(下载路径:http://www.hibernate.org/;点击HibernateAnnotations右边的下载)

hibernate-annotations.jar

lib\ejb
3
-persistence.jar、hibernate-commons-annotations.jar

hibernate针对JPA的实现包(下载路径:http://www.hibernate.org/,点击HibernateEntitymanager右边下载)


hibernate-entitymanager.jar

lib\test\log
4
j.jar、slf
4
j-log
4
j
12
.jar

spring安装包下的

dist\spring.jar

lib\c
3
p
0
\c
3
p
0
-0.9
.
1.2
.jar

lib\aspecti\aspectjweaver.jar

aspectjrt.jar

lib\colib\cglib-nodep
-2.1
_
3
.jar

lib\j
2
ee\common-annotations.jar

vlib\log
4
j\log
4
j
-1.2
.
15
.jar

lib\jakarta-commons\commons_loggin.jar

数据库驱动包
mysql-connector-java-bin.jar

2、配置beans.xml

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.1.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<!--1.配置Spring管理-->
<!--将bean交由spring管理可以用<bean></bean>和扫描加注-->
<!--在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component
@Controller@Service等这些注解的类,则把这些类注册为bean注意:如果配置了<context:component-scan>那么<context:annotation-config/>
标签就可以不用再xml中配置了,因为前者包含了后者。另外<context:annotation-config/>还提供了两个子标签-->
<!--扫描该包及该包下的子包-->
<context:component-scanbase-package="cn.pp"/>

<!--2.配置数据库连接-->
<!--集成hibernatesessionFactory单例模式线程安全创建耗内存-->
<!--数据库的连接池在xml中配置和数据库相关联,并用c3p0来配置数据库连接池-->
<beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<propertyname="driverClass"value="com.mysql.jdbc.Driver"/>
<propertyname="jdbcUrl"
value="jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8"/>
<propertyname="user"value="root"/>
<propertyname="password"value=""/>
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default:3-->
<propertyname="initialPoolSize"value="1"/>
<!--连接池中保留的最小连接数。-->
<propertyname="minPoolSize"value="1"/>
<!--连接池中保留的最大连接数。Default:15-->
<propertyname="maxPoolSize"value="300"/>
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default:0-->
<propertyname="maxIdleTime"value="60"/>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default:3-->
<propertyname="acquireIncrement"value="5"/>
<!--每60秒检查所有连接池中的空闲连接。Default:0-->
<propertyname="idleConnectionTestPeriod"value="60"/>
</bean>

<!--3.配置SessionFactory-->
<beanid="sessionFactory"name="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"/>
<!--放置hibernate的配置文件-->
<propertyname="mappingResources">
<list>
<value>cn/pp/bean/Employee.hbm.xml</value>
</list>
</property>
<propertyname="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
</value>
</property>
</bean>

<!--4.配置事务-->
<!--hibernate事务管理器配置-->
<beanid="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
<!--spring可以用xml和注解来配置事务声明-->
<tx:annotation-driventransaction-manager="transactionManager"/>
</beans>

3、Spring实例

importjava.util.List;

importcn.pp.params.Employee;

publicinterfaceEmployeeIService{
publicbooleansave(Employeeemployee);
publicbooleanupdate(Employeeemployee);
publicEmployeefind(StringuserId);
publicbooleandelete(String...userIds);
publicList<Employee>findAll();
}

importjava.util.List;
importjavax.annotation.Resource;
importorg.apache.log4j.Logger;
importorg.hibernate.Criteria;
importorg.hibernate.SessionFactory;
importorg.springframework.stereotype.Service;
importorg.springframework.transaction.annotation.Transactional;
importcn.pp.params.Employee;
importcn.pp.service.EmployeeIService;

@Service
@Transactional
publicclassEmployeeServiceImplimplementsEmployeeIService{
privatestaticLoggerlogger=Logger.getLogger(Employee.class);
@Resource(name="sessionFactory")
SessionFactoryfactory;

@Override
publicbooleansave(Employeeemployee){
try{
factory.getCurrentSession().save(employee);
}catch(Exceptione){
logger.error(e.getMessage());
returnfalse;
}
returntrue;
}

@Override
publicbooleanupdate(Employeeemployee){
try{
factory.getCurrentSession().update(employee);
}catch(Exceptione){
logger.error(e.getMessage());
returnfalse;
}
returntrue;
}

//@Transactional(propagation=Propagation.NOT_SUPPORTED)
@Override
publicEmployeefind(StringuserId){
try{
return(Employee)factory.getCurrentSession().get(Employee.class,userId);
}catch(Exceptione){
logger.error(e.getMessage());
}
returnnull;
}

@Override
publicbooleandelete(String...userIds){
try{
for(StringuserId:userIds){
Employeeemployee=(Employee)factory.getCurrentSession().load(Employee.class,userId);
factory.getCurrentSession().delete(employee);
}
}catch(Exceptione){
logger.error(e.getMessage());
returnfalse;
}
returntrue;
}

@SuppressWarnings("unchecked")
//@Transactional(propagation=Propagation.NOT_SUPPORTED)
@Override
publicList<Employee>findAll(){
try{
//returnfactory.getCurrentSession().createQuery("fromEmployee").list();
Criteriacriteria=factory.getCurrentSession().createCriteria(Employee.class);
returncriteria.list();
}catch(Exceptione){
logger.error(e.getMessage());
}
returnnull;
}

}

数据库表映射文件

<?xmlversion="1.0"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="cn.pp.params.Employee"table="EMPLOYEE"lazy="true">
<idname="userId"column="USER_ID"type="java.lang.String">
<generatorclass="uuid"/>
</id>
<propertyname="userName"column="USER_NAME"type="java.lang.String"/>
<propertyname="address"column="ADDRESS"type="java.lang.String"/>
<propertyname="birthday"column="BIRTHDAY"type="java.util.Date"/>
</class>
</hibernate-mapping>

测试用例:

importjava.util.Calendar;
importjava.util.Date;
importjava.util.GregorianCalendar;
importjava.util.List;
importorg.junit.BeforeClass;
importorg.junit.Test;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importcn.pp.params.Employee;
importcn.pp.service.EmployeeIService;

publicclassEmployeeIServiceTest{

privatestaticEmployeeIServiceemployeeIService;

@BeforeClass
publicstaticvoidinitContext(){
ApplicationContextcontext=newClassPathXmlApplicationContext("beans.xml");
employeeIService=(EmployeeIService)context.getBean("employeeServiceImpl");
}

@Test
publicvoidtestSave(){
Employeee=newEmployee();
e.setUserName("杰克");
e.setAddress("北京");
Calendarc=newGregorianCalendar(1991,5,5,0,0,0);
Datedate=c.getTime();
e.setBirthday(date);
employeeIService.save(e);
}

@Test
publicvoidtestUpdate(){
Employeee=employeeIService.find("4028826a507f660001507f6601620000");
e.setUserName("螺丝");
employeeIService.update(e);
}

@Test
publicvoidtestFind(){
Employeee=employeeIService.find("4028826a507f660001507f6601620000");
System.out.println(e.getUserName());
}

@Test
publicvoidtestDelete(){
employeeIService.delete("4028826a507f660001507f6601620000");
}

@Test
publicvoidtestFindAll(){
List<Employee>list=employeeIService.findAll();
for(Employeee:list){
System.out.println(e.getUserName());
employeeIService.delete(e.getUserId());
}
}
}

4、Struts配置:

<struts>
<!--指定默认编码集,作用于HttpServletRequest的setCharacterEncoding方法和freemarkervelocity的输出-->
<constantname="struts.118n.encoding"value="UTF-8"></constant>
<!--该属性用于指定Struts2请求处理的后缀,默认为.action可以处理所有后缀是.action的处理,如果
需要指定多个请求处理后缀,后缀之间用逗号隔开-->
<constantname="struts.action.extension"value="do,action"></constant>
<!--将struts的action交由spring管理不在由struts的工厂介入-->
<constantname="struts.objectFactory"value="spring"/>

<packagename="employeePackage"namespace="/pg"extends="struts-default">
<actionname="employee_*"class="cn.actions.EmployeeAction"method="{1}">
<resultname="message">/WEB-INF/message.jsp</result>
<resultname="list">/WEB-INF/list.jsp</result>
</action>
</package>
</struts>

测试实例:

action:

//spring默认scope是单例模式@Scope("prototype")表示每次接收一个请求创建一个Action对象
@Controller@Scope("prototype")
publicclassEmployeeAction{
@ResourceEmployeeIServiceemployeeIService;
privateStringmessage;
privateHttpServletRequestrequest;
privateServletContextcontext;
privateEmployeeemployee;

publicEmployeeAction(){
request=ServletActionContext.getRequest();
context=ServletActionContext.getServletContext();
}
publicStringlist(){
List<Employee>list=employeeIService.findAll();
request.setAttribute("list",list);
return"list";
}
publicStringadd(){
if(employee!=null){
employeeIService.save(employee);
}else{
setMessage("部分人员信息为空!");
return"message";
}
setMessage("添加成功");
return"message";
}
publicStringgetMessage(){
returnmessage;
}
publicvoidsetMessage(Stringmessage){
this.message=message;
}
publicEmployeegetEmployee(){
returnemployee;
}
publicvoidsetEmployee(Employeeemployee){
this.employee=employee;
}
}

packagecn.pp.params;

importjava.util.Date;

publicclassEmployee{
privateStringuserId;
privateStringuserName;
privateStringaddress;
privateDatebirthday;
publicStringgetUserId(){
returnuserId;
}
publicvoidsetUserId(StringuserId){
this.userId=userId;
}
publicStringgetUserName(){
returnuserName;
}
publicvoidsetUserName(StringuserName){
this.userName=userName;
}
publicStringgetAddress(){
returnaddress;
}
publicvoidsetAddress(Stringaddress){
this.address=address;
}
publicDategetBirthday(){
returnbirthday;
}
publicvoidsetBirthday(Datebirthday){
this.birthday=birthday;
}

}

list.jsp:

<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>人员列表</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
</head>

<body>
<div><ahref="/SSH/index.jsp">添加人员</a></div>
<hr/>
<div>
<c:iftest="${list.size()>0}">
<table>
<thead>
<tr>
<td>用户名</td>
<td>住址</td>
<td>生日</td>
</tr>
</thead>
<tbody>
<c:forEachitems="${list}"var="item">
<tr>
<td>${item.userName}</td>
<td>${item.address}</td>
<td>${item.birthday}</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
<c:iftest="${list.size()==0}">
<span>暂无数据</span>
</c:if>
</div>
</body>
</html>

add.jsp:

<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>添加人员</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
</head>

<body>
<div><ahref="/SSH/pg/employee_list.do">列表</a></div>
<hr/>
<div>
<formaction="/SSH/pg/employee_add.do"method="post">
<table>
<tr>
<td>用户名</td>
<td><inputtype="text"name="employee.userName"/></td>
</tr>
<tr>
<td>住址</td>
<td><inputtype="text"name="employee.address"/></td>
</tr>
<tr>
<td>生日</td>
<td><inputtype="text"name="employee.birthday"/></td>
</tr>
<tr>
<tdcolspan="2"align="center">
<inputtype="submit"value="提交"/>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>

message.jsp:

<body>

<div>
${message}
</div>
<hr/>
<div>
<ahref="/SSH/pg/employee_list.do">返回列表</a>
<ahref="/SSH/index.jsp">添加人员</a>
</div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: