1. 程式人生 > >SSH框架搭建例項--Spring4+Struts2+Hibernate4搭建

SSH框架搭建例項--Spring4+Struts2+Hibernate4搭建

 SSH框架的搭建

一 Spring容器裡我們通過IOC依賴注入的方式把Hibernate和Struts的各個元件都交給Spring容器去建立和管理。以及事物管理等

這裡給出的步驟不是具體的搭建步驟(按照原理搭建的步驟),只是給出了一個完整SSH框架的所有程式碼包括配置檔案以及jar  ,直接複製下面給出的專案可直接執行。

二 SSH框架需要的jar包

這個給出了整合SSH需要的jar包  稍後會出一篇文章講一下每一個jar包的具體作用都是什麼

這裡先給出所示jar包的下載地址:http://download.csdn.net/detail/porsche_gt3rs/9829426

三 SSH步驟

  1. 新建一個web專案匯入上面提到的jar 包 在web.xml檔案中配置Struts2的過濾器(前端控制器)和Spring容器的例項化及配置Spring配置檔案(上下文)的位置

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Spring_Struts2</display-name>
  
  <!-- 指定Spring配置檔案(上下文)位置和名稱 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
   
  <!-- 在伺服器啟動時,例項化Spring容器物件 -->
  <listener>
  	<listener-class>
  		org.springframework.web.context.ContextLoaderListener
  	</listener-class>
  </listener>
  
  <!-- 前端控制器 -->
  <filter>
  	<filter-name>strutsFilter</filter-name>
  	<filter-class>
  		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  	</filter-class>
  	<!-- <filter-class>
  		org.apache.struts2.dispatcher.FilterDispatcher
  	</filter-class> -->
  </filter>
  <filter-mapping>
  	<filter-name>strutsFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2.在src下建立一個struts2配置檔案:struts.xml  配置一個action action的建立交給Spring容器

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 
              "http://struts.apache.org/dtds/struts-2.0.dtd" >
<struts>
	<package name="demo1"  extends="struts-default">
		<!-- 利用struts-spring-plugin.jar去
		Spring容器尋找bean物件 利用class屬性當做id值去spring容器中獲取 -->
		<action name="hello1" class="helloAction">
			<result name="success">/hello.jsp</result>
		</action>
		
		<action name="findUserInfo" class="UserInfoAction">
			<result name="success">/WEB-INF/jsp/User.jsp</result>
		</action>
	</package>
   
</struts>
3.在src下建立一個Spring配置檔案:applicationContext.xml 
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:mvc="http://www.springframework.org/schema/mvc" 
  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:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/mvc  
     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
     http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context-4.0.xsd
     http://www.springframework.org/schema/tx
     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">

	<!-- 定義連線池Bean物件    (這裡使用dbcp連線池)-->
	<bean id="myDataSource" destroy-method="close" 
	class="org.apache.commons.dbcp.BasicDataSource">
		<!-- 注入資料庫的連線引數 -->
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl">
		</property>
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver">
		</property>
		<property name="username" value="WebChat">
		</property>
		<property name="password" value="WebChat">
		</property>
		<property name="maxActive" value="20">  <!-- 最大的連線數為20個 -->
		</property>
		<property name="initialSize" value="2"> <!-- 初始連線數為2個 -->
		</property>
	</bean>

	<!-- 註冊一個sessionFactory元件 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 注入資料庫連線池 -->
		<property name="dataSource" ref="myDataSource">
		</property>
		<!-- 注入Hibernate配置引數 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<!-- 注入對映描述檔案 -->
		<property name="mappingResources">
			<list>
				<value>com/xuhao/entities/Userinfo.hbm.xml</value>
			</list>
		</property>
	</bean>

	<!-- UserInfoDAO元件 -->
	<bean id="UserinfoDao" scope="prototype" 
	class="com.xuhao.Dao.impl.HibernateUserInfoDaoImpl">
		<property name="sessionFactory" ref="sessionFactory">
		</property>
	</bean>
	<!-- UserInfoService元件 -->
	<bean id="UserinfoService" class="com.xuhao.ServiceImpl.UserInfoServiceImpl" scope="prototype">
		<property name="UserInfoDao" ref="UserinfoDao">
		</property>
	</bean>
	<!-- UserInfoAction元件 -->
	<bean id="UserInfoAction" class="com.xuhao.action.UserInfoAction">
		<property name="UserInfoService" ref="UserinfoService"></property>
	</bean>
	
	
	<bean id="helloAction" class="com.xuhao.action.HelloAction" scope="prototype">
	</bean>

	
	
	
</beans>

4. entities action service dao 的程式碼:

entities

package com.xuhao.entities;


/**
 * Userinfo entity. @author MyEclipse Persistence Tools
 */

public class Userinfo implements java.io.Serializable {

	// Fields

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String userId;
	private String userName;
	private String password;
	private String phone;
	private String sex;
	private String email;
	private String userQq;
	private String userType;
	private String superUser;
	private String createTime;
	private String remark1;
	private String remark2;
	private String remark3;
	private String remark4;

	// Constructors

	/** default constructor */
	public Userinfo() {
	}

	/** minimal constructor */
	public Userinfo(String userId) {
		this.userId = userId;
	}

	/** full constructor */
	public Userinfo(String userId, String userName, String password,
			String phone, String sex, String email, String userQq,
			String userType, String superUser, String createTime,
			String remark1, String remark2, String remark3, String remark4) {
		this.userId = userId;
		this.userName = userName;
		this.password = password;
		this.phone = phone;
		this.sex = sex;
		this.email = email;
		this.userQq = userQq;
		this.userType = userType;
		this.superUser = superUser;
		this.createTime = createTime;
		this.remark1 = remark1;
		this.remark2 = remark2;
		this.remark3 = remark3;
		this.remark4 = remark4;
	}

	// Property accessors

	public String getUserId() {
		return this.userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return this.userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPhone() {
		return this.phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getSex() {
		return this.sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getUserQq() {
		return this.userQq;
	}

	public void setUserQq(String userQq) {
		this.userQq = userQq;
	}

	public String getUserType() {
		return this.userType;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}

	public String getSuperUser() {
		return this.superUser;
	}

	public void setSuperUser(String superUser) {
		this.superUser = superUser;
	}

	public String getCreateTime() {
		return this.createTime;
	}

	public void setCreateTime(String createTime) {
		this.createTime = createTime;
	}

	public String getRemark1() {
		return this.remark1;
	}

	public void setRemark1(String remark1) {
		this.remark1 = remark1;
	}

	public String getRemark2() {
		return this.remark2;
	}

	public void setRemark2(String remark2) {
		this.remark2 = remark2;
	}

	public String getRemark3() {
		return this.remark3;
	}

	public void setRemark3(String remark3) {
		this.remark3 = remark3;
	}

	public String getRemark4() {
		return this.remark4;
	}

	public void setRemark4(String remark4) {
		this.remark4 = remark4;
	}


}

HelloAction

package com.xuhao.action;

public class HelloAction {
	// output
	private String name;

	public String getName() {
		return name;
	}

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

	public String execute(){
		name = "TOMCAT";
		return "success";
	}
}
UserInfoAction
package com.xuhao.action;

import java.util.List;

import com.xuhao.Service.UserInfoService;
import com.xuhao.entities.Userinfo;

/**
 * 使用者資訊類
 * @author xuhao
 *
 */
public class UserInfoAction {
	
	
	private List<Userinfo> ulist;
	

	public List<Userinfo> getUlist() {
		return ulist;
	}



	public void setUlist(List<Userinfo> ulist) {
		this.ulist = ulist;
	}



	private UserInfoService userInfoService;
	
	
	
	public UserInfoService getUserInfoService() {
		return userInfoService;
	}



	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}



	/**
	 * 查詢所有使用者資訊
	 * @return
	 */
	public String execute(){
		ulist = userInfoService.findAll();
		return "success";
	}
}

UserInfoService UserInfoServiceImpl
package com.xuhao.Service;

import java.util.List;

import com.xuhao.entities.Userinfo;

public interface UserInfoService {
	public List<Userinfo> findAll();
}


package com.xuhao.ServiceImpl;

import java.util.List;

import com.xuhao.Dao.UserInfoDao;
import com.xuhao.Service.UserInfoService;
import com.xuhao.entities.Userinfo;

public class UserInfoServiceImpl implements UserInfoService{

	private UserInfoDao userInfoDao;
	
	
	public UserInfoDao getUserInfoDao() {
		return userInfoDao;
	}


	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}


	/**
	 * 查詢所有使用者資訊
	 */
	@Override
	public List<Userinfo> findAll() {
		return userInfoDao.findAll();
	}

}

UserInfoDao UserInfoDaoImpl

package com.xuhao.Dao;

import java.util.List;

import com.xuhao.entities.Userinfo;

/**
 * UserInfoDao鎺ュ彛綾�
 * @author xuhao
 *
 */
public interface UserInfoDao {
	public Userinfo findById(String user_id);
	public void save(Userinfo userInfo);
	public void delete(String user_id);
	public void update(Userinfo userInfo);
	public List<Userinfo> findAll();
	public int Count();
	public List<Userinfo> findByPage(int page, int pageSize);
	
}

package com.xuhao.Dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.xuhao.Dao.UserInfoDao;
import com.xuhao.entities.Userinfo;

/**
 * UserInfoDao實現類
 * @author xuhao
 *
 */
@Repository
@Scope("prototype")
public class HibernateUserInfoDaoImpl extends HibernateDaoSupport
 	implements UserInfoDao{

	@Resource//  將容器裡面的SessionFactory注入進去
	public void setMySessionFactory(SessionFactory sf){
		//  將注入的SessionFactory給DaoSupport傳入
		super.setSessionFactory(sf);
	}

	
	@Override
	public Userinfo findById(String user_id) {
		Userinfo userinfo = getHibernateTemplate().get(Userinfo.class, user_id);
		return userinfo;
	}

	@Override
	public void save(Userinfo userInfo) {
		getHibernateTemplate().save(userInfo);
	}

	@Override
	public void delete(String user_id) {
		Userinfo userinfo = findById(user_id);
		getHibernateTemplate().delete(userinfo);
	}

	@Override
	public void update(Userinfo userInfo) {
		getHibernateTemplate().update(userInfo);
	}

	@Override
	public List<Userinfo> findAll() {
		String hql = "FROM Userinfo";
		@SuppressWarnings("unchecked")
		List<Userinfo> ulist = (List<Userinfo>) getHibernateTemplate().find(hql);
		return ulist;
	}

	@Override
	public int Count() {
		String hql = "SELECT COUNT(*) FROM Userinfo";
		List list = getHibernateTemplate().find(hql);
		int count = Integer.parseInt(list.get(0).toString());
		return count;
	}

	/**
	 * 分頁
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List<Userinfo> findByPage(final int page, final int pageSize) {
		List<Userinfo> ulist = (List<Userinfo>)getHibernateTemplate().execute(
			new HibernateCallback() {  //  回撥函式

				@Override
				public Object doInHibernate(Session session)  //  把底層的session暴露出來 可以使用
						throws HibernateException {
					//  使用session物件
					String hql = "FROM Userinfo";
					Query query = session.createQuery(hql);
					int begin = (page - 1) * pageSize;
					query.setFirstResult(begin);
					query.setMaxResults(pageSize);
					return query.list();
				} 
				
			}
		);
		return ulist;
	}

}
實體的對映檔案
<?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">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.xuhao.entities.Userinfo" table="USERINFO" schema="WEBCHAT">
        <id name="userId" type="java.lang.String">
            <column name="USER_ID" length="50" />
            <generator class="assigned" />
        </id>
        <property name="userName" type="java.lang.String">
            <column name="USER_NAME" length="100" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" length="100" />
        </property>
        <property name="phone" type="java.lang.String">
            <column name="PHONE" length="20" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="SEX" length="2" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="EMAIL" length="100" />
        </property>
        <property name="userQq" type="java.lang.String">
            <column name="USER_QQ" length="20" />
        </property>
        <property name="userType" type="java.lang.String">
            <column name="USER_TYPE" length="2" />
        </property>
        <property name="superUser" type="java.lang.String">
            <column name="SUPER_USER" length="50" />
        </property>
        <property name="createTime" type="java.lang.String">
            <column name="CREATE_TIME" length="20" />
        </property>
        <property name="remark1" type="java.lang.String">
            <column name="REMARK1" length="500" />
        </property>
        <property name="remark2" type="java.lang.String">
            <column name="REMARK2" length="500" />
        </property>
        <property name="remark3" type="java.lang.String">
            <column name="REMARK3" length="500" />
        </property>
        <property name="remark4" type="java.lang.String">
            <column name="REMARK4" length="500" />
        </property>
        <!-- <set name="publicUsers" inverse="true">
            <key>
                <column name="SUPER_USER" length="50" />
            </key>
            <one-to-many class="md.PublicUser" />
        </set> -->
    </class>
</hibernate-mapping>

index.jsp hello.jsp user.jsp

index.jsp

<%@ page language="java" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
  	<a href="hello1.action">Hello例項1</a>
  </body>
</html>

hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   	
  </head>
  
  <body>
    <h1>${name}你好!</h1>
    <a href="findUserInfo.action">查詢所有使用者資訊</a>
  </body>
</html>

user.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
  </head>
  
  <body>
    <center>
  		<h1>使用者詳細資訊</h1>
  		<table border="1px;" width="400px;" >
  			<tr>
  				<td>ID</td>
  				<td>姓名</td>
  				<td>密碼</td>
  				<td>手機號</td>
  				<td>性別</td>
  				<td>郵箱</td>
  				<td>QQ</td>
  				<td>使用者型別</td>
  				<td>上級使用者</td>
  				<td>建立時間</td>
  			</tr>
  			<s:iterator value="#request.ulist" id="u">
  			<tr>
  				<td align="center"><s:property value="#u.userId"></s:property></td>
  				<td align="center"><s:property value="#u.userName"></s:property></td>
  				<td align="center"><s:property value="#u.password"></s:property></td>
  				<td align="center"><s:property value="#u.phone"></s:property></td>
  				<td align="center"><s:property value="#u.sex"></s:property></td>
  				<td align="center"><s:property value="#u.email"></s:property></td>
  				<td align="center"><s:property value="#u.userQq"></s:property></td>
  				<td align="center"><s:property value="#u.userType"></s:property></td>
  				<td align="center"><s:property value="#u.superUser"></s:property></td>
  				<td align="center"><s:property value="#u.createTime"></s:property></td>
  				<%-- <td><a href="delete.action?id=<s:property value='#mt.id'/>">刪除</a></td>
  				<td><a href="update.jsp?id=<s:property value='#mt.id'/>">更新</a></td> --%>
  			</tr>
  			</s:iterator>
  		</table>
  		<br>
  			<!-- <a href="save.jsp" >新增使用者</a> -->
  	</center>
  </body>
</html>


  5 測試執行

將專案部署 啟動後 在瀏覽器輸入:   http://localhost:8080/Spring_Struts2/