天天看点

搭建简单的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查询。