Spring4.3整合Hibernate4.3搭建Spring MVC
1,web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>chauvet</display-name> <!-- 工程的根名称 -->
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>chauvet.root</param-value>
</context-param> <!-- loj4j的配置文件路径 和log4j的监听器-->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener> <!-- 设置Spring容器加载配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/spring/applicationContext.xml
,classpath:/spring/spring-connection.xml
<!-- ,classpath:/spring/spring-hibernate.xml
,classpath:/spring/spring-c3p0.xml-->
</param-value>
</context-param> <!-- spring IOC容器的配置文件位置和IOC容器的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- spring mvc的核心转发器 和转发的规则 -->
<servlet>
<servlet-name>chauvet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 默认/WEB-INF/[servlet名字]-servlet.xml加载上下文, 如果配置了contextConfigLocation参数,将使用classpath:/spring/chauvet-servlet.xml加载上下文 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/chauvet-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>chauvet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 全局过滤器,主要用来判断登录、鉴权、编码转换,只过滤 /的动态资源 -->
<filter>
<filter-name>allFilter</filter-name>
<filter-class>com.chauvet.utils.AllFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>allFilter</filter-name>
<!-- 和spring核心转发器过滤规则相同 -->
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 配置session超时时间 -->
<session-config>
<session-timeout>30</session-timeout>
</session-config> <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
2.applicationContext.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:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
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-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-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/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"> <!-- bean管理 --> <!-- service --> <!-- dao --> <!-- util --> </beans>
3.chauvet-servlet.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:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- spring核心配置 --> <!-- 启动自动扫描该包下所有的Bean(例如@Controller) -->
<context:component-scan base-package="com.chauvet" /> <!-- 启用注解 -->
<mvc:annotation-driven /> <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器 -->
<!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors> <!-- 允许对静态资源文件的直接访问 -->
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" /> <!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /> <!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean> <!-- Resolves view names to protected .jsp resources within the /WEB-INF/chauvet directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/chauvet/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
4.spring-connection.xml(通过注入的方式为SessionFactory注入hibernate的配置信息,从而省去hibernate配置文件)
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" 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/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:property-placeholder location="classpath:/jdbc.properties" /> <!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="${jdbc.driverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.pass}"></property>
</bean> <!-- 配置SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.chauvet.po</value>
</list>
</property>
</bean> <!-- 配置一个事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean> <!-- 配置事务,使用代理的方式 -->
<bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>
<prop key="del*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
</beans>
5.Controller
package com.chauvet.controller; import java.io.IOException;
import java.util.Date;
import java.util.List; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; @Controller
@RequestMapping("/login")
public class LoginController extends BaseController {
/**
* 跳转到登录页面
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping(value = "/gotoLogin", method = RequestMethod.GET)
public ModelAndView gotoLogin(HttpServletRequest request,HttpServletResponse response){ return new ModelAndView("login/gotoLogin");
} }
6.index.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head></head>
<body>
<script type="text/javascript">document.location.href='login/gotoLogin';</script>
</body>
</html>
7.BaseDao.java
package com.chauvet.dao.impl; import java.util.List;
import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction; public class BaseDao { /**
* log4j日志记录
*/
private Logger log = Logger.getLogger(this.getClass()); @Resource
private SessionFactory sessionFactory;
public Session getSession(){
// return sessionFactory.openSession(); // 需要自己关闭session
/***
* getCurrentSession()的两个特性:
* 1、在没有session的情况下不会自动创建一个
* 2、会自动关闭session
*/
return sessionFactory.getCurrentSession();
} /***
* 保存
* @param obj
*/
public void save(Object obj){
getSession().save(obj);
}
/**
* 根据表名查出这个表下的所有记录
* @param <T> 泛型
* @param tableName 表名
* @return List<T>
*/
public <T> List<T> findAll(String tableName) {
log.debug("findAll:"+tableName);
String hql = "from " + tableName + " ";
return findByHql(hql);
}
}
8.PO User.java
package com.chauvet.po; import java.util.Date; import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType; import org.hibernate.annotations.GenericGenerator; @Entity
@Table(name="user")
public class User{
private String id; //主键,自动生成UUID
private String name;//名字
private int sex;//性别
private int age;//年龄
private Date registerTime;//注册时间
private Date createTime;//创建时间 @Id
@GenericGenerator(name="systemUUID",strategy="uuid")
@GeneratedValue(generator="systemUUID")
@Column(name = "id", insertable = true, updatable = true, nullable = false,length = 32)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
} @Column(name="name",length=32)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} @Column(name="sex")
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
} @Column(name="age")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} @Temporal(TemporalType.TIMESTAMP)
@Column(name="createTime")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
} @Temporal(TemporalType.TIMESTAMP)
@Column(name="registerTime")
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
}
Spring4.3整合Hibernate4.3搭建Spring MVC的更多相关文章
- MAC OS X El CAPITAN 搭建SPRING MVC (1)- 目录、包名、创建web.xml
一. 下载STS(Spring Tool Suite) 官方地址:http://spring.io/tools/sts 下载spring tool suite for mac 最新版本.这个IDE是很 ...
- 零基础搭建 spring mvc 4 项目(本文基于 Servlet 3.0)
作者各必备工具的版本如下: Tomcat:apache-tomcat-7.0.63 (下载链接) Java EE - Eclipse:Luna Service Release 1 v4.4.1 (下载 ...
- Spring MVC复习 —— 搭建Spring MVC项目
Spring MVC复习 -- 搭建Spring MVC项目 摘要:这篇笔记是关于Spring MVC的复习,内容是如何搭建Spring MVC项目. 让我们快速的搭建一个Spring MVC ...
- 从零开始学 Java - 搭建 Spring MVC 框架
没有什么比一个时代的没落更令人伤感的了 整个社会和人都在追求创新.进步.成长,没有人愿意停步不前,一个个老事物慢慢从我们生活中消失掉真的令人那么伤感么?或者说被取代?我想有些是的,但有些东西其实并不是 ...
- 一、Spring MVC起步——IntelliJ IDEA 搭建Spring MVC环境(手把手搭建)
本机环境: JDK 1.7 IntelliJ IDEA 2017.2 1.新建项目 Create New Project 选择Spring MVC 填写项目名和项目存放位置 然后点击Fin ...
- Spring MVC篇一、搭建Spring MVC框架
本项目旨在搭建一个简单的Spring MVC框架,了解Spring MVC的基础配置等内容. 一.项目结构 本项目使用idea intellij创建,配合maven管理.整体的目录结构如图: 其中ja ...
- 搭建spring mvc项目
在之前搭建maven项目这篇的基础上继续集成,引入spring mvc支持 一.添加jar包引用 修改pom.xml文件,加入:(其他关联的jar包maven会自动引用) <!-- 项目属性 - ...
- [转载]快速搭建Spring MVC 4开发环境
(一)工作环境准备: JDK 1.7 Eclipse Kepler Apache Tomcat 8.0 (二)在Eclipse中新建Maven工程,在Archetype类型中,选择“maven-arc ...
- eclipse luna maven搭建spring mvc
1. 环境配置 a) Java 1.7 b) Eclipse luna c) Maven3.2.5 d) Spring 4.1.4 2. ...
随机推荐
- 深入理解Java中配置环境变量
深入理解Java中配置环境变量 配置的目的: 本来只在安装JDK的bin目下能运行java.exe,javac.exe,jar.exe,javadoc.exe等Java开发工具包命令,我们现在想让在所 ...
- English trip V1 - 辅导课 VOCABULARY BRUSH UP(1-6) 词汇刷新 SA:Winona
1.How Do you Feel Now? 形容词 adj. = adjective Describe people and thi ...
- UVA-10273 Cyborg Genes (DP)
题目大意:给两个字符串a.b,找出一个最短的字符串c,使得这两个字符串都是c的子序列.只需找出p的最小长度和最小长度时的个数. 题目分析:与LCS问题类似.最小长度的状态转移方程,dp(i,j)=mi ...
- 基础最短路(模板 bellman_ford)
Description 在每年的校赛里,所有进入决赛的同学都会获得一件很漂亮的t-shirt.但是每当我们的工作人员把上百件的衣服从商店运回到赛场的时候,却是非常累的!所以现在他们想要寻找最短的从商店 ...
- 计时(.NET)
using System.Diagnostics; // 开始计时 Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // 要计时的操 ...
- windows下面使用nginx配置web注意问题
1.路径一定要用两个反斜杠进行转义,如果只用单个反斜杠,遇到\n就识别不到路径了,例如下图中的\news中包含\n
- spark 资源参数调优
资源参数调优 了解完了Spark作业运行的基本原理之后,对资源相关的参数就容易理解了.所谓的Spark资源参数调优,其实主要就是对Spark运行过程中各个使用资源的地方,通过调节各种参数,来优化资源使 ...
- 【webpack系列】1 What is webpack?
什么是webpack? 现今的网页可以看做是功能丰富的应用,拥有着复杂的js代码和一大堆依赖包.为了简化开发的复杂程度,有了很多好用的实践方法 模块化 让我们可以把复杂的程序细化为小的文件 类似于Ty ...
- en_o out1
1● o əʊ ɒ ə ɔː ʌ ʊ: 2● oor ʊə ɔː 3● oo u u: 4● or ɜː ə ɔː 5● oar ore ɔː 6● ow əʊ aʊ ...
- java之args[0]
java程序有一个主方法main方法,是这样的public static void main(String [] args)args[0]就是用命令行javac编译后java运行java程序时,传入的 ...