上一篇给大家讲到spring3搭建的简单的springMVC的测试例子,没有数据层。这篇给大家介绍下spring3+Hibernate3搭建一个springMVC框架,并且有数据层。废话不多说,直接上代码了。以后会给大家搭建spring3。当然我是初学者,有什么问题还请多多见谅。
当然首先不能忘记jar包,jar包在这也不多说。在最后会给源码下载地址。在源码包里都有,本人用的是oracle数据库,并且用的是Eclipse开发。如何用Eclipse搭建web工程,将在以后的文章中贴出。
首先当然是要新建一个web工程,我的工程名就是叫spring3hibernate3。下图是我的工程的架构。
包文件的展开图如下:
下面进入正题,导入jar包,接下来就是配置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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>spring3hibernate3</display-name> <!-- 引入spring的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext.xml</param-value> </context-param> <!-- 引入spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置编码过滤器 --> <filter> <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name> <url-pattern>*.jsp</url-pattern> <url-pattern>*.html</url-pattern> </filter-mapping> <!-- 配置spring的分发器 --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 引入自己命名的springMVC文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <!-- 服务启动时就加载 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <!-- 拦截所有以.do结尾的请求 --> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 欢迎页 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
接下来spring-mvc.xml的配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 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"> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> </bean> <context:annotation-config/> <!-- 扫描注解包 --> <context:component-scan base-package="com.json.dao" /> <context:component-scan base-package="com.json.service" /> <context:component-scan base-package="com.json.controller" /> <!-- 视图配置 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> </beans>
在classpath下面的META-INF/路径下面有application.properties,是数据库的相关配置,其实就是键值对,刚开始学的时候,我们是自己解析properties文件,其实apache已经帮我们做了。以下是文件的内容:
jdbc.url=jdbc:oracle:thin:@localhost:1521:XE jdbc.username=scott jdbc.password=tiger
配置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: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"> <!-- 引入配置properties文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="fileEncoding" value="UTF-8" /> <property name="locations"> <list> <value>classpath*:/META-INF/application.properties</value> </list> </property> </bean> <!-- 配置数据源dataSource --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- 数据库的驱动, url, username, password --> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 连接池启动时创建的连接数量 --> <property name="initialSize" value="5" /> <!-- 同一时间最多的连接数量,0表示没有限制 --> <property name="maxActive" value="0" /> <!-- 池中不会被释放的最多空闲的连接数,0表示没有显示 --> <property name="maxIdle" value="20"/> <!-- 在不新建连接的条件下,池中保持空闲的最少连接数 --> <property name="minIdle" value="1" /> </bean> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" > <property name="dataSource" ref="dataSource"/> <property name="hibernateProperties"> <props> <!-- oracle数据库的方言 --> <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> <!-- 是否显示sql语句 --> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.jdbc.batch_size">80</prop> <prop key="hibernate.cacheQueries">true</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> <prop key="hibernate.cache.use_query_cache">true</prop> </props> </property> <!-- 扫描实体包。不知道为什么,com.json.model.* 这样配置会报错 --> <property name="packagesToScan" value="com.json.*" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- Annotation管理事务器 --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> </beans>
到这里我们的配置文件就完成了。然后就是代码的编写了。既然牵扯到数据层,那么肯定会有表。当然这里也是简单实现数据的一个流通。所以我们就用简单的通用的用户表来测试。表名为fq_user,以下是数据库的表创建代码:
drop table fq_user; create table fq_user( user_id number(5) primary key, user_name varchar2(50), user_age number(3) ); insert into fq_user(user_id, user_name, user_age) values(1,'hehe',23); commit; select * from fq_user;
数据库建好之后,就要实现相应的实体映射,这里全程用注解的形式。以下是实体User的代码:
package com.json.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="fq_user") public class User implements Serializable{ private static final long serialVersionUID = -2051600566896335425L; @Id @Column(name="user_id") private Long id; @Column(name="user_name") private String name; @Column(name="user_age") private Long age; public User(){} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } public String toString(){ return org.apache.commons.lang.builder.ReflectionToStringBuilder.toString(this); } }
由上面的代码我们可以得知数据库中一条数据,我们就演示从数据中拿到这条数据。接口层的代码就不贴了。就贴实现层的。下面是dao层的BaseDAO.java的代码:
package com.json.dao.impl; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class BaseDAO extends HibernateDaoSupport{ @Autowired public void setSessionFactoryOverride(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } }
UserDAOImpl.java的代码:
package com.json.dao.impl; import org.springframework.stereotype.Repository; import com.json.dao.UserDAO; import com.json.model.User; @Repository("userDao") public class UserDAOImpl extends BaseDAO implements UserDAO{ @Override public User get(long id) { return this.getHibernateTemplate().get(User.class, id); } }
UserServiceImpl.java的代码:
package com.json.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.json.dao.UserDAO; import com.json.model.User; import com.json.service.UserService; @Service("userService") public class UserServiceImpl implements UserService{ @Resource(name="userDao") private UserDAO userDao; @Override public User get(long id) { return userDao.get(id); } }
UserController.java的代码:
package com.json.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.json.model.User; import com.json.service.UserService; @Controller public class UserController { @Resource(name="userService") private UserService userService; @RequestMapping("/get") public String get(){ User u = userService.get(1); System.out.println(u); return "get"; } }
在/WEB-INF/page/下面有新建一个get.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>get.jsp</title> </head> <body> I am get.jsp </body> </html>
好的,我们的测试所有的代码就完成了。下面启动数据库,启动服务器。在地址栏中输入:http://localhost:8290/spring3hibernate3/get.do,页面会跳转到get.jsp。
控制台的输出如下:
由以上可以看出,我们拿到了数据。
以下是源代码的下载地址:http://download.csdn.net/detail/fanshujuntuan/7547253。