Spring MVC框架搭建(spring4.0+hibernate4.3)

Spring下载地址: http://repo.springsource.org/libs-release-local/org/springframework/spring/

 

Hhibernate下载地址: http://sourceforge.net/projects/hibernate/files/

 

 

1. jar包引入

 

spring-framework-4.0.0.RELEASE18个):libs文件夹中除却spring-build-src-4.0.0.RELEASE.jarspring-framework-bom-4.0.0.RELEASE.jarspring-messaging-4.0.0.RELEASE.jarspring-websocket-4.0.0.RELEASE.jar四个jar包,其它全部导入,共18jar包。

 

spring依赖包aopalliance.jarcommons-logging-1.1.1.jarlog4j-1.2.15.jar

 

hibernate-release-4.3.0.Final10个):lib文件夹中required文件夹下的10jar包。

 

hibernate 缓存包(4个)ehcache-core-2.4.3.jarhibernate-ehcache-4.3.0.Final.jarslf4j-api-1.7.5.jarslf4j-log4j12-1.7.5.jar

 

其他工具包(9个)commons-fileupload-1.3.jarcommons-io-2.4.jarcommons-lang3-3.2.jarcommons-beanutils-1.9.0.jarcommons-dbcp-1.4.jarcommons-pool-1.6.jarpager-taglib.jarcommons-collections-3.2.1.jarmysql-connector-java-5.1.27.jar

 

 

  1. 配置文件

(1) web.xml配置

 

关于filter的使用,可以参考:Spring MVC过滤器-登录过滤

 

<?xmlversion="1.0" encoding="UTF-8"?>
<web-appversion="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>SpringMVC</display-name>        
<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>
 
<!--加载spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/applicationContext-*.xml</param-value>
</context-param>
 
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
<!--springMVC 框架加载服务 -->
<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/applicationContext-springmvc.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>
 
<!--filter配置,解决编码问题 -->
<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>
<!--encoding filter for jsp page -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 
<!--sessionFilter配置,解决session过滤问题 -->
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>com.springmvc.core.web.filter.SessionFilter</filter-class>
<init-param>
<param-name>notFilter</param-name>
<param-value>/skin/,/index.jsp, /mvc/index, /login, /logout</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 
<!--OpenSessionInViewFilter配置,解决延迟加载时Session会关闭的问题 -->
<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>
 
<!--配置PagerFilter,用来获取分页数据 -->
<filter>
<filter-name>pagerFilter</filter-name>
<filter-class>com.springmvc.core.web.filter.PagerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>pagerFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 
<!--session time out 23*60 -->
<session-config> 
        <session-timeout>1380</session-timeout> 
          </session-config>
</web-app>

 

(2)applicationContext-springmvc.xml配置

 

此为spring核心配置文件

关于spring使用annotation注解,可以参考:1. 基于注解的 Spring MVC 简单入门  2. 基于注解的SpringMVC

 

<?xmlversion="1.0" encoding="UTF-8"?>
<!--
-DispatcherServlet application context for DeclareOnline's web tier.
 
springmvc 的 DispatcherServlet 对应的配置文件
-->
<beansxmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
   xmlns:p="http://www.springframework.org/schema/p" 
   xmlns:context="http://www.springframework.org/schema/context" 
   xmlns:mvc="http://www.springframework.org/schema/mvc" 
    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/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
 
 
<!--
-The controllers are autodetected POJOs labeled with the @Controller annotation.
Springmvc将在该路径下寻找Controller(有Controller注释的类)
-->
<context:component-scanbase-package="com.springmvc.*"/>
 
<!--开启注解 -->
<mvc:annotation-driven/>
<!--使用依赖控制器类名字的惯例,将URI映射到控制器(开启注解的另一种方式) -->
<!--
<beanclass="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<beanclass="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
启动SpringMVC的注解功能,完成请求和注解POJO的映射
<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
-->
 
<!--静态资源访问 -->
<mvc:resourceslocation="/skin/" mapping="/skin/**"/> 
 
<!--定义Spring MVC 的模板文件 -->
<beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--支持JSTL -->
<propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/>
<!--模板的路径 -->
<propertyname="prefix" value="/" />
<!--模板文件后缀 -->
<propertyname="suffix" value=".jsp" />
</bean>
 
    <!-- Spring MVC 文件上传配置 -->
    <beanid="multipartResolver"    
         class="org.springframework.web.multipart.commons.CommonsMultipartResolver"    
          p:defaultEncoding="utf-8">  
  <propertyname="maxUploadSize">
<value>10485760000</value>
</property>
<propertyname="maxInMemorySize">
<value>40960</value>
</property>        
 
</bean>
</beans>


 

(3)applicationContext-hibernate.xml配置

 

A. 此文件是spring方式的hibernate连接数据库的配置

 

spring配置数据库连接方式有很多种,可以参考一下: 在Spring中配置DataSource的6种方法

此处使用了Spring利用PropertyPlaceholderConfigurer占位符,参考文章: Spring 利用PropertyPlaceholderConfigurer占位符

 

Spring事务配置的方式也有多中,可以参考: Spring事务配置的五种方式和spring里面事务的传播属性和事务隔离级别

applicationContext-hibernate.xml

<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:util="http://www.springframework.org/schema/util"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
              http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd
              http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd
              http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-2.0.xsd"default-lazy-init="false">
 
<!--======================== property configure本配置文件负责加载变量信息必须在在spring配置文件的最前面加载(第一个加载) ======================== -->
<!--载入properties配置文件,以${key}的方式引用 -->
<beanid="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertyname="locations">
<list>
<value>classpath:conf/mvcdb.properties</value>
</list>
</property>
</bean>
 
<!--========================   dataconfigure   ==========================-->
<!--配置连接池(jdbc方式) -->
<!--<bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName" value="${mvcdb.mysql.driver}"/>
<propertyname="url" value="${mvcdb.mysql.url}"/>
<propertyname="username" value="${mvcdb.mysql.user}"/>
<propertyname="password" value="${mvcdb.mysql.password}"/>
</bean>-->
 
<beanid="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<propertyname="driverClassName">
<value>${mvcdb.mysql.driver}</value>
</property>
<propertyname="url">
<value>${mvcdb.mysql.url}</value>
</property>
<propertyname="username">
<value>${mvcdb.mysql.user}</value>
</property>
<propertyname="password">
<value>${mvcdb.mysql.password}</value>
</property>
<propertyname="initialSize">
<value>${mvcdb.mysql.initialSize}</value>
</property>
<propertyname="maxActive">
<value>${mvcdb.mysql.maxActive}</value>
</property>
    <property name="minIdle">
<value>${mvcdb.mysql.maxActive}</value>
</property>
<propertyname="maxIdle">
<value>${mvcdb.mysql.maxActive}</value>
</property>
<propertyname="maxWait">
<value>${mvcdb.mysql.maxWait}</value>
</property>
<propertyname="testOnBorrow">
<value>${mvcdb.mysql.testOnBorrow}</value>
</property>
                 <propertyname="testWhileIdle">
<value>${mvcdb.mysql.testWhileIdle}</value>
</property>
                 <propertyname="validationQuery">
<value>${mvcdb.mysql.validationQuery}</value>
</property>
</bean>
 
 
<!--配置hibernate 上下文 -->
<beanid="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<propertyname="dataSource" ref="dataSource" />
 
<!--包级扫描 hibernate实体类 -->
<propertyname="configLocations">
  <list>
<!--<value>com.springmvc.*</value> -->
      <value>classpath*:com/springmvc/mvcdev/userInfo/hibernate/hibernate.cfg.userInfo.xml</value>
  </list>
</property>
 
<propertyname="hibernateProperties">
<props>
<propkey="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>
<propkey="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<propkey="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<propkey="hibernate.cache.use_query_cache">false</prop>
<propkey="hibernate.show_sql">true</prop>
<!--<prop key="hibernate.hbm2ddl.auto">update</prop>  -->
<propkey="hibernate.cache.use_second_level_cache">false</prop>
<propkey="hibernate.max_fetch_depth">2</prop>
<propkey="hibernate.jdbc.fetch_size">50</prop>
<propkey="hibernate.jdbc.batch_size">50</prop>
<propkey="hibernate.use_outer_join">false</prop>
<propkey="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
   
    <!-- 配置jdbc事务 -->
<beanid="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<propertyname="sessionFactory">
<reflocal="sessionFactory" />
</property>
</bean>
 
<!--配置启用事务的动态代理 -->
<beanid="baseTransactionProxy"class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"abstract="true">
<propertyname="transactionManager">
<refbean="transactionManager" />
</property>
<propertyname="proxyTargetClass" value="true"/>
<propertyname="transactionAttributes">
<props>
<propkey="insert*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="active*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="end*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="lock*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="unLock*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="update*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="modify*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="remove*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="del*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="add*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="save*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="set*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="exchage*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="sort*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="do*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="undo*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="transact*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="enrolment*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="accept*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="init*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="edit*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="create*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="support*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="active*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="mapping*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="reset*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="change*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="submit*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="draft*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="assign*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="close*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="suspend*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="publish*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="revoke*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="print*">PROPAGATION_REQUIRED,-Exception</prop>                                
<propkey="undeploy*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="suspend*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="resume*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="rand*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="send*">PROPAGATION_REQUIRED,-Exception</prop>
<propkey="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
</beans>


 

B.此文件需要在mvcdb.properties文件中配置数据库的相关信息。


mvcdb.properties

#=================================================
#mysql connection parameters
#=================================================
mvcdb.mysql.driver=com.mysql.jdbc.Driver
mvcdb.mysql.url=jdbc:mysql://localhost:3306/zszx?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
mvcdb.mysql.user=root
mvcdb.mysql.password=123456
 
mvcdb.mysql.initialSize=2
mvcdb.mysql.maxActive=10000
mvcdb.mysql.minIdle=5
mvcdb.mysql.maxIdle=2 
mvcdb.mysql.maxWait=600000
 
mvcdb.mysql.testOnReturn=false
mvcdb.mysql.testWhileIdle=true
 
mvcdb.mysql.testOnBorrow=true
mvcdb.mysql.validationQuery=select1


 

C.此文件扫描hibernate实体时扫描的文件,此处以hibernate.cfg.userInfo.xml为例。

 

hibernate.cfg.userInfo.xml


<!DOCTYPEhibernate-configuration PUBLIC
"-//Hibernate/HibernateConfiguration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!--用户映射实体 -->
<mappingclass="com.springmvc.mvcdev.userInfo.domain.Userinfo"/>
</session-factory>
</hibernate-configuration>


D.Userinfo实体类使用注解方式关联数据库。


Hibernate 使用注解,可以参考:1. Hibernate Annotation   2.Hibernate4实战之Hibernate4注解零配置

Userinfo.java

packagecom.springmvc.mvcdev.userInfo.domain;
 
importjava.io.Serializable;
 
importjavax.persistence.Column;
importjavax.persistence.Entity;
importjavax.persistence.Id;
importjavax.persistence.Table;
 
/**
 * 用户实体类
 *
 * @ClassName: Userinfo
 * @author: QuBinBin
 * @date: 2014-1-3 上午10:53:36
 *
 */
 
@Entity
@Table(name= "userinfo")
publicclass Userinfo implements Serializable {
privatestatic final long serialVersionUID = -8047186992943452353L;
 
/**
 * 主键ID
 */
@Id
@Column(name= "ID", unique = true, nullable = false)
privateInteger id;
 
/**
 * 用户账号
 */
@Column(name= "NAME", length = 200)
privateString name;
 
/**
 * 用户真实姓名
 */
@Column(name= "TRUENAME", length = 200)
privateString truename;
 
/**
 * 用户密码
 */
@Column(name= "PWD", length = 100)
privateString pwd;
 
/**
 * Email
 */
@Column(name= "EMAIL", length = 50)
privateString email;
 
/**
 * 手机
 */
@Column(name= "MOBILE", length = 20)
privateString mobile;
 
/**
 * 状态(1激活 0禁用)
 */
@Column(name= "STATUS")
privateInteger status;
 
publicInteger getId() {
returnthis.id;
}
 
publicvoid setUserId(Integer id) {
this.id= id;
}
 
publicString getName() {
returnthis.name;
}
 
publicvoid setName(String name) {
this.name= name;
}
 
publicString getTruename() {
returnthis.truename;
}
 
publicvoid setTruename(String truename) {
this.truename= truename;
}
 
publicString getPwd() {
returnthis.pwd;
}
 
publicvoid setPwd(String pwd) {
this.pwd= pwd;
}
 
publicString getEmail() {
returnemail;
}
 
publicvoid setEmail(String email) {
this.email= email;
}
 
publicString getMobile() {
returnmobile;
}
 
publicvoid setMobile(String mobile) {
this.mobile= mobile;
}
 
publicInteger getStatus() {
returnthis.status;
}
 
publicvoid setStatus(Integer status) {
this.status= status;
}
}


 

(4)applicationContext-import.xml配置

 

此文件配置依赖注入的内容

applicationContext-import.xml

<?xmlversion="1.0" encoding="UTF-8"?>
 
<!--
  - Application context definition forJPetStore's business layer.
  - Contains bean references to the transactionmanager and to the DAOs in
  - dataAccessContext-local/jta.xml (seeweb.xml's "contextConfigLocation").
  -->
<beansxmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      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/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-3.0.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
           >
<importresource="classpath*:com/springmvc/mvcdev/userInfo/spring/applicationContext-userInfo.xml"/>
 
</beans>


 

 

具体注入内容在import的每个模块下的xml文件中。此处以applicationContext-userInfo.xml为例。

applicationContext-userInfo.xml

<?xmlversion="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:util="http://www.springframework.org/schema/util"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-2.0.xsd">
 
 
<!--******************************用户********************* -->
 
<!--Hibernate 用户持久化访问接口 -->
<beanid="userInfoDAO"class="com.springmvc.mvcdev.userInfo.dao.impl.UserInfoDAOImpl">
<propertyname="sessionFactory" ref="sessionFactory"/>
</bean>
<beanid="userInfoServiceImpl"class="com.springmvc.mvcdev.userInfo.service.impl.UserInfoServiceImpl">
<propertyname="userInfoDAO" ref="userInfoDAO"></property>
</bean>
<!--事务控制 -->
<beanid="userInfoService" parent="baseTransactionProxy">
<propertyname="target" ref="userInfoServiceImpl"/>
</bean>
 
</beans>

 

  1. 参考资料

 

Spring MVC 教程,快速入门,深入分析 http://elf8848.iteye.com/blog/875830/

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值