struts2+spring+hibernate+oracle整合,實現增刪改查操作。(一)


好記性不如爛筆頭,閑來無事,自己搭建了一個基於struts2+spring+hibernate+oracle的框架,以備查閱。如果你看到了,且感興趣,歡迎交流。

使用的環境以及版本如下:

Windows 7、Eclipse4.6、Tomcat8.0、JDK1.8、數據庫oracle11g

Struts-2.3.30、Spring-4.2.2、Hibernate5.2.2

代碼結構目錄

 

一、搭建環境

1、新建web項目

1.1、打開Eclipse,點擊File-->new-->other-->web-->Dynamic Web  Project 點擊next,進入項目新建頁面如圖所示:

  project name 我的是ssh,其他的targer runtime和Dynamic web module version根據自己的配置環境可以修改。我這里用的是tomcat8.0和2.5

 

1.2、然后一直next,當走到Web Module時, 選中Generate  web.xml deployment descriptor,點擊完成,項目新建成功。

  如果不選中Generate  web.xml deployment descriptor,那么新建的項目中就沒有web.xml文件,需要手動添加。

 

2、導入jar包

  2.1、導入struts2 所需的jar包

    把下載好的Struts-2.3.30解壓后,找到struts-2.3.30\apps\ struts2-blank.war \WEB-INF\lib的jar包,復制到項目的WebContent\WEB-INF\lib目錄下

  2.2、導入spring 所需的jar包

    把下載好的Spring-4.2.2解壓后,找到spring-framework-4.2.2.RELEASE\libs的jar包,復制到項目的WebContent\WEB-INF\lib目錄下

  2.3、導入hibernate所需的jar包

    把下載好的Hibernate5.2.2解壓后,找到hibernate-release-5.2.2.Final\lib\required的jar包,復制到項目的WebContent\WEB-INF\lib目錄下(注意:本例使用是ORACLE,記得導入對應的數據庫驅動包)

  2.4、導入oracle所需的jar包

    我用的是classes12.jar,復制到項目的WebContent\WEB-INF\lib目錄下

3、新建jsp文件,login.jsp、index.jsp、error.jsp

  3.1、在WebContent下新建login.jsp文件,配置如下:

   <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
      </head>
      <body>
        <form action="loginAction.action" method="post">
          用戶名:<input type="text" name="username"><br>
          <input type="submit" value="提交">
        </form>
      </body>
    </html>

  3.2、在WebContent下新建error.jsp文件,配置如下:   

  <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
      </head>
      <body>
        error
      </body>
    </html>

  3.3、在WEB-INF下新建page/index.jsp文件,配置如下:

  <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
      </head>
      <body>
        index
      </body>
    </html>

4、配置struts2

  4.1、在web.xml配置過濾器filter,filter-mapping,配置如下:    

  <?xml version="1.0" encoding="UTF-8"?>
  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>ssh</display-name>
	
	<!-- 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>
	
      <welcome-file-list>
          <welcome-file>index.htm</welcome-file>
          <welcome-file>index.jsp</welcome-file>
          <welcome-file>default.htm</welcome-file>
          <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
  </web-app>

  4.1、在struts.xml配置action,配置如下:

  <?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>
     <!-- 告知struts2運行時使用spring來創建對象 -->
     <!--  <constant name="struts.objectFactory" value="spring" /> -->
      <!-- 定義一個包 -->
    <package name="test" extends="struts-default">
    <!-- 通過action連接spring -->
      <action name="loginAction" class="loginAction" method="login">
        <!-- 成功時,跳轉到index.jsp頁面 -->
	   <result name="success">/WEB-INF/page/index.jsp</result>
	   <!-- 失敗時,跳轉到error.jsp頁面 -->
	   <result name="error">/error.jsp</result>
	  </action>
	</package>
</struts> 

5、配置spring

  5.1、在web.xml配置監聽器filter,filter-mapping,配置如下:

   <!--Spring配置監聽器 -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 加載application.xml文件 -->
    <param-value>classpath:application.xml</param-value>
    </context-param>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

  5.2、在src下新建application.xml,在property 中ref的值和bean中的id值一致。配置如下:

  <?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: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/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">

    <!--把service注入action中 -->
    <bean id="loginAction" class="com.ssh.action.LoginAction" scope="prototype">
      <property name="loginService" ref="loginService" />
    </bean>

    <!-- 把dao注入service中 -->

    <bean id="loginService" class="com.ssh.serviceImpl.LoginServiceImpl"  scope="prototype">

      <property name="loginDao" ref="loginDao" />
    </bean>

    <!-- 把sessionFactory注入到dao中 -->
    <bean id="loginDao" class="com.ssh.daoImpl.LoginDaoImpl" scope="prototype">
      <property name="factory">
        <ref bean="sessionFactory" />
      </property>
    </bean>

    <!-- 加載hibernate.cfg.xml文件 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
      <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
      </property>
    </bean>
  </beans>

5、配置hibernate

  5.1、在src下新建hibernate.cfg.xml,配置如下: 

  <!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>
	  <property name="hibernate.show_sql">true</property> 
	  <!-- 配置Oracle方言 --> 
          <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property> 
          <!-- 加載Oracle驅動 -->
          <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
          <!-- 配置Oracle的url路徑,連接數據庫, ORCL數據庫名-->
          <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:ORCL</property>
          <!-- 配置Oracle的用戶名-->
          <property name="hibernate.connection.username">zs</property>
          <!-- 配置Oracle的密碼-->
          <property name="hibernate.connection.password">123456</property>
        
          <property name="hibernate.hbm2ddl.auto">update</property>
          <!-- 映射hibernate.hbm.xml文件 -->
          <mapping resource="com/ssh/entity/hibernate.hbm.xml"/>
	</session-factory>
  </hibernate-configuration>

   5.2、在com.ssh.entity包下新建hibernate.hbm.xml,配置如下:   

  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE hibernate-mapping PUBLIC 
      "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

  <!--用戶Hibernate映射文件,用戶屬性和數據庫表結構相互映射 -->
  <hibernate-mapping>
	<class name="com.ssh.entity.User" table="shop_user">
	  <id name="userid" type="java.lang.Integer">
        <column name="userid" />
        <generator class="native"/>
       </id>
       <property name="username" type="java.lang.String">
         <column name="username" length="20" not-null="true" />        </property> </class>   </hibernate-mapping>

6、各層的代碼顯示

  6.1、action層,也是控制層

  package com.ssh.action;

  import com.opensymphony.xwork2.ActionSupport;
  import com.ssh.service.LoginService;

  public class LoginAction extends ActionSupport {

	//序列號
	private static final long serialVersionUID = 1L;
	//定義用戶名
	private String username;
	//定義service
	private LoginService loginService;
	
    public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
    /**
     * 獲取username的目的是為了dubug測試跳轉,除此之外沒有其他操作。
     * @return SUCCESS/ERROR
     */
	public String login() {
		if ("1".equals(username)) {
			int num = loginService.getUser();
			if(num > 0){
				return SUCCESS;
			}else{
				return ERROR;
			}
		} else {
			return ERROR;
		}
	}
}

  6.2、service層,分別建立接口和實現類

  package com.ssh.service;
  /**
   * LoginService接口類
   * @author wei
   */
  public interface LoginService {
	public int getUser();
  }

   

  package com.ssh.serviceImpl;

  import com.ssh.dao.LoginDao;
  import com.ssh.service.LoginService;
  /**
   * LoginServiceImpl實現類
   * @author wei
   */
  public class LoginServiceImpl implements LoginService{

	//dao實例的使用注入方式
	private LoginDao loginDao;
	
	public void setLoginDao(LoginDao loginDao) {
		this.loginDao = loginDao;
	}
	
	@Override
	public int getUser() {
		int num = loginDao.getUser();
		return num;
	}
  }

  6.3、dao層,分別建立接口和實現類

  package com.ssh.dao;

  /**
   * LoginDao接口
   * @author wei
   */
  public interface LoginDao {
	public int getUser();
  }

  

  package com.ssh.daoImpl;

  import java.util.List;

  import org.hibernate.Session;
  import org.hibernate.SessionFactory;
  import org.hibernate.Transaction;
  import org.hibernate.query.Query;

  import com.ssh.dao.LoginDao;
  import com.ssh.entity.User;

  /**
   * LoginDaoImpl實現類
   * @author wei
   */
  public class LoginDaoImpl implements LoginDao {

	// 要使用某個實例,就定義聲明一個對象,然后給它添加set方法,實現spring注入方式
	private SessionFactory factory;
	public void setFactory(SessionFactory factory) {
		this.factory = factory;
	}

	@Override
	public int getUser() {
		// 獲取session getCurrentSession:先查找,沒有則創建新的;openSession:每次都創建
		Session session = factory.openSession();
		//開啟事務
		Transaction tx = session.beginTransaction();
		
		//插入
		User user = new User();
		user.setUsername("wangwu");
		session.save(user);
		
		//查詢
		String sqlSel = "from User";
		Query<User> query = session.createQuery(sqlSel,User.class);
		List<User> list = query.getResultList();
		for(User user1:list){
			System.out.println(user1.getUsername()+":"+user1.getUserid());
		}
		
		//關閉事務
		tx.commit();
		session.close();
		
		//修改
		Session session2 = factory.openSession();
		//開啟事務
		Transaction tx2 = session2.beginTransaction();
		String sqlup="update User set username = 'test' where userid = '47'";
		session2.createQuery(sqlup).executeUpdate();
		
		String sqDel="delete from  User  where userid = '47'";
		int size = session2.createQuery(sqDel).executeUpdate();
		//關閉事務
		tx2.commit();
		session2.close();
		return size;
	}
  }

  6.4、entity層  

  package com.ssh.entity;

  /**
   * 用戶實體類
   * @author wei
   */
  public class User {
	// 用戶id 
	private int userid;
	//用戶名稱
	private String username;

	public int getUserid() {
		return userid;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public User() {
	}
  }

7、總結

Struts:

優點:1、開源的,使開發者可以更深了解他的原理和內部實現機制;2、可擴展性采用MVC模式分離業務邏輯層 顯示層 模型層 低耦合,結構清晰,使開發者專注於業務邏輯;3、豐富的標簽庫供使用;4、支持國際化;5、很高的重用性。

缺點:1、Struts將MVC中的控制層 一分為三 在獲得結構更加清晰的同時,也增加了系統的復雜度;2、ActionForms使用不便、無法進行單元測試;3、對servlet依賴性過強,struts在處理action時 必須要依賴 httprequest和 HttpResponse 對象。

Hibernate

優點:1、數據庫連接的中間件,而且對程序的依賴性很小 透明性 使用了java的反射機制;2、輕量級 他對jdbc進行了輕量級的封裝 而且可以在程序中取代EJB的cmp,完成持久化;3、性能很好,而且還是輕量級 很靈活;4、支持多種數據庫的1對多的復雜關系;5、可 

             以 完全使用面向對象的思想去編程,使用了JTA JDBC 和 JNDI技術。

缺點:1、一個持久化類不能映射多個表;2、相對內存消耗JDBC是最省內存的,hibernate次之 ejb Bean 最差。

Spring

優點:1、spring 是基於ioc(控制反轉)和aop(面向切面編程) 的框架,而且封裝了所有的事務,不需要程序員自己去提交事務,一切都由web容器去控制,省去了很多代碼。2、spring采用了單態和工廠模式 采用mvc模式下的java程序 盡管已經把層與層之間的關系耦

             合度降低,但還是有聯系,這時候使用spring 把所有bean都交由web容器去控制 創建和銷毀,這樣才真正的降低了耦合度, 而且bean的創建的生命周期都在web容器 里控制,而且他從工廠里實例的bean都是單態的,當然可以加一個屬性讓他不是單態;3、

             向接口編程,只需要知道要實現的接口就可以,不需要知道他的具體實現,使用spring框架有利於單元測試

總結:ssh(spring+struts2+hibernate)是基於MVC三層架構的基礎上,進行的優化,目的為了便於項目管理,提高項目開發效率。但是隨着近幾年來,ssh框架暴露出來的弊端,也是令人堪憂,所以現在人們大多采用ssm(spring+springMVC+mybitis),不僅擁有ssh的優點,而且避免了ssh的弊端。

參考鏈接: http://www.cnblogs.com/sharpest/p/7362364.html


免責聲明!

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



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