天天看點

搭建簡單的SSH架構執行個體

1.導入所依賴的架包

搭建簡單的SSH架構執行個體

2.配置web.xml檔案

<!--配置spring 容器用于初始化容器  -->
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:spring-*.xml</param-value>
  </context-param>
  <!--配置struts  -->
  <filter>
  	<filter-name>struts</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
           

3.配置spring-hibernate.xml

<!--開啟元件掃描  -->
	<context:component-scan base-package=""/>

	<!--定義資料源  -->
	<!--配置資料庫連接配接  -->
	<bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
		<property name="url" value="jdbc:mysql:///資料庫名?useUnicode=true&amp;characterEncoding=UTF-8"/>
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="username" value="賬戶"/>
		<property name="password" value="密碼"/>
	</bean>

	<!--配置sqlSessionFactory  -->
	<bean id="sqlSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!--連接配接資料庫  -->
		<property name="dataSource" ref="dataSource"/>
		<!--配置hibernateTemplace  -->
		<property name="hibernateProperties">
			<props>
                 <--使用hibernate方言-->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                控制台顯示相關的HQL
				<prop key="hibernate.show_sql">true</prop>
                格式化HQL
				<prop key="hibernate.format_sql">true</prop>
			</props>
		</property>
		<!--配置映射檔案  -->
		<property name="mappingLocations">
			<list>
				<value>classpath:mappings/XX.hbm.xml</value>
			</list>
		</property>
	</bean>
	<!--配置事務管理  -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sqlSessionFactory"/>
	</bean>
	<!--開啟事務注解驅動  -->
	<tx:annotation-driven transaction-manager="txManager"/>
	<!--配置hibernateTemplace  -->
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sqlSessionFactory"/>
	</bean>
           

4.配置struts.xml

<struts>
		<package name="Link" namespace="/" extends="struts-default">
			<action name="hreo_*" class="hreoAction" method="{1}">
				<result name="success" >/jsp/list.jsp</result>
				<result name="update">/jsp/update.jsp</result>
				<result name="add">/jsp/add.jsp</result>
				<result name="redirect" type="redirectAction">hreo_list</result>
			</action>
		</package>
	</struts>
           

5.index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>主界面</title>
</head>
<body style="font-size: 30px;">
	<form action="${pageContext.request.contextPath }/hreo_list.action" method="post">
		<input type="submit" value="進入">
	</form>
</body>
</html>
           

6.list.jsp

可以使用OGNL或者EL表達式,根據個人愛好

不知道啥是OGNL表達式的看我部落格文章---小東升職記---裡面有執行個體說明

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>展示頁面</title>
<style type="text/css">
	table {
	border: 1px solid #ccc;
	margin: 100px auto;
	border-collapse: collapse;
}
	table td {
	border: 1px solid #ccc;
}
	tfoot {
	text-align: center;
	font-family: 楷體;
	font-size: 15px;
}
</style>
</head>
<body>
	<div>
		<table>
			<thead>
				<tr>
					<td>英雄名稱</td>
					<td>英雄屬性</td>
					<td>英雄位置</td>
					<td>英雄名綽号</td>
					<td>英雄操作</td>
				</tr>
			</thead>
			<c:forEach items="${list }" var="list" step="1">
			<tbody>
				<tr>
					<td>${list.h_name }</td>
					<td>${list.h_properties }</td>
					<td>${list.h_loc }</td>
					<td>${list.h_nick }</td>
					<td>
						<a href="${pageContext.request.contextPath }/hreo_detail.action?h_name=${list.h_name}" target="_blank" rel="external nofollow" >修改</a>
						<a href="${pageContext.request.contextPath }/hreo_delete.action?h_name=${list.h_name}" target="_blank" rel="external nofollow" >删除</a>
					</td>
				</tr>
			</tbody>
			</c:forEach>
			<tfoot>
				<tr>
					<td colspan="5">拳頭出品</td>
				</tr>
			</tfoot>
		</table>
	</div>
</body>
</html>
           

7.編寫一個簡單的控制層

/**
 * 
 */
package com.zhiyou100.action;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.util.ValueStack;
import com.zhiyou100.entity.Hero;
import com.zhiyou100.service.HreoService;

/**
 * @author Administrator
 *
 */
@Controller
@Scope("prototype")
public class HreoAction {
	@Resource
	private HreoService hreoService;
	
	public HreoService getHreoService() {
		return hreoService;
	}
	public void setHreoService(HreoService hreoService) {
		this.hreoService = hreoService;
	}
	@Resource
	private Hero hero;
	
	public Hero getHero() {
		return hero;
	}
	public void setHero(Hero hero) {
		this.hero = hero;
	}
	private String h_name;
	
	public String getH_name() {
		return h_name;
	}
	public void setH_name(String h_name) {
		this.h_name = h_name;
	}
	public String list() {
		List<Hero> list = hreoService.findAll();
		ValueStack stack = ActionContext.getContext().getValueStack();
		stack.set("list", list);
		return "success";
	}
	public String delete() {
		Hero hero2 = hreoService.FindByName(h_name);
		hreoService.delete(hero2);
		return "redirect";
	}
	public String detail() {
		Hero hero2 = hreoService.FindByName(h_name);
		ValueStack valueStack = ActionContext.getContext().getValueStack();
		valueStack.set("hero", hero2);
		return "update";
	}
	public String update() {
		hreoService.update(hero);
		return "redirect";
	}
}
           

8.服務層我就隻寫實作類,接口不在寫

/**
 * 
 */
package com.zhiyou100.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zhiyou100.dao.HreoDao;
import com.zhiyou100.entity.Hero;
import com.zhiyou100.service.HreoService;

/**
 * @author Administrator
 *
 */
@Service
public class HreoServiceImpl implements HreoService{
	@Resource
	private HreoDao hreoDao;
	public List<Hero> findAll() {
		// TODO Auto-generated method stub
		return hreoDao.FindAll();
	}
	public void delete(Hero hero) {
		// TODO Auto-generated method stub
		hreoDao.delete(hero);
	}
	public Hero FindByName(String name) {
		return hreoDao.FindByName(name);
	}
	public void update(Hero hero) {
		// TODO Auto-generated method stub
		hreoDao.update(hero);
	}
}
           

9.持久層隻寫實作類

/**
 * 
 */
package com.zhiyou100.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.zhiyou100.dao.HreoDao;
import com.zhiyou100.entity.Hero;

/**
 * @author Administrator
 *
 */
@Repository
@Transactional
public class HreoDaoImpl implements HreoDao{
	@Resource
	private HibernateTemplate hibernateTemplate;
	public List<Hero> FindAll() {
		// TODO Auto-generated method stub
		@SuppressWarnings("unchecked")
		List<Hero> list = hibernateTemplate.find("from Hero where h_status = 1");
		if (list!=null&&list.size()>0) {
			return list;
		}
		return null;
	}
	public void delete(Hero hero) {
		// TODO Auto-generated method stub
		hero.setH_status(0);
		hibernateTemplate.update(hero);
	}
	public Hero FindByName(String name) {
		@SuppressWarnings("unchecked")
		List<Hero> list = hibernateTemplate.find("from Hero where h_name=? and h_status = 1", name);
		return list.get(0);
	}
	public void update(Hero hero) {
		// TODO Auto-generated method stub
		hibernateTemplate.update(hero);
	}
}
           

10.寫相關的*.hbm.xml配置檔案

<hibernate-mapping>
    	<class name="com.zhiyou100.entity.Hero" table="hreo">
    		<id name="h_id" column="h_id" type="int">
    			<generator class="identity"/>
    		</id>
    		<property name="h_name" column="h_name" type="string"/>
    		<property name="h_properties" column="h_properties" type="string"/>
    		<property name="h_loc" column="h_loc" type="string"/>
    		<property name="h_nick" column="h_nick" type="string"/>
    		<property name="h_status" column="h_status" type="int"/>
    	</class>
    </hibernate-mapping>
           

11.其餘的操作不在書寫,代碼很容易看懂的,最重要的是讓你體會一下SSH的用法,優點和缺點,友善你以後寫項目适合選取合适的架構

12.談談我對hibernate的了解吧

1. 面向對象設計的軟體内部運作過程可以了解成就是在不斷建立各種新對象、建立對象之間的關系,調用對象的方法來改變各個對象的狀态和對象消亡的過程,不管程式運作的過程和操作怎麼樣,本質上都是要得到一個結果,程式上一個時刻和下一個時刻的運作結果的差異就表現在記憶體中的對象狀态發生了變化。

2.為了在關機和記憶體空間不夠的狀況下,保持程式的運作狀态,需要将記憶體中的對象狀态儲存到持久化裝置和從持久化裝置中恢複出對象的狀态,通常都是儲存到關系資料庫來儲存大量對象資訊。從Java程式的運作功能上來講,儲存對象狀态的功能相比系統運作的其他功能來說,應該是一個很不起眼的附屬功能,java采用jdbc來實作這個功能,這個不起眼的功能卻要編寫大量的代碼,而做的事情僅僅是儲存對象和恢複對象,并且那些大量的jdbc代碼并沒有什麼技術含量,基本上是采用一套例行公事的标準代碼模闆來編寫,是一種苦活和重複性的工作。

3.通過資料庫儲存java程式運作時産生的對象和恢複對象,其實就是實作了java對象與關系資料庫記錄的映射關系,稱為ORM(即Object Relation Mapping),人們可以通過封裝JDBC代碼來實作了這種功能,封裝出來的産品稱之為ORM架構,Hibernate就是其中的一種流行ORM架構。使用Hibernate架構,不用寫JDBC代碼,僅僅是調用一個save方法,就可以将對象儲存到關系資料庫中,僅僅是調用一個get方法,就可以從資料庫中加載出一個對象。

4.使用Hibernate的基本流程是:配置Configuration對象、産生SessionFactory、建立session對象,啟動事務,完成CRUD操作,送出事務,關閉session。

5.使用Hibernate時,先要配置hibernate.cfg.xml檔案,其中配置資料庫連接配接資訊和方言等,還要為每個實體配置相應的hbm.xml檔案,hibernate.cfg.xml檔案中需要登記每個hbm.xml檔案。

6.在應用Hibernate時,重點要了解Session的緩存原理,級聯,延遲加載和hql查詢。