所谓的SSH框架就是Spring MVC+Spring+Hibernate。
本文是在上一篇“Spring MVC基础使用总结”基础上进行的。
一、Spring MVC和spring集成
spring和spring mvc其实是一个东西,在spring官网上,这两个在一个地方。
1、更改配置文件web.xml
(1)添加springframework的监听
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
(2)将原来配置在servlet中的配置文件位置拎出来单独配置
①之前
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/springAnnotation-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
②之后
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/springAnnotation-servlet.xml</param-value>
</context-param>
<listener>
<!--......-->
</listener>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
2、创建基于spring的三层框架
(1)接口层
ISpring.java
package com.tgb.web.controller.annotation;
public interface ISpring {
public String get();
}
(2)新建springManager.java实现ISpring.java接口
package com.tgb.web.controller.annotation;
public class SpringManager implements ISpring {
@Override
public String get() {
System.out.println("------I am springManager----");
return "I am getMethod";
}
}
(3)新建配置文件,配置springManager的信息
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>
<!--注册springManager组件-->
<beans>
<bean id="springManager" class="com.tgb.web.controller.annotation.SpringManager"></bean>
</beans>
(4)新建controller调用springManager的get方法
package com.tgb.web.controller.annotation;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SpringController {
//使用注解获取bean
@Resource(name="springManager")
private ISpring springManager;
@RequestMapping("/spring/get")
public String get(){
System.out.println(springManager.get());
return "/success";
}
}
二、集成hibernate
1、全局配置文件-SpringAnnotation-hibernate.xml
(1)配置数据源信息
<!--配置数据源信息-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
<property name="userName" value="spring"/>
<property name="password" value="spring"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<!--配置hibernate的方言-->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hiberante.format_sql">true</prop>
</props>
</property>
<!--加载配置文件-->
<property name="configLocations">
<list>
<value>
classpath*:com/tgb/web/controller/hibernate/hibernate.cfg.test.xml
</value>
</list>
</property>
</bean>
最后加载配置文件,是加载hibernate自己的配置文件,hibernate自己的配置文件中,配置了对实体类的映射。
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>
<!--只需要加载spring实体类的路径即可,其他的关于hibernate的配置在SpringAnnotation-hibernate.xml中配置-->
<mapping class="com.tgb.web.controller.entity.User"/>
</session-factory>
</hibernate-configuration>
(2)拦截事务配置
<!--拦截事务配置-->
<!--数据源和代理机制配置-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<!--指定管理哪个session-->
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--事务特性描述配置-->
<bean id="transactionBase" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<!--配置在什么情况下开启事务-->
<property name="transactionAttributes">
<props>
<!--PROPAGATION_REQUIRED表示支持当前事务,如果当前没有事务,则新建一个事务-->
<!-- -Exception表示有异常抛出时,事务回滚,-代表回滚,+代表提交-->
<!--PROPAGATION_NEVER表示以非事务的方式执行,如果当前存在事务,则抛出异常-->
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="get*">PROPAGATION_NEVER</prop>
</props>
</property>
</bean>
三、SSH框架的代码结构
1、entity层
(1)User.java
package com.tgb.web.controller.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="T_USER")
public class User {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Column(length=32)
private String id;
@Column(length=32)
private String userName;
@Column(length=32)
private String age;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
2、Dao层
(1)接口类:IUserDao.java
package com.tgb.web.controller.dao;
import java.util.List;
import com.tgb.web.controller.entity.User;
public interface IUserDAO {
public void addUser(User user);
}
(2)数据库操作类(具体实现类):UserDAO.java
package com.tgb.web.controller.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import com.tgb.web.controller.entity.User;
public class UserDAO implements IUserDAO {
//有了sessionFactory就可以去操作数据库了
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void addUser(User user) {
//getCurrentSession()拿到当前的session,若没有的话,hibernate会自动创建一个
//拿到的session才可以去操作数据库,调用save(user)方法,就可以吧user存储到数据库中。
sessionFactory.getCurrentSession().save(user);
}
}
3、Service层
(1)接口类IUserManager.java
package com.tgb.web.controller.service;
import java.util.List;
import com.tgb.web.controller.entity.User;
public interface IUserManager {
public void addUser(User user);
}
(2)具体实现类UserManager.java
package com.tgb.web.controller.service;
import java.util.List;
import com.tgb.web.controller.dao.IUserDAO;
import com.tgb.web.controller.entity.User;
public class UserManager implements IUserManager {
//将Dao层的userDao注入进来
private IUserDAO userDao;
public void setUserDao(IUserDAO userDao) {
this.userDao = userDao;
}
@Override
public void addUser(User user) {
userDao.addUser(user);
}
}
4、UserController
package com.tgb.web.controller;
@Controller
@RequestMapping("/user")
public class UserController {
//注入userManager
@Resource(name="userManager")
private IUserManager userManager;
@RequestMapping("/toAddUser")
public String toAddUser(){
return "/addUser";
}
@RequestMapping("/addUser")
public String addUser(User user){
userManager.addUser(user);
return "/success";
}
}
5、配置类
(1)springAnnotation-servlet.xml
全局配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 注解扫描包 -->
<context:component-scan base-package="com.tgb.web.controller" />
<!-- 开启注解 -->
<mvc:annotation-driven/>
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->
<!-- 静态资源访问 -->
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760000" />
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
(2)对hibernate的配置
springAnnotation-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>
<beans>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
<property name="username" value="spring"/>
<property name="password" value="spring"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hiberante.format_sql">true</prop>
</props>
</property>
<property name="configLocations">
<list>
<value>
classpath*:com/tgb/web/controller/hibernate/hibernate.cfg.test.xml
</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="transactionBese" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="get*">PROPAGATION_NEVER</prop>
</props>
</property>
</bean>
</beans>
(3)hibernate与表对应关系
hibernate.cfg.test.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>
<mapping class="com.tgb.web.controller.entity.User"/>
</session-factory>
</hibernate-configuration>
(4)spring中注册的组件
springAnnotation-import.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>
<beans>
<bean id="userDao" class="com.tgb.web.controller.dao.UserDAO">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--配置service层的bean-->
<bean id="userManagerBase" class="com.tgb.web.controller.service.UserManager">
<property name="userDao" ref="userDao"></property>
</bean>
<!--注册userManager,继承事务,返回一个userManagerBase的类-->
<!--进行这样配置后,一个事务对应着一个类-->
<bean id="userManager" parent="transactionBese">
<property name="target" ref="userManagerBase"></property>
</bean>
</beans>
(5)在全局配置文件中将spring注册组件的配置注入
springAnnotation-core.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>
<beans>
<import resource="classpath*:com/tgb/web/controller/spring/springAnnotation-import.xml"/>
</beans>
6、web.xml文件中注入config包下的三个配置文件
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/springAnnotation-*.xml</param-value>
</context-param>
7、jsp页面
addUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function addUser(){
var form = document.forms[0];
form.action="/springMVC11/user/addUser";
form.method="post";
form.submit();
}
</script>
</head>
<body>
<h>添加用户</h>
<form name="userForm" action="">
姓名:<input type="text" name="userName">
年龄:<input type="text" name="age">
<input type="button" value="添加" onclick="addUser()">
</form>
</body>
</html>
8、项目目录树
四、示例:SSH框架实现查询
1、dao层
(1)IUserDAO中加入查询接口
package com.tgb.web.controller.dao;
public interface IUserDAO {
public List<User> getAllUser();
}
(2)UserDAO中实现该接口
使用了hql语句查询
package com.tgb.web.controller.dao;
public class UserDAO implements IUserDAO {
//有了sessionFactory就可以去操作数据库了
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public List<User> getAllUser() {
//使用HQL语句查询,方便快捷
String hql = "from User";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
return query.list();
}
}
2、service层
(1)IUserManager中加入查询接口
package com.tgb.web.controller.service;
public interface IUserManager {
public List<User> getAllUser();
}
(2)UserManager中调用UserDAO的方法
package com.tgb.web.controller.service;
public class UserManager implements IUserManager {
//将Dao层的userDao注入进来
private IUserDAO userDao;
public void setUserDao(IUserDAO userDao) {
this.userDao = userDao;
}
@Override
public List<User> getAllUser() {
return userDao.getAllUser();
}
}
3、controller中建立页面与方法的关系
package com.tgb.web.controller;
@Controller
@RequestMapping("/user")
public class UserController {
//注入userManager
@Resource(name="userManager")
private IUserManager userManager;
@RequestMapping("/getAllUser")
public String getAllUser(HttpServletRequest request){
List<User> user = userManager.getAllUser();
request.setAttribute("user", user);
return "/userManager";
}
}
4、编写查询所有用户的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
</script>
</head>
<body>
<table border="1">
<tbody>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
<c:if test="${!empty user }">
<c:forEach items="${user }" var="u">
<tr>
<!--显示姓名和年龄-->
<td>${u.userName }</td>
<td>${u.age }</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
</body>
</html>
5、配置文件加入配置
web.xml
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
五、总结
SSH框架分了这么多层,在开发时要把每个层的职责搞清楚,在对应的层写对应的代码,这样写出的代码才真正符合MVC设计理念。
1、JSP页面这些前端逻辑,不写数据处理逻辑;
2、controller页面主要负责页面与方法的定向,连接View和Model,当然有些判断可以在controller端实现,比如,一个用户登录功能,用户填写用户名和密码后点击登录,controller可以判断用户名是否为空、密码长度是否符合规则等这种原则性的规定是否符合。
3、service层是实现业务逻辑的关键层,它负责将前端的需求拆分成对数据库的增删改查,然后调用DAO层的增删改查方法;
4、Dao层只实现比较基本的增删改查,复杂的逻辑交给service去实现;
5、Entity层就是简单的创建javaBean,然后是get和set方法。