程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> SSH整合(struts2.3.24+hibernate3.6.10+spring4.3.2+mysql5.5+myeclipse8.5+tomcat6+jdk1.6),struts2hibernate

SSH整合(struts2.3.24+hibernate3.6.10+spring4.3.2+mysql5.5+myeclipse8.5+tomcat6+jdk1.6),struts2hibernate

編輯:JAVA綜合教程

SSH整合(struts2.3.24+hibernate3.6.10+spring4.3.2+mysql5.5+myeclipse8.5+tomcat6+jdk1.6),struts2hibernate


終於開始了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整合基本就是這樣的,結束!

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved