配置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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>myweb</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/jsp/register.jsp</welcome-file>
<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
</welcome-file-list>
<!-- 载入全部的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring-*.xml</param-value>
</context-param>
<!-- 配置Spring监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置字符集 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/</url-pattern> <!-- 配置Session -->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>flushMode</param-name>
<param-value>AUTO</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping> <!-- 配置SpringMVC -->
<servlet>
<description>myweb</description>
<display-name>myweb</display-name>
<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/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

SpringMVC中Bean的配置spring-mvc.xml

<?

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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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.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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启Spring MVC注解 -->
<mvc:annotation-driven />
<!-- 处理静态资源 -->
<mvc:resources location="/resources" mapping="/resources/**" />
<!-- 打开Spring的Annotation支持 -->
<context:annotation-config />
<!-- 注解扫描包 -->
<context:component-scan base-package="com.myweb.controller" />
<context:component-scan base-package="com.myweb.dao.imp" />
<context:component-scan base-package="com.myweb.service.imp" />
<!-- 配置SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- <property name="dataSource" ref="dataSource" /> -->
<property name="configLocation" value="classpath:config/hibernate.cfg.xml" />
<property name="packagesToScan" value="com.myweb.entity" />
</bean>
<!-- 配置Dao要注入的hibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置Spring的事务处理 -->
<!-- 创建事务管理器 -->
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置AOP。Spring是通过AOP来进行事务管理的 -->
<aop:config>
<!-- 设置pointCut表示哪些方法要增加事务处理 -->
<!-- 下面的事务是声明在DAO中,可是通常都会在Service来处理多个业务对象逻辑的关系,注入删除,更新等,此时假设在运行了一个步骤之后抛出异常
就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service。这也就是Spring所提供的一个很方便的工具。声明式事务 -->
<aop:pointcut id="allMethods" expression="execution(* com.myweb.service.*.*(..))" />
<!-- 通过advisor来确定详细要增加事务控制的方法 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" />
</aop:config>
<!-- 配置哪些方法要增加事务控制 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- 让全部的方法都增加事务管理,为了提高效率。能够把一些查询之类的方法设置为仅仅读的事务 -->
<tx:method name="*" propagation="REQUIRED" read-only="true" />
<!-- 下面方法都是可能设计改动的方法。就无法设置为仅仅读 -->
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- 开启事务注解 -->
<tx:annotation-driven />
<!-- 默认的视图解析器ViewResolver -->
<bean id="defaultViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

Hibernate的配置hibernate.cfg.xml

<?

xml version="1.0" encoding="UTF-8"?

>
<!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>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost/myweb
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
jiangyu
</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<!-- ddl语句自己主动建表 -->
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="jdbc.fetch_size">50</property>
<property name="jdbc.batch_size">30</property>
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquireRetryAttempts">30</property>
<property name="hibernate.c3p0.acquireIncrement">2</property>
<property name="hibernate.c3p0.checkoutTimeout">30000</property>
<property name="hibernate.c3p0.idleConnectionTestPeriod">120</property>
<property name="hibernate.c3p0.maxIdleTime">180</property>
<property name="hibernate.c3p0.initialPoolSize">3</property>
<property name="hibernate.c3p0.maxPoolSize">50</property>
<property name="hibernate.c3p0.minPoolSize">1</property>
<property name="hibernate.c3p0.maxStatements">0</property>
<!-- XML配置映射关系 <mapping resource="Employee.hbm.xml" /> -->
<!-- 注冊ORM映射文件 -->
<!-- spring不起作用 <mapping package="com.myweb.entity"/> -->
</session-factory>
</hibernate-configuration>

实体层

package com.myweb.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "w_user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(length = 50)
private String username;
@Column(length = 20)
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

数据訪问层(DAO层)

接口:

package com.myweb.dao;
import com.myweb.entity.User;
public interface UserDao {
User save(User user);
}

实现:

package com.myweb.dao.imp;

import javax.inject.Inject;

import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository; import com.myweb.dao.UserDao;
import com.myweb.entity.User; @Repository
public class UserDaoImp implements UserDao {
@Inject
private HibernateTemplate template; @Override
public User save(User user) {
// TODO Auto-generated method stub template.save(user); return template.load(User.class, user.getId());
} }

服务层(Service层)

接口:

package com.myweb.service;
import com.myweb.entity.User;
public interface UserService {
User save(User user);
}

实现:

package com.myweb.service.imp;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import com.myweb.dao.UserDao;
import com.myweb.entity.User;
import com.myweb.service.UserService;
@Service
public class UserServiceImp implements UserService {
@Inject
private UserDao userDao;
@Override
public User save(User user) {
// TODO Auto-generated method stub
return userDao.save(user);
}
}

控制层(Controller层)

package com.myweb.controller;
import javax.inject.Inject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.myweb.entity.User;
import com.myweb.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Inject
private UserService userService;
@RequestMapping(value = "/register.do", method = RequestMethod.POST)
public String register(User user) {
userService.save(user);
return "login";
}
@RequestMapping(value = "/login.do", method = RequestMethod.POST)
public String login(@ModelAttribute("user") User user) {
return "self";
}
}

视图成(View层)

register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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>
<form action="/myweb/user/register.do" method="post">
用户名:<input type="text" name="username" /><br /> 密码:<input
type="password" name="password"><br /> <input type="submit"
value="提交">
</form>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
<title>登录</title>
</head>
<body>
<form action="/myweb/user/login.do" method="post">
用户名:<input type="text" name="username"><br /> 密码:<input
type="password" name="password"><br /> <input type="submit"
value="登录">
</form>
</body>
</html>

self.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>欢迎你!。! ${user.username}
</body>
</html>

Spring4+SpringMVC+Hibernate4整合入门与实例的更多相关文章

  1. spring4+springmvc+hibernate4 demo

    来自 CSDN . 其实下面的更好:加入了maven集成.Spring4 MVC Hibernate4集成 下面也是一篇讲的很详细的文章: hibernate4无法保存数据 而自己遇到的hiberna ...

  2. Spring4 SpringMVC Hibernate4 Freemaker 整合样例

    更正改动(2014-05-30 13:47:22):有的IDE中web.xml会报这个错: cvc-complex-type.2.4.a: Invalid content was found star ...

  3. Spring4 SpringMVC Hibernate4 Freemaker 集成示例

    变更更正(2014-05-30 13:47:22):一些IDE在web.xml我们会报告这个错误: cvc-complex-type.2.4.a: Invalid content was found ...

  4. Spring4 与 Hibernate4 整合过程中的问题记录

    Spring4使用注解配置,很方便也很有趣,就是有一些坑需要自己去发现和解决,笔者列出自己在使用过程中遇到的问题,希望对您有所帮助. 1.如果使用hibernate.cfg.xml配置文件配置Hibe ...

  5. spring+springmvc+ibatis整合注解方式实例【转】

    源自-----> http://shaohan126448.iteye.com/blog/2033563 (1)web.xml文件(Tomcat使用) 服务器根据配置内容初始化spring框架, ...

  6. spring+springmvc+ibatis整合注解方式实例

    需求说明 实现用户通过数据库验证登录需求.採用 Myeclipse+Tomcat 6.0+Mysql 5.0+JDK 1.6 2.数据库表 开发所用是Mysql数据库,仅仅建立单张用户表T_USER, ...

  7. spring4和hibernate4整合的步骤

    基本的整合步骤如下: 由于在spring中可以直接实现自动装配bean对象,所以可以直接将hibernate中的配置属性移植过来: 1. 装配dataSource对象 <!-- 配置数据源 -- ...

  8. Spring4+SpringMVC+MyBatis整合思路(山东数漫江湖)

    1.Spring框架的搭建 这个很简单,只需要web容器中注册org.springframework.web.context.ContextLoaderListener,并指定spring加载配置文件 ...

  9. Maven+SpringMVC+Mybatis整合入门Demo

    1 数据库准备 (1)建立一个名为mytest的数据库 (2)创建表 CREATE TABLE `t_user` ( `USER_ID` int(11) NOT NULL AUTO_INCREMENT ...

随机推荐

  1. include/autoconfig.mk

    把autoconfig.mk和/include/configs/ $(obj)include/autoconf.mk.dep: $(obj)include/config.h include/commo ...

  2. SQL Server on Red Hat Enterprise Linux

    本文从零开始一步一步介绍如何在Red Hat Enterprise Linux上搭建SQL Server 2017,包括安装系统.安装SQL等相关步骤和方法(仅供测试学习之用,基础篇). 一.   创 ...

  3. Linux基础命令详解-2

    本篇详解的命令有以下30个 1.rmdir 功能:删除一个空目录   2.telnet 功能:使用telnet协议连接到主机的指定端口 3.vim 功能:编辑器之神 vim三种模式的功能及其转换   ...

  4. Webstrom卡顿问题解决

    1.设置node_modules 打开项目,新建node_modules空文件夹,然后右击选择Mark Directory as,选择Excluded. 2.设置ingore文件 files-> ...

  5. C# 字符串型转数字型

    // 当需要将字符串格式的数字转为数字时候,我们会用到的函数为Convert.ToDouble(),// 然而当你的字符串为49,9时,由于包含了逗号,函数会将逗号忽略,直接转为499,// 所以我们 ...

  6. Leetcode 336.回文对

    回文对 给定一组唯一的单词, 找出所有不同 的索引对(i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串. 示例 1: 输入: ["abcd&quo ...

  7. HDU-3743 Minimum Sum,划分树模板

    Minimum Sum 被这个题坑了一下午,原来只需找一个最中间的数即可,我以为是平均数. 题意:找一个数使得这个数和区间内所有数的差的绝对值最小.输出最小值. 开始用线段树来了一发果断T了,然后各种 ...

  8. 九度oj 题目1283:第一个只出现一次的字符

    题目描述: 在一个字符串(1<=字符串长度<=10000,全部由大写字母组成)中找到第一个只出现一次的字符. 输入: 输入有多组数据 每一组输入一个字符串. 输出: 输出第一个只出现一次的 ...

  9. 02-offsetLeft和offsetTop

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  10. 分析Tapjoy的模式—分发用于ios设备的企业级应用程序

    下面简单介绍下Tapjoy的模式,供大家参考: Tapjoy最初的合作模式:“按安装奖励”(pay-per-install) Tapjoy利用非常成功的奖励性下载模式影响了App Store的免费游戏 ...