華文網

JAVAEE——SSH三大框架整合(spring+struts2+hibernate)

一、整合原理

二、導包(41個) 1.hibernate (1)hibernate/lib/required

(2)hibernate/lib/jpa | java persist api java的持久化規範(介面) (3)資料庫驅動 2.struts2 (1)struts-blank.war/WEB-INF/lib/*

注意:javassist-3.18.1-GA.jar包與hibernate中的重複(只保留高版本即可)

(2)struts整合spring外掛程式包

注意:這個包一旦導入,那麼struts2在啟動時就會尋找spring容器.找不到將會拋出異常

3.spring (1)基本:4+2

core | beans | context | expression | logging | log4j

(2)整合web:web包

spring-web

(3)整合aop:4個

spring-aop | spring-aspect | aop聯盟 | aopweaving

(4)整合Hibernate和事務:4個

spring-jdbc | spring-tx | c3p0 | spring-orm

(5)整合junit4測試:test包

spring-test

4.標籤庫

standard.jar | jstl-1.2.jar

三、單獨配置spring容器 1.創建applicationContext.xml,並導入約束(4個) beans | context | aop | tx

2.配置spring隨專案啟動(web.xml) org.springframework.web.context.ContextLoaderListener contextConfigLocation classpath:applicationContext.xml

四、單獨配置struts2 1.配置struts2主設定檔(struts.xml) /success.jsp

2.配置struts2核心篩檢程式到web.xml struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /*

五、struts2與spring整合 1.導包(已經導入)

struts2-spring-plugin-2.3.24.jar

2.配置常量

查看預設設定檔從31行開始找到要配置的變數。

### if specified, the default object factory can be overridden here ### Note: short-hand notation is supported in some cases, such as "spring" ### Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here # struts.objectFactory = spring ### specifies the autoWiring logic when using the SpringObjectFactory. ### valid values are: name, type, auto, and constructor (name is the default) struts.objectFactory.spring.autoWire = name

添加常量到struts.xml

3.整合方案1:struts2自己創建action,spring負責組裝依賴屬性(瞭解) /index.htm /login.jsp

不推薦理由:最好由spring完整管理action的生命週期.spring中功能才應用到Action上.

4.整合方案2:spring負責創建action以及組裝.(推薦)

applicationContext.xml:

struts.xml:

/index.htm /login.jsp

六、單獨配置hibernate 1.導入實體類&orm中繼資料package cn.xyp.web.domain; import java.util.HashSet; import java.util.Set; public class User { private Long user_id; private String user_code; private String user_name; private String user_password; private Character user_state; public Long getUser_id { return user_id; } public void setUser_id(Long user_id) { this.user_id = user_id; } public String getUser_code { return user_code; } public void setUser_code(String user_code) { this.user_code = user_code; } public String getUser_name { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getUser_password { return user_password; } public void setUser_password(String user_password) { this.user_password = user_password; } public Character getUser_state { return user_state; } public void setUser_state(Character user_state) { this.user_state = user_state; } @Override public String toString { return "User [user_id=" + user_id + ", user_code=" + user_code + ", user_name=" + user_name + ", user_password=" + user_password + "]"; } }

User.hbm.xml:

2.配置主設定檔(hibernate.xml) com.mysql.jdbc.Driver jdbc:mysql:///crm_32 root 1234 org.hibernate.dialect.MySQLDialect true true update

七、spring整合hibernate 1.整合原理

將sessionFactory物件交給spring容器管理

2.在spring中配置sessionFactory (1)配置方案一:(瞭解)

(2)配置方案二:(推薦) com.mysql.jdbc.Driver jdbc:mysql:///crm_32 root 1234 org.hibernate.dialect.MySQLDialect true true update

八、spring整合c3p0連接池 1.配置db.propertiesjdbc.jdbcUrl=jdbc:mysql:///xyp_crm jdbc.driverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=123456

2.引入連接池到spring中

3.將連接池注入給SessionFactory

九、spring整合hibernate環境操作資料庫 1.Dao類創建:繼承HibernateDaoSupport

注意:專案中要確保使用統一版本。

//HibernateDaoSupport 為dao注入sessionFactory public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

2.hibernate範本的操作 (1)execute @Override public User getByUserCode(final String usercode) { //HQL return getHibernateTemplate.execute(new HibernateCallback { @Override public User doInHibernate(Session session) throws HibernateException { String hql = "from User where user_code = ? "; Query query = session.createQuery(hql); query.setParameter(0, usercode); User user = (User) query.uniqueResult; return user; } });

(2)findByCriteria //Criteria DetachedCriteria dc = DetachedCriteria.forClass(User.class); dc.add(Restrictions.eq("user_code", usercode)); List list = (List) getHibernateTemplate.findByCriteria(dc); if(list != null && list.size>0){ return list.get(0); }else{ return null; }

3.spring中配置dao

十、spring的aop事務 1.準備工作

2.xml配置aop事務 (1)配置通知

(2)配置織入

3.注解配置aop事務 (1)開啟注解事務

(2)Service類中使用注解@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true) public class UserServiceImpl implements UserService{ @Override @Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false) public void saveUser(User u) { ud.save(u); }

十一、擴大session作用範圍 1.配置filter

為了避免使用懶載入時出現no-session問題.需要擴大session的作用範圍。

openSessionInView org.springframework.orm.hibernate5.support.OpenSessionInViewFilter openSessionInView /*

十二、練習:用戶登錄 1.struts.xml核心配置 /index.htm /login.jsp

2.Action代碼public class UserAction extends ActionSupport implements ModelDriven { private User user = new User; private UserService userService ; public void setUserService(UserService userService) { this.userService = userService; } public String login throws Exception { //1 調用Service執行登陸邏輯 User u = userService.getUserByCodePassword(user); //2 將返回的User對象放入session域 ActionContext.getContext.getSession.put("user", u); //3 重定向到項目首頁 return "toHome"; } @Override public User getModel { return user; } }

2.Service核心代碼 public User getUserByCodePassword(User u) { // 1 根據登陸名稱查詢登陸使用者 User existU = ud.getByUserCode(u.getUser_code); // 2 判斷用戶是否存在.不存在=>拋出異常,提示用戶名不存在 if (existU == null) { throw new RuntimeException("用戶名不存在!"); } // 3 判斷使用者密碼是否正確=>不正確=>拋出異常,提示密碼錯誤 if (!existU.getUser_password.equals(u.getUser_password)) { throw new RuntimeException("密碼錯誤!"); } // 4 返回查詢到的使用者物件 return existU; }

3.Dao核心代碼 public User getByUserCode(final String usercode) { //Criteria DetachedCriteria dc = DetachedCriteria.forClass(User.class); dc.add(Restrictions.eq("user_code", usercode)); List list = (List) getHibernateTemplate.findByCriteria(dc); if(list != null && list.size>0){ return list.get(0); }else{ return null; } }