Spring4+SpringMVC+Hibernate4整合入门与实例
配置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整合入门与实例的更多相关文章
- spring4+springmvc+hibernate4 demo
来自 CSDN . 其实下面的更好:加入了maven集成.Spring4 MVC Hibernate4集成 下面也是一篇讲的很详细的文章: hibernate4无法保存数据 而自己遇到的hiberna ...
- Spring4 SpringMVC Hibernate4 Freemaker 整合样例
更正改动(2014-05-30 13:47:22):有的IDE中web.xml会报这个错: cvc-complex-type.2.4.a: Invalid content was found star ...
- Spring4 SpringMVC Hibernate4 Freemaker 集成示例
变更更正(2014-05-30 13:47:22):一些IDE在web.xml我们会报告这个错误: cvc-complex-type.2.4.a: Invalid content was found ...
- Spring4 与 Hibernate4 整合过程中的问题记录
Spring4使用注解配置,很方便也很有趣,就是有一些坑需要自己去发现和解决,笔者列出自己在使用过程中遇到的问题,希望对您有所帮助. 1.如果使用hibernate.cfg.xml配置文件配置Hibe ...
- spring+springmvc+ibatis整合注解方式实例【转】
源自-----> http://shaohan126448.iteye.com/blog/2033563 (1)web.xml文件(Tomcat使用) 服务器根据配置内容初始化spring框架, ...
- spring+springmvc+ibatis整合注解方式实例
需求说明 实现用户通过数据库验证登录需求.採用 Myeclipse+Tomcat 6.0+Mysql 5.0+JDK 1.6 2.数据库表 开发所用是Mysql数据库,仅仅建立单张用户表T_USER, ...
- spring4和hibernate4整合的步骤
基本的整合步骤如下: 由于在spring中可以直接实现自动装配bean对象,所以可以直接将hibernate中的配置属性移植过来: 1. 装配dataSource对象 <!-- 配置数据源 -- ...
- Spring4+SpringMVC+MyBatis整合思路(山东数漫江湖)
1.Spring框架的搭建 这个很简单,只需要web容器中注册org.springframework.web.context.ContextLoaderListener,并指定spring加载配置文件 ...
- Maven+SpringMVC+Mybatis整合入门Demo
1 数据库准备 (1)建立一个名为mytest的数据库 (2)创建表 CREATE TABLE `t_user` ( `USER_ID` int(11) NOT NULL AUTO_INCREMENT ...
随机推荐
- js,jq,php使用正则方法
1.js使用正则表达式案例: <script> var str=”543535364565@qq.com”; var res=“/^\d*@(QQ|qq|136)\.(com|cn)$/” ...
- Java-构造一个字符串
实用StringBuffer构造字符串 package com.tj; public class MyClass implements Cloneable { public static void m ...
- luogu3698 [CQOI2017]小Q的棋盘
最长链是根节点到深度最深的结点的路径. 显然,要么直接走最长链,要么兜兜转转几个圈圈再走最长链,而最长链以外的结点因为要"兜圈",所以要经过两次. #include <ios ...
- 异常System.Threading.Thread.AbortInternal
异常信息: System.Threading.ThreadAbortException: 正在中止线程. 在 System.Threading.Thread.AbortInternal() 在 Sys ...
- BZOJ 4503 两个串 ——FFT
[题目分析] 定义两个字符之间的距离为 (ai-bi)^2*ai*bi 如果能够匹配,从i到i+m的位置的和一定为0 但这和暴力没有什么区别. 发现把b字符串反过来就可以卷积用FFT了. 听说KMP+ ...
- [HNOI2010]CHORUS 合唱队 (区间DP)
题目描述 对于一个包含 NN 个整数的数列 AA ,我们可以把它的所有元素加入一个双头队列 BB . 首先 A1A1 作为队列的唯一元素,然后依次加入 A2∼ANA2∼AN ,如果 Ai<Ai− ...
- 【强化学习】百度云BCC openai gym 环境配置
openai gym是RL算法的测试床.为了直观和便于调试,我们需要可视化界面.然而远程服务器使用openGL的问题比较棘手,这篇博客记录在百度云BCC上配置openai gym环境的注意事项. 按照 ...
- LightOJ1125 Divisible Group Sums
Divisible Group Sums Given a list of N numbers you will be allowed to choose any M of them. So you c ...
- zoj 2562 反素数
题目大意:求n范围内最大的反素数(反素数定义:f(x)表示x的因子数,f(x)>f(x1) (0<x1<x)) x用质因数形式为:x=a1^p1*a2^p2......an^pn(a ...
- UOJ#370. 【UR #17】滑稽树上滑稽果
$n \leq 1e5$个点,每个点有个权值$a_i \leq 2e5$.现将点连成树,每个点$i$的链接代价为$a_i \ \ and \ \ i父亲的代价$,这里的$and$是二进制按位与,求最小 ...