首页 > 代码库 > SSH整合(struts2.3.24+hibernate3.6.10+spring4.3.2+mysql5.5+myeclipse8.5+tomcat6+jdk1.6)
SSH整合(struts2.3.24+hibernate3.6.10+spring4.3.2+mysql5.5+myeclipse8.5+tomcat6+jdk1.6)
终于开始了ssh的整合,虽然现在比较推崇的是,ssm(springmvc+spring+mybatis)这种框架搭配确实比ssh有吸引力,因为一方面springmvc本身就是遵循spring标准,所以不用像struts那样添加jar包去管理,其次是mybatis不能算一个完全的orm框架(因为mybatis依旧写的是面向关系的sql)但是相比ssh更加灵活和优化更加容易。
貌似偏题了,重新说回ssh整合。
首先引入jar包:(这里需要新建一个web项目,如果你不知道怎么在myeclipse怎么新建一个web项目,那么你需要做的不是整合ssh,而是回去重新翻一遍java的IDE使用手册)
struts2(常规jar包):
hibernate常规jar包:
spring jar包(包括core,aop,jdbc,tx,orm,spring-struts)ps:下图里面tx类的jar包被分在了aop中,因为aop中要用到事务,所以就不单独建一个user library
mysql的jdbc的jar包:
mysql-connector-java-5.0.8-bin.jar
接着来看项目结构:
很简答的三层:dao,service,action,javabean放在entity包下面,所有的都写在配置文件里(spring管理的bean,hibernate的属性,struts2action的配置)
mysql的mybatis数据库中有两张表:
t_user
_dept
有人说干嘛起这样的名字,我只能说,我愿意你咬我啊(当然,这里肯定不是,一方面是避免和数据库中关键字重名,一方面是也可以表明这是数据库的表,免得和别的数据库中搞混)
user表里有四个字段,一个id,一个username,一个password,一个关联部门表的外键
dept中有两个字段,一个部门编号(deptNo),一个部门名称(deptName)
好了,准备条件都写好了,现在可以开始写
UserDao中三个方法,直接贴代码:
package com.mz.dao;import java.io.Serializable;import java.util.List;import org.hibernate.Query;import org.hibernate.SessionFactory;import org.hibernate.classic.Session;import com.mz.entity.User;public class UserDao { private SessionFactory sessionFactory; //保存一个user对象到数据库 public boolean save(User user) { Serializable serializable = sessionFactory.getCurrentSession().save(user); System.out.println("serializable:" + serializable); return true; } //通过id寻找到user public User getUserById(int id) { User user = (User) sessionFactory.getCurrentSession().get(User.class, id); return user; } //通过部门编号寻找到一个list的user public List<User> getUserByDept(int deptNo) { String hql = "from User user where user.dept.deptNo = ?"; Session session = this.sessionFactory.getCurrentSession(); //Criteria criteria = session.createCriteria(hql); Query query = session.createQuery(hql); query.setInteger(0, deptNo); List<User> users = query.list(); return users; } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
通过hibernate中的SessionFactory建立数据持久层。有人说为什么本来该有事务的地方现在却没有了,我只能说,你还没看完,这部份已经被spring声明式事务管理了好吧。
其次是UserService,简化之后只有一个方法:
package com.mz.service;import com.mz.dao.UserDao;import com.mz.entity.User;public class UserService { private UserDao userDao; public User getUser(int id) { User user = userDao.getUserById(id); return user; } public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } }
然后是UserAction层,依然只有一个方法(省略了一些东西没有介绍,毕竟这里很多东西是struts的,本文重点介绍的是spring整合):
package com.mz.action;import java.util.Map;import org.apache.struts2.interceptor.RequestAware;import com.mz.entity.User;import com.mz.service.UserService;import com.opensymphony.xwork2.ActionSupport;public class UserAction extends ActionSupport implements RequestAware{ private Map<String, Object> request; private UserService userService; public String execute() { int id = 2; User user = userService.getUser(id); request.put("user", user); return SUCCESS; } public Map<String, Object> getRequest() { return request; } public void setRequest(Map<String, Object> request) { this.request = request; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } }
查找id为2的user并且存储到request中,最后返内部跳转。
最后来看javabean:
User.java:
package com.mz.entity;public class User { private int id; private String username; private String password; private Dept dept; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } }
User的hibernate映射文件User.hbm.xml:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping > <class name="com.mz.entity.User" table="t_user"> <id name="id" column="id"> <generator class="native" /> </id> <property name="username" column="username" ></property> <property name="password" column="password"></property> <many-to-one name="dept" column="deptNo" class="com.mz.entity.Dept"></many-to-one> </class></hibernate-mapping>
Dept.java
package com.mz.entity;public class Dept { private int deptNo; private String deptName; public int getDeptNo() { return deptNo; } public void setDeptNo(int deptNo) { this.deptNo = deptNo; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } }
Dept的映射文件Dept.hbm.xml:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- This mapping demonstrates content-based discrimination for the table-per-hierarchy mapping strategy, using a formula discriminator. --><hibernate-mapping > <class name="com.mz.entity.Dept" table="_dept"> <id name="deptNo" column="deptNo"> <generator class="native" /> </id> <property name="deptName" column="deptName" ></property> </class></hibernate-mapping>
好了,接下来就是配置文件的事情了:
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="user" namespace="/" extends="struts-default"> <!-- 这里的userAction配置在bean.xml中,struts会自动到bean.xml中寻找对应的类 --> <action name="user" class="userAction"> <result name="success">/index.jsp</result> </action> </package></struts>
接着是bean.xml:这里需要配置的有:dao,service,dataSource(数据池),sessionFactory,sessionFactory的事务管理,事务管理器,以及拦截的aop(aop配置在service层,因为service层主要是业务处理,如果业务出现问题,事务就应该回滚,当然,具体的事务配置应该根据项目需求来定!!!!!):
<?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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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"> <!-- 配置dataSource --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" > <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatis"></property> <property name="user" value="root"></property> <property name="password" value="111111"></property> <property name="initialPoolSize" value="3"></property> <property name="maxPoolSize" value="10"></property> <property name="acquireIncrement" value="2"></property> <property name="maxStatements" value="10"></property> </bean> <!-- 配置dao --> <bean id="userDao" class="com.mz.dao.UserDao" > <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置action --> <bean id="userAction" class="com.mz.action.UserAction"> <property name="userService" ref="userService"></property> </bean> <!-- 配置service --> <bean id="userService" class="com.mz.service.UserService"> <property name="userDao" ref="userDao"></property> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <!-- 引用配置好了的数据池,需要c3p0的对应jar --> <property name="dataSource" ref="dataSource"></property> <!-- hibernate的属性配置 START: --> <property name="hibernateProperties"> <props> <prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="show_sql">true</prop> <prop key="hbm2ddl.auto">update</prop> </props> </property> <!-- hibernate的属性配置 END: --> <!-- hibernate需要做持久化的映射文件 START: --> <property name="mappingLocations"> <list> <value>classpath:com/mz/entity/*.hbm.xml</value> </list> </property> <!-- hibernate需要做持久化的映射文件 END: --> </bean> <!-- 配置sessionFactory的事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 配置事务 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="*save*" read-only="false"/> <tx:method name="*get*" read-only="true"></tx:method> </tx:attributes> </tx:advice> <!-- 配置事务aop --> <aop:config> <aop:pointcut expression="execution(* com.mz.service.*.*(..))" id="pt"></aop:pointcut> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/> </aop:config> </beans>
因为所有的属性都是配置在spring的配置文件中,所以其实不需要hibernate.cfg.xml,
最后就是在web.xml加入struts2的filter和spring的listener,代码如下:
struts2:
<!--struts2配置 START: --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- struts2配置 END: -->
spring:
<!-- spring ioc配置 START: --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:bean.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring ioc配置 END: -->
好了,部署到tomcat开始做测试:
index.jsp中加入:
用户名:${user.username }
url:http:localhost:8080/ssh/user(截图是因为加了sessionInViewFilter,请无视)
相当于我们测试成功了,可是如果我们想要看user对应的部门${user.dept.deptName}),就会报错:
这是因为hibernate的session的懒加载机制导致的,那么我们可以在web.xml中配置一个filter使得在返回客户端时session一直存在:
<!-- 配置spring的opensessioninview START:--> <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>*.action</url-pattern> </filter-mapping> <!-- 配置spring的opensessioninview END:-->
拦截所有的.action访问,再次访问,如图所示:
这次就可以显示了,当然还有其他方法,比如(lazy="false",当然这样子每次都要加载出来,这种多对一的还好,如果是1对多,每次都是默认加载出来,对系统的负担会很大,所以不推荐不推荐不推荐!!!!)
ssh整合基本就是这样的,结束!
SSH整合(struts2.3.24+hibernate3.6.10+spring4.3.2+mysql5.5+myeclipse8.5+tomcat6+jdk1.6)