SpringMVC、spring、hibernate简单整合实例(附程序代码)

开发工具:myEclipse2014

java版本:1.8

数据库:mysql5.0

创建工程结构:

配置依赖包:

使用PowerDesigner创建数据库原型:

选择mysql5.0:

创建表,主键自增:

添加自增:

导出数据库:

查看生成脚本,选择导出位置:

使用数据库管理工具:Navicat for MySQL创建数据库springmvc:

打开命令窗口:

运行脚本:

刷新查看表创建情况:

使用hibernate生成逆向工程:

1.创建hibernate门面:

2.选择创建版本:

3.刷新工程目录,删除默认生成文件:

4.选择DB Browser 创建数据库连接:

5.选择项目数据库表springmvc-person创建逆向工程:

6.选择要生成的路径、包:

7.刷新目录,检查是否生成实体类和映射文件:

8.将配置文件放到创建的config-com.rl.mapping包下,便于统一管理:

创建spring文件:

在config中创建beans.xml,使用注解整合所有的bean:

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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-3.0.xsd 
	http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
	<!-- 配置扫描器 -->
	<context:component-scan base-package="com.rl"/>

	<!-- 指定数据源(使用自带的DriverManagerDataSource数据源) -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!-- 配置属性 -->
		<!-- 配置数据库驱动 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<!-- 配置url -->
		<property name="url" value="jdbc:mysql://localhost:3306/springmvc"/>
		<!-- 配置username -->
		<property name="username" value="root"/>
		<!-- 配置password -->
		<property name="password" value="root"/>
	</bean>
	
	<!-- 配置sessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!-- 关联数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 加载映射(此处使用文件夹形式加载),value:加载的路径mapping文件夹下的所有文件 -->
		<property name="mappingDirectoryLocations" value="classpath:com.rl.mapping.*"></property>
		<!-- 配置hibernate本身的属性(是否展示SQL、方言、更新策略等) -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.Dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl">update</prop>
			</props>
		</property>
	</bean>
	
	<!-- 配置事务 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<!-- 配置依赖(依赖sessionFactory) -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<!-- 配置通知(事务连接点消息通知)、关联事务 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<!-- 当事务到达连接点时,对事务进行传播 -->
		<tx:attributes>
			<!-- 对事务保存方法,进行统一提交和回滚(防止脏数据) -->
			<tx:method name="save*" propagation="REQUIRED"/>
			<!-- 对事务查询方法,进行只读设置 -->
			<tx:method name="select*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 对AOP界面配置 -->
	<aop:config>
		<!-- 关联通知,当切点:execution表达式(范围:第一个*代表返回值类型、..*代表(..)所有子包(*)所有类、.*所有方法、(..)所有参数) -->
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.rl.service..*.*(..))"/>
	</aop:config>
</beans> 
 

对代码进行编写:

1.创建dao包:com.rl.dao

2.在dao中创建PersonDao接口:

package com.rl.dao;

import cn.tx.model.Person;

public interface PersonDao {
	
	//创建保存方法
	public void savePerson(Person person);

}

3.在dao中创建com.rl.dao.Impl包,包下创建PersonDaoImpl类,实现PersonDao接口,继承HibernateDaoSupport:

4.在PersonDaoImpl中实现具体的方法,注意在hibernate模板中没有注解,需要创建一个setMeSessionFactory方法实现父类中的方法,在savePerson中调用:

package com.rl.dao.Impl;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import cn.tx.model.Person;

import com.rl.dao.PersonDao;
//添加Repository注解
@Repository
public class PersonDaoImpl extends HibernateDaoSupport implements PersonDao {

	//在hibernateTemplate中没有注解方法,需要添加一个方法调用注解
	@Autowired
	public void setMeSessionFactory(SessionFactory sessionFactory){
		//调用父类中的SessionFactory方法
		super.setSessionFactory(sessionFactory);
	}
	public void savePerson(Person person) {
		//使用Hibernate模板
		this.getHibernateTemplate().save(person);
	}

}

5.创建service包:com.rl.service,创建PersonService接口,创建接口方法savePerson:

6.提供Service的实现类:创建com.rl.service.Impl包,创建PersonServiceImpl类,实现PersonService接口:

7.添加savePerson方法,注意不要忘记添加注解:

package com.rl.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tx.model.Person;

import com.rl.dao.PersonDao;
import com.rl.service.PersonService;
@Service
public class PersonServiceImpl implements PersonService {

	//注入Dao(使用注解不用额外提供set方法)
	@Autowired
	private PersonDao personDao;
	
	
	public void savePerson(Person person) {
		personDao.savePerson(person);
	}

}

8.创建controller:创建com.rl.controller包,包下创建PersonController类:

9.在PersonController中实现跳转方法和添加方法:

package com.rl.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.tx.model.Person;

import com.rl.service.PersonService;

@Controller
@RequestMapping("/person")
public class PersonController {
	
	//注入service
	@Autowired
	private PersonService personService;
	
	//设置跳转到的指定界面的方法
	@RequestMapping("/toForm.do")
	public String toForm(){
		return "form";
	}
	
	//设置添加方法
	@RequestMapping("/save.do")
	public String save(Person person){
		personService.savePerson(person);
		return "success";
	}
}

10.处理页面表单:

在WEB-INF-jsp下创建form.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>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <form action="person/save.do" method="post">
    	name:<input name="name" type="text"><br>
    	gender:<input name="gender" type="text"><br>
    	address:<input name="address" type="text"><br>
    	birthday:<input name="birthday" type="text"><br>
    	
    	<input type="submit" value="submit">
    </form>
  </body>
</html>

web.xml配置:

<?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">
<!-- 配置主键 -->
<servlet>
	<servlet-name>springmvc</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<!-- 配置文件位置 -->
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<!-- 指定springmvc配置文件路径 -->
		<param-value>classpath:springmvc.xml</param-value>
	</init-param>
</servlet>
<!-- 映射文件 -->
<servlet-mapping>
	<servlet-name>springmvc</servlet-name>
	<!-- 添加要拦截的请求,和struts不同(不能使用/*的方法,使用*.xxx,按规范使用*.do) -->
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

<!-- 加载spring文件 -->
<listener>
	<!-- 文件名记不住可以在类下写个ContextLoader,拿到包路径 -->
	<listener-class>org.springframework.web.context.ContextLoader</listener-class>
</listener>
<!-- 修改路径 -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<!-- 指定spring配置文件路径 -->
	<param-value>classpath:beans.xml</param-value>
</context-param>
</web-app>

config-springmvc.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 
	springmvc配置文件命名规则:
		使用web.xml中“<servlet-name>”名字加上-Servlet.xml
		默认创建在WEB-INF下
		头信息和spring配置方法一致
 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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-3.0.xsd 
	http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd 
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">

	<!-- mvc注解驱动 -->
	<!-- <mvc:annotation-driven/> -->
	
	<!-- 
		配置扫描器,配置扫描器以后,注解驱动会自动添加,所以无需额外添加 
		@Controller
		@Service
		@repository
		@Component(用于无法分层的类,但也想spring来管理)
		@AutoWired,@Resources
	-->
	<context:component-scan base-package="com.rl.controller"/>

	<!-- 配置视图解析器(用InternalResourceViewResolver类,来解析视图) -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 为视图解析器配置前缀(很多jsp放在比较深的目录,很多目录是公用的,每次重复写浪费资源,增加冗余度) -->
		<property name="prefix" value="/WEB-INF/jsp/"></property>
		
		<!-- 为视图解析器配置后缀(所有视图的后缀名) -->
		<property name="suffix" value=".jsp"></property>
	</bean>
</beans> 
 

11.添加日志,在练习中要养成良好的习惯添加日志:

在config在添加log4j.properties:

log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

将项目部署在Tomcat中,启动项目在浏览中访问http://localhost:8080/ssh2/person/toForm.do

出现错误:

检查控制台,

查看错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': 
Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field:
private com.rl.service.PersonService com.rl.controller.PersonController.personService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No matching bean of type [com.rl.service.PersonService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

排查发现web.xml下的listener包配置错误为:ContextLoader:应该使用:ContextLoaderListener

修改代码web.xml中:

重启Tomcat:

界面展示成功,在表单中添加信息:

提交表单:

报错:在beans.xml中加载劲射文件不能识别.要使用/:

修改代码:

重启服务器,填写表单:

提交成功了,查看数据库中是否有person值:

数据中展示数据成功,一般情况下,springmvc都是和mybatis整合。

                          个人学习笔记(拓薪教育学员),请勿转载。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值