欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年07月04日 10:07:29   作者:kent鵬  
這篇文章主要介紹了詳解JAVAEE——SSH三大框架整合(spring+struts2+hibernate),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

一、整合原理

二、導(dǎo)包(41個(gè))

1.hibernate

(1)hibernate/lib/required

  

(2)hibernate/lib/jpa | java persist api java的持久化規(guī)范(接口)

  

(3)數(shù)據(jù)庫驅(qū)動(dòng)

  

2.struts2

(1)struts-blank.war/WEB-INF/lib/*

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

  

(2)struts整合spring插件包

注意:這個(gè)包一旦導(dǎo)入,那么struts2在啟動(dòng)時(shí)就會(huì)尋找spring容器.找不到將會(huì)拋出異常

  

3.spring

(1)基本:4+2

core | beans | context | expression | logging | log4j

(2)整合web:web包

spring-web

(3)整合aop:4個(gè)

spring-aop | spring-aspect | aop聯(lián)盟 | aopweaving

(4)整合Hibernate和事務(wù):4個(gè)

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

(5)整合junit4測試:test包

spring-test

4.標(biāo)簽庫

standard.jar | jstl-1.2.jar

三、單獨(dú)配置spring容器

1.創(chuàng)建applicationContext.xml,并導(dǎo)入約束(4個(gè)) beans | context | aop | tx

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" 
    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-4.2.xsd 
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd 
              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

  <bean name="userAction" class="cn.xyp.web.action.UserAction"></bean>

</beans>

2.配置spring隨項(xiàng)目啟動(dòng)(web.xml)

 <!-- 讓spring隨web啟動(dòng)而創(chuàng)建的監(jiān)聽器 -->
 <listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <!-- 配置spring配置文件位置參數(shù) -->
 <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:applicationContext.xml</param-value>
 </context-param>

四、單獨(dú)配置struts2

1.配置struts2主配置文件(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="crm" namespace="/" extends="struts-default">
    <action name="UserAction_*" class="cn.xyp.web.action.UserAction" method="{1}">
      <result name="success">/success.jsp</result>
    </action>
  </package>
</struts>

2.配置struts2核心過濾器到web.xml

 <!-- struts2核心過濾器 -->
 <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與spring整合

1.導(dǎo)包(已經(jīng)導(dǎo)入)

struts2-spring-plugin-2.3.24.jar

2.配置常量

查看默認(rèn)配置文件從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

  <!-- # struts.objectFactory = spring  將action的創(chuàng)建交給spring容器  
      struts.objectFactory.spring.autoWire = name spring負(fù)責(zé)裝配Action依賴屬性
      -->
  <constant name="struts.objectFactory" value="spring"></constant>

3.整合方案1:struts2自己創(chuàng)建action,spring負(fù)責(zé)組裝依賴屬性(了解)

<!-- 整合方案1:class屬性上仍然配置action的完整類名
        struts2仍然創(chuàng)建action,由spring負(fù)責(zé)組裝Action中的依賴屬性
     -->
    <action name="UserAction_*" class="cn.xyp.web.action.UserAction" method="{1}" >
      <result name="toHome" type="redirect" >/index.htm</result>
      <result name="error" >/login.jsp</result>
    </action>

不推薦理由:最好由spring完整管理action的生命周期.spring中功能才應(yīng)用到Action上.

4.整合方案2:spring負(fù)責(zé)創(chuàng)建action以及組裝.(推薦)

applicationContext.xml:

  <!-- action -->
  <!-- 注意:Action對象作用范圍一定是多例的.這樣才符合struts2架構(gòu) -->
  <bean name="userAction" class="cn.itcast.web.action.UserAction" scope="prototype" >
    <property name="userService" ref="userService" ></property>
  </bean>

struts.xml:

    <!-- 
       整合方案2:class屬性上填寫spring中action對象的BeanName
         完全由spring管理action生命周期,包括Action的創(chuàng)建
         注意:需要手動(dòng)組裝依賴屬性
     -->
    <action name="UserAction_*" class="userAction" method="{1}" >
      <result name="toHome" type="redirect" >/index.htm</result>
      <result name="error" >/login.jsp</result>
    </action>

六、單獨(dú)配置hibernate

1.導(dǎo)入實(shí)體類&orm元數(shù)據(jù)

  

舉例:User.java

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:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.xyp.domain" >
  <class name="User" table="sys_user" >
    <id name="user_id" >
      <generator class="native"></generator>
    </id>
    <property name="user_code" ></property>
    <property name="user_name" ></property>
    <property name="user_password" ></property>
    <property name="user_state" ></property>
  
  </class>
</hibernate-mapping>

2.配置主配置文件(hibernate.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
  
     <!-- 數(shù)據(jù)庫驅(qū)動(dòng) -->
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
     <!-- 數(shù)據(jù)庫url -->
    <property name="hibernate.connection.url">jdbc:mysql:///crm_32</property>
     <!-- 數(shù)據(jù)庫連接用戶名 -->
    <property name="hibernate.connection.username">root</property>
     <!-- 數(shù)據(jù)庫連接密碼 -->
    <property name="hibernate.connection.password">1234</property>
    <!-- 數(shù)據(jù)庫方言
      注意: MYSQL在選擇方言時(shí),請選擇最短的方言.
     -->
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    
    
    <!-- 將hibernate生成的sql語句打印到控制臺(tái) -->
    <property name="hibernate.show_sql">true</property>
    <!-- 將hibernate生成的sql語句格式化(語法縮進(jìn)) -->
    <property name="hibernate.format_sql">true</property>
    <!-- 
    自動(dòng)導(dǎo)出表結(jié)構(gòu). 自動(dòng)建表
     -->
    <property name="hibernate.hbm2ddl.auto">update</property>
     
     <!-- 引入實(shí)體配置文件 -->
    <mapping resource="cn/xyp/domain/Customer.hbm.xml" />
    <mapping resource="cn/xypt/domain/LinkMan.hbm.xml" />
    <mapping resource="cn/xyp/domain/User.hbm.xml" />
    
  </session-factory>
</hibernate-configuration>

七、spring整合hibernate

1.整合原理

將sessionFactory對象交給spring容器管理

2.在spring中配置sessionFactory

(1)配置方案一:(了解) 

<!-- 加載配置方案1:仍然使用外部的hibernate.cfg.xml配置信息 -->
  <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
    <property name="configLocation" value="classpath:hibernate.cfg.xml" ></property>
  </bean> 

(2)配置方案二:(推薦)

  <!-- 加載配置方案2:在spring配置中放置hibernate配置信息 -->
  <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
    <!-- 將連接池注入到sessionFactory, hibernate會(huì)通過連接池獲得連接 -->
    <property name="dataSource" ref="dataSource" ></property>
    <!-- 配置hibernate基本信息 -->
    <property name="hibernateProperties">
      <props>
        <!-- 必選配置 -->
        <prop key="hibernate.connection.driver_class" >com.mysql.jdbc.Driver</prop>
        <prop key="hibernate.connection.url" >jdbc:mysql:///crm_32</prop>
        <prop key="hibernate.connection.username" >root</prop>
        <prop key="hibernate.connection.password" >1234</prop> 
        <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop>
        
        <!-- 可選配置 -->
        <prop key="hibernate.show_sql" >true</prop>
        <prop key="hibernate.format_sql" >true</prop>
        <prop key="hibernate.hbm2ddl.auto" >update</prop>
      </props>
    </property>
    <!-- 引入orm元數(shù)據(jù),指定orm元數(shù)據(jù)所在的包路徑,spring會(huì)自動(dòng)讀取包中的所有配置 -->
    <property name="mappingDirectoryLocations" value="classpath:cn/itcast/domain" ></property>
  </bean>

八、spring整合c3p0連接池

1.配置db.properties

jdbc.jdbcUrl=jdbc:mysql:///xyp_crm
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=123456

2.引入連接池到spring中

  <!-- 讀取db.properties文件 -->
  <context:property-placeholder location="classpath:db.properties" />
  <!-- 配置c3p0連接池 -->
  <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
  </bean>

3.將連接池注入給SessionFactory

  <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
    <!-- 將連接池注入到sessionFactory, hibernate會(huì)通過連接池獲得連接 -->
    <property name="dataSource" ref="dataSource" ></property>

九、spring整合hibernate環(huán)境操作數(shù)據(jù)庫

1.Dao類創(chuàng)建:繼承HibernateDaoSupport

注意:項(xiàng)目中要確保使用統(tǒng)一版本。

//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<User>() {
      @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<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc);
      
    if(list != null && list.size()>0){
      return list.get(0);
    }else{
      return null;
    }

3.spring中配置dao

  <!-- Dao -->
  <bean name="userDao" class="cn.xyp.dao.impl.UserDaoImpl" >
    <!-- 注入sessionFactory -->
    <property name="sessionFactory" ref="sessionFactory"></property>
  </bean>

十、spring的aop事務(wù)

1.準(zhǔn)備工作

  <!-- 核心事務(wù)管理器 -->
  <bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" >
    <property name="sessionFactory" ref="sessionFactory" ></property>
  </bean>

2.xml配置aop事務(wù)

(1)配置通知

  <!-- 配置通知 -->
  <tx:advice id="txAdvice" transaction-manager="transactionManager" >
    <tx:attributes>
      <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
      <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
      <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
      <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
      <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
      <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
      <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
      <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
    </tx:attributes>
  </tx:advice>

(2)配置織入

  <!-- 配置將通知織入目標(biāo)對象
  配置切點(diǎn)
  配置切面 -->
  <aop:config>
    <aop:pointcut expression="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))" id="txPc"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
  </aop:config>

3.注解配置aop事務(wù)

(1)開啟注解事務(wù)

  <!-- 開啟注解事務(wù) -->
  <tx:annotation-driven transaction-manager="transactionManager" />

(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);
  }

十一、擴(kuò)大session作用范圍

1.配置filter

為了避免使用懶加載時(shí)出現(xiàn)no-session問題.需要擴(kuò)大session的作用范圍。

 <!-- 擴(kuò)大session作用范圍
   注意: 任何filter一定要在struts的filter之前調(diào)用
   因?yàn)閟truts是不會(huì)放行的
  -->
  <filter>
   <filter-name>openSessionInView</filter-name>
   <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
 </filter>

 <filter-mapping>
   <filter-name>openSessionInView</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>

十二、練習(xí):用戶登錄

1.struts.xml核心配置

<struts>
  <!-- # struts.objectFactory = spring  將action的創(chuàng)建交給spring容器  
      struts.objectFactory.spring.autoWire = name spring負(fù)責(zé)裝配Action依賴屬性
      -->
  <constant name="struts.objectFactory" value="spring"></constant>

  <package name="crm" namespace="/" extends="struts-default" >
    <global-exception-mappings>
      <exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
    </global-exception-mappings>

     <!-- 
       整合方案:class屬性上填寫spring中action對象的BeanName
         完全由spring管理action生命周期,包括Action的創(chuàng)建
         注意:需要手動(dòng)組裝依賴屬性
     -->
    <action name="UserAction_*" class="userAction" method="{1}" >
      <result name="toHome" type="redirect" >/index.htm</result>
      <result name="error" >/login.jsp</result>
    </action>
  </package>
</struts>

2.Action代碼

public class UserAction extends ActionSupport implements ModelDriven<User> {
  private User user = new User();
  
  private UserService userService ;
  
  public void setUserService(UserService userService) {
    this.userService = userService;
  }

  public String login() throws Exception {
      //1 調(diào)用Service執(zhí)行登陸邏輯
      User u = userService.getUserByCodePassword(user);
      //2 將返回的User對象放入session域
      ActionContext.getContext().getSession().put("user", u);
      //3 重定向到項(xiàng)目首頁
    return "toHome";
  }

  @Override
  public User getModel() {
    return user;
  }

}

2.Service核心代碼

  public User getUserByCodePassword(User u) {
    // 1 根據(jù)登陸名稱查詢登陸用戶
    User existU = ud.getByUserCode(u.getUser_code());
    // 2 判斷用戶是否存在.不存在=>拋出異常,提示用戶名不存在
    if (existU == null) {
      throw new RuntimeException("用戶名不存在!");
    }
    // 3 判斷用戶密碼是否正確=>不正確=>拋出異常,提示密碼錯(cuò)誤
    if (!existU.getUser_password().equals(u.getUser_password())) {
      throw new RuntimeException("密碼錯(cuò)誤!");
    }
    // 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<User> list = (List<User>) getHibernateTemplate().findByCriteria(dc);
    
    if(list != null && list.size()>0){
      return list.get(0);
    }else{
      return null;
    }
    
  }

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java8中使用一行代碼讀取文件

    Java8中使用一行代碼讀取文件

    這篇文章主要介紹了Java8中使用一行代碼讀取文件,要注意,本文介紹的方法不適合讀取很大的文件,因?yàn)榭赡艽嬖趦?nèi)存空間不足的問題,需要的朋友可以參考下
    2015-03-03
  • java針對于時(shí)間轉(zhuǎn)換的DateUtils工具類

    java針對于時(shí)間轉(zhuǎn)換的DateUtils工具類

    這篇文章主要為大家詳細(xì)介紹了java針對于時(shí)間轉(zhuǎn)換的DateUtils工具類,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • springboot+redis+阿里云短信實(shí)現(xiàn)手機(jī)號登錄功能

    springboot+redis+阿里云短信實(shí)現(xiàn)手機(jī)號登錄功能

    這篇文章主要介紹了springboot+redis+阿里云短信實(shí)現(xiàn)手機(jī)號登錄功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2024-01-01
  • Spring Boot 定制URL匹配規(guī)則的方法

    Spring Boot 定制URL匹配規(guī)則的方法

    本篇文章主要介紹了Spring Boot 定制URL匹配規(guī)則的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-02-02
  • java中如何使用HttpClient調(diào)用接口

    java中如何使用HttpClient調(diào)用接口

    這篇文章主要介紹了java中如何使用HttpClient調(diào)用接口,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • 詳解java中命令行模式的實(shí)現(xiàn)

    詳解java中命令行模式的實(shí)現(xiàn)

    命令模式是一種行為設(shè)計(jì)模式,它允許您將請求封裝為對象,以便您可以將其參數(shù)化、隊(duì)列化、記錄和撤銷,本文主要為大家介紹一下java實(shí)現(xiàn)命令模式的示例代碼,需要的可以參考下
    2023-09-09
  • Java詳細(xì)分析LCN框架分布式事務(wù)

    Java詳細(xì)分析LCN框架分布式事務(wù)

    這篇文章主要介紹了Java LCN框架分布式事務(wù),分布式事務(wù)是指事務(wù)的參與者、支持事務(wù)的服務(wù)器、資源服務(wù)器以及事務(wù)管理器分別位于不同的分布式系統(tǒng)的不同節(jié)點(diǎn)之上
    2022-07-07
  • java中maven下載和安裝步驟說明

    java中maven下載和安裝步驟說明

    在本篇文章里小編給大家分享的是一篇關(guān)于java中maven下載和安裝步驟說明內(nèi)容,對此有興趣的朋友們可以學(xué)習(xí)參考下。
    2021-02-02
  • 詳解SpringMVC中的@RequestMapping注解

    詳解SpringMVC中的@RequestMapping注解

    這篇文章主要介紹了SpringMVC中@RequestMapping注解,@RequestMapping注解是一個(gè)用來處理請求地址映射的注解,可用于映射一個(gè)請求或一個(gè)方法,可以用在類或方法上,需要的朋友可以參考下
    2023-07-07
  • request如何獲取完整url(包括域名、端口、參數(shù))

    request如何獲取完整url(包括域名、端口、參數(shù))

    這篇文章主要介紹了request如何獲取完整url(包括域名、端口、參數(shù))問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12

最新評論