整合初步--------->SSH(注解版)


上面的一篇博客已經介紹了 Spring和Hibernate之間的整合,沒看過的童鞋可以去看看,這篇博客講解Spring+Hibernate+Struts2注解版。。。。。。。。。

個人覺得使用注解可能更方便一點,就是在靈活性上不好把控,當方法特別多的時候,使用事務來進行管理時,就會消耗內存,從而造成浪費。如果使用AOP方式來進行管理,就可以指定我哪些方法進行怎樣的操作,會減少內存的消耗。

使用注解,首先你要知道你需要哪些支持(就是jar包),找不對就會出現jar包沖突的情況,我在剛開始時經常出現這種情況,這就需要你一定的基礎,熟悉各個框架之間需要連接的橋梁。今天講解的示例,使用的是以下jar包:

 

    <dependencies>
        <!--測試 jar包-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.3</version>
        </dependency>

        <!--spring jar包
          帶有一系列的jar包
          例如:core ,expression,beans,context,aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

        <!--spring web jar 包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

        <!--spring-tx jar 包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

        <!--spring-ormjar 包
          整合所需jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

        <!--spring-jdbcjar 包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

        <!--aspectJ jar 包-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--commons-dncpjar 包
          數據源
        -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!--<dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>-->

        <!--c3p0jar 包-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!--struts2-spring-plugin jar 包
          整合所需插件包
        -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.5.10</version>
        </dependency>


        <!--struts2 core 包  核心包-->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.5.10</version>
        </dependency>

        <!--使用注解action jar包-->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>2.5.10</version>
        </dependency>

        <!--hibernate jar 包-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.6.Final</version>
        </dependency>

        <!--jtajar 包-->
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>jta</artifactId>
            <version>1.1</version>
        </dependency>

        <!--mysql數據庫驅動-->
        <dependency>
            <groupId>org.wisdom-framework</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34_1</version>
        </dependency>

        <!--oraclejar 包-->
        <!--<dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.1.0</version>
        </dependency>-->

        <!--jstl jar包-->
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-spec</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.1</version>
        </dependency>

        <!--mybatis jar包-->
        <!-- <dependency>
             <groupId>org.mybatis</groupId>
             <artifactId>mybatis</artifactId>
             <version>3.4.2</version>
         </dependency>-->

        <!--servlet api包-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

在這里說明一點:有時候項目可能識別不到你編寫的xml文件和properties文件時,你就需要加上<build></build>節點里面的內容,

這樣編譯器就會編譯了,童鞋們要記住呦!

項目的整體架構:

 

使用idea的好處就是,架構特別清晰,什么層干什么活,不會出現混亂的情況,當你的架構調理不清楚時,啟動測試時就會出現各種錯誤,這里吐槽一下:idea有時候報錯不會報到具體的錯誤,這點就不好,也在於我學的不精,基礎太差,呵呵,小小的抱怨一下。

當我們所需要的jar包准備完畢后,就可以開始搭建我們的架構了。

beans類的書寫:

package cn.note.beans;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Created by accp on 2017/3/31.
 */
@Table
public class Book {
    @Id
    @GeneratedValue
    private Integer id;
    @Column
    private String name;
    @Column
    private String price;

    public Book() {
    }

    public Book(String name, String price) {
        this.name = name;
        this.price = price;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}

dao層的書寫:主要定義方法原型,編寫SQL語句,訪問數據庫,獲得數據,傳遞給biz層,進行之后的判斷

dao:

package cn.note.dao;

import cn.note.beans.Book;

import java.util.List;

/**
 * Created by accp on 2017/3/31.
 */
public interface IBookDao {
    /*查詢,用作登錄*/
    int select(Book book);
    /*查詢所有的圖書*/
    List<Book>  selectAll();
 }

dao層的實現層impl:

package cn.note.dao.impl;

import cn.note.beans.Book;
import cn.note.dao.IBookDao;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by accp on 2017/3/31.
 */
/*標識這個是dao層*/
@Repository
public class BookDaoImpl implements IBookDao {
    /*使用自動注入屬性*/
    @Autowired
    private SessionFactory sessionFactory;
    /*標識哪些方法進行事務的管理,從而進行如何的操作*/
    @Transactional
    public int select(Book book) {
        /*
        * 頁面上根據傳遞過來的數據進行裝配
        * */
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Book.class)
                .add(Restrictions.eq("name",book.getName())).add(Restrictions.eq("price", book.getPrice()));
        List<Book> list = criteria.list();
        if (list != null) {
            return 1;
        }
        return 0;
    }
    /*標識哪些方法進行事務的管理,從而進行如何的操作*/
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
    public List<Book> selectAll() {
        /*獲取全部的圖書信息*/
        return sessionFactory.getCurrentSession().createSQLQuery("SELECT  * from book").list();
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}

biz層主要是進行一些邏輯判斷時所在的層面。

biz的方法:

package cn.note.biz;

import cn.note.beans.Book;

import java.util.List;

/**
 * Created by accp on 2017/3/31.
 */
public interface IBookBiz {
    int select(Book book);

    List<Book> selectAll();
}

方法的實現類:

package cn.note.biz.impl;

import cn.note.beans.Book;
import cn.note.biz.IBookBiz;
import cn.note.dao.IBookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by accp on 2017/3/31.
 */
/*標識這是biz層*/
@Service("bookBiz")
public class BookBizImpl implements IBookBiz {
    /*自動注入屬性*/
    @Autowired
    private IBookDao dao;

    public int select(Book book) {
        
        return dao.select(book);
    }
    public List<Book> selectAll() {
        return dao.selectAll();
    }

    public IBookDao getDao() {
        return dao;
    }

    public void setDao(IBookDao dao) {
        this.dao = dao;
    }
}

當我寫到這的時候,不禁想到,這個畫面我好像似曾相識,原來這就是你寫了好多遍的情況,這些代碼已經記錄在你的手指上了,不需要你的大腦思考,你就會不知不覺的把它編寫出來,這就像是老朋友,多年未見,感情依然。。。

還是讓我們繼續吧,生活的腳步跟上。。。。。。。。

接下來就是action類的編寫,這個層主要是獲取從頁面上傳來的數據,進行判斷,之后該進行哪些操作,這個層面就會用到struts2框架的功能,Struts2是一個基於MVC設計模式的Web應用框架,它本質上相當於一個servlet,在MVC設計模式中,Struts2作為控制器(Controller)來建立模型與視圖的數據交互。Struts 2是Struts的下一代產品,是在 struts 1和WebWork的技術基礎上進行了合並的全新的Struts 2框架。其全新的Struts 2的體系結構與Struts 1的體系結構差別巨大。Struts 2以WebWork為核心,采用攔截器的機制來處理用戶的請求,這樣的設計也使得業務邏輯控制器能夠與ServletAPI完全脫離開,所以Struts 2可以理解為WebWork的更新產品。雖然從Struts 1到Struts 2有着太大的變化,但是相對於WebWork,Struts 2的變化很小。

LoginAction類的編寫:

package cn.note.action;

import cn.note.beans.Book;
import cn.note.biz.IBookBiz;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by accp on 2017/3/31.
 */
/*標識action層
* scope:管理action生成的是多例還是單例
* :prototype 和 singleton
* Namespace:命名空間
* 默認繼承哪個包
* */
@Controller
@Scope("prototype")
@Namespace("/")
@ParentPackage("struts-default")
public class LoginAction extends ActionSupport{
    /*自動注入屬性*/
    @Autowired
    private IBookBiz biz;
    @Override
    /*value:跟你表單提交到的action邏輯名稱對應
    * className:為action指定別名
    * */
    @Action(value = "login",results = {@Result(name = "success",location = "/success.jsp"),
            @Result(name = "input",location = "/index.jsp")},className = "loginAction")
    public String execute() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        /*獲取頁面上輸入的名稱*/
        String name = request.getParameter("name");
        /*獲取頁面上輸入的價格*/
        String price = request.getParameter("price");
        Book book=new Book(name,price);
        int count = biz.select(book);
        if(count>0){
            List<Book> list = biz.selectAll();
           request.getSession().setAttribute("list",list);
            return SUCCESS;
        }else{
            return INPUT;
        }
    }

    public IBookBiz getBiz() {
        return biz;
    }

    public void setBiz(IBookBiz biz) {
        this.biz = biz;
    }
}

寫到這里,我們的工程就差不多完成一大半了,即將登上高峰,加把勁。。。。。

接下來開始編寫xml文件吧,把這些繁瑣的工作做完我們才能見到彩虹,現在正在聽《陽光總在風雨后》,唱的真好。

2017年4月5日17:06:46

xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
">
    <!--注冊jdbc-->
     <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--添加數據源-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--配置sessionFactory-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <!--方言-->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <!--打印sql-->
                <prop key="hibernate.show_sql">true</prop>
                <!--格式化sql-->
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hbm2ddl.auto">update</prop>
                <!--獲取線程內的變量-->
                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>
            </props>
        </property>
        <!--<property name="mappingDirectoryLocations" value="classpath:cn/happy/beans"></property>-->
    </bean>

    <context:component-scan base-package="cn.note"></context:component-scan>
    <!--bean dao-->
    <!--<bean id="bookDao" class="cn.happy.dao.impl.BookDaoImpl">
        <property name="factory" ref="sessionFactory"></property>
    </bean>-->

    <!--bean biz-->
   <!-- <bean id="bookBiz" class="cn.happy.biz.impl.BookBizImpl">
        <property name="dao" ref="bookDao"/>
    </bean>-->

    <!--action-->
    <!--<bean id="login" class="cn.happy.action.LoginAction">
        <property name="biz" ref="bookBiz"></property>
    </bean>-->

    <!--配置事務-->
    <!--第一步配置事務管理器-->
    <!--<bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="selectAll" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>-->
    <!--配置事務管理器-->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!--注解驅動-->
    <tx:annotation-driven transaction-manager="txManager"></tx:annotation-driven>
</beans>

jdbc.properties文件:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///y2163
jdbc.username=root
jdbc.password=123456

想想寫到這里我們還缺少什么,有沒有什么遺漏,我們先來理一下思路:當用戶請求頁面,填寫完數據,點擊提交,就會根據指定的action地址,action內部機制(FilterDispatcher)會做出一些判斷,去尋找相應的action,根據攜帶的一些數據,調取相應的方法去完成這個工作,完成一系列的判斷工作之后,攜帶數據返回。

下面的圖解會更清晰一點:

看到這個,我就想起我剛理解這個的那會兒,老大難問題,好了廢話不多說了,還是回歸正題吧,看到這里我就想到在web.xml中也需要配置一下,因為在整合中struts2充當的是攔截器的角色,需要配置:

<!--配置filter-->
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>

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

想想還得配置讓項目認到你配置的xml文件:

<!--指定路徑-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContextnote.xml</param-value>
  </context-param>

在配置一道監聽器:

<!--配置監聽器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

上面我們也說到要配置xml文件,這些做完之后,就可以搭建我們的頁面了

index.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登錄頁面</title>
</head>
<body>
<form method="post" action="login">
    用戶名:<input name="name"/><br>
    密碼:<input name="price"/><br>
    <input type="submit" value="提交"/><br>
</form>
</body>
</html>

success.jsp:

<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="c" uri="/struts-tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>成功頁面</title>
</head>
<body>
success!!!!!!!!
<s:debug></s:debug>
${list}
</html>

整體的 一個項目就這樣完成了,寫下來因為沒那么難,看你自己的掌握程度,多多聯系,相信自己。

現在自己聽的歌:《霸王別姬》2017年4月5日17:45:49

好了,登頂。

下期再見。。。。。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM