Spring+Spring MVC+Hibernate框架搭建实例
前言:这里只是说明整个搭建流程,并不进行原理性的讲解
一 下面所需要用到的数据库配置:
数据库方面,使用mysql创建一个users表,具体代码如下:
DROPTABLEIFEXISTS`users`;CREATETABLE`users`(`UserID`int(4)NOTNULLAUTO_INCREMENT,`UserName`varchar(16)NOTNULL,`Password`varchar(16)NOTNULL,`Telephone`varchar(16)NOTNULL,`Address`varchar(16)NOTNULL,PRIMARYKEY(`UserID`))ENGINE=InnoDBAUTO_INCREMENT=8DEFAULTCHARSET=utf8;--------------------------------Recordsofusers------------------------------INSERTINTO`users`VALUES('1','aa','aa12','aa','aa');INSERTINTO`users`VALUES('2','bb','bb','bb','bb');INSERTINTO`users`VALUES('3','cc','cc','cc','cc');INSERTINTO`users`VALUES('7','admin','admin','12306','北京天安门');
二 创建web项目,并导入相关jar包:
创建一个dynamic web project,然后在WEB-INF/lib下导入spring和hibernate的jar包,嫌麻烦的话也可以使用我用到的jar包,链接:http://pan.baidu.com/s/1kUse26z。整个项目的结构是这样的:
三 创建视图页面user.jsp:
路径是:/WEB-INF/jsp/user/user.jsp,代码如下:
<%@pagelanguage="java"contentType="text/html;charset=UTF-8"pageEncoding="UTF-8"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPEhtml><html><head><metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"><basehref="<%=basePath%>"><title>Inserttitlehere</title></head><body><h2>Message:${message}</h2></body></html>
四 根据数据库表的字段建立实体类Users.java:
实体类放在cn.zifangsky.entity包中,这里采用了注解的方式来配置,Users.java代码如下:
packagecn.zifangsky.entity;importjavax.persistence.Column;importjavax.persistence.Entity;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence.Id;@Entity(name="users")publicclassUsersimplementsjava.io.Serializable{@Id@GeneratedValue(strategy=GenerationType.AUTO)@Column(name="UserID")privateIntegeruserId;@Column(name="UserName",length=16)privateStringuserName;@Column(name="Password",length=16)privateStringpassword;@Column(name="Telephone",length=16)privateStringtelephone;@Column(name="Address",length=16)privateStringaddress;publicUsers(){}publicUsers(IntegeruserId,StringuserName,Stringpassword,Stringtelephone,Stringaddress){this.userId=userId;this.userName=userName;this.password=password;this.telephone=telephone;this.address=address;}publicIntegergetUserId(){returnuserId;}publicvoidsetUserId(IntegeruserId){this.userId=userId;}publicStringgetUserName(){returnuserName;}publicvoidsetUserName(StringuserName){this.userName=userName;}publicStringgetPassword(){returnpassword;}publicvoidsetPassword(Stringpassword){this.password=password;}publicStringgetTelephone(){returntelephone;}publicvoidsetTelephone(Stringtelephone){this.telephone=telephone;}publicStringgetAddress(){returnaddress;}publicvoidsetAddress(Stringaddress){this.address=address;}}
五 处理框架整合的配置文件:
(1)首先是web.xml,路径是:WEB-INF/web.xml:
<?xmlversion="1.0"encoding="UTF-8"?><web-appxmlns: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"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID"version="3.0"><display-name>ArchetypeCreatedWebApplication</display-name><!--配置Spring--><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/spring-*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!--定义DispatcherServlet--><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/classes/springmvc-servlet.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-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></filter-mapping><!--控制Session的开关--><filter><filter-name>openSession</filter-name><filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class></filter><filter-mapping><filter-name>openSession</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>
(2)spring mvc所需要用到的配置文件springmvc-servlet.xml,路径是:src/springmvc-servlet.xml:
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:p="http://www.springframework.org/schema/p"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.0.xsd"><!--启用springmvc注解--><mvc:annotation-driven/><!--不操作静态资源--><mvc:default-servlet-handler/><!--启动自动扫描该包下所有的Bean(例如@Controller)--><context:component-scanbase-package="cn.zifangsky.controller"/><!--定义视图解析器--><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><propertyname="prefix"><value>/WEB-INF/jsp/user/</value></property><propertyname="suffix"><value>.jsp</value></property></bean></beans>
(3)整合hibernate所需要用到的配置文件spring-hibernate.xml,这里为了简单只用了基础的jdbc数据源,路径是src/spring-hibernate.xml:
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.0.xsd"><!--声明事务管理器--><beanid="myHibTxManager"class="org.springframework.orm.hibernate5.HibernateTransactionManager"><propertyname="sessionFactory"ref="sessionFactory"/></bean><!--定义事务通知--><tx:adviceid="tx_Advice"transaction-manager="myHibTxManager"><!--定义事务传播规则--><tx:attributes><!--对get/load/search开头的方法应用只读事务规则--><tx:methodname="get*"propagation="SUPPORTS"read-only="true"/><tx:methodname="load*"propagation="SUPPORTS"read-only="true"/><tx:methodname="search*"propagation="SUPPORTS"read-only="true"/><!--对其他方法应用REQUIRED事务规则--><tx:methodname="*"propagation="REQUIRED"/></tx:attributes></tx:advice><aop:config><!--对com.zxpm.biz包下的所有类的所有方法都应用事务规则--><aop:pointcutid="bizMethods"expression="execution(*cn.zifangsky.service.*.*(..))"/><!--将事务通知和切面组合--><aop:advisoradvice-ref="tx_Advice"pointcut-ref="bizMethods"/></aop:config><!--配置数据源--><beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><propertyname="driverClassName"value="com.mysql.jdbc.Driver"/><propertyname="url"value="jdbc:mysql://127.0.0.1/zxpm"/><propertyname="username"value="root"/><propertyname="password"value="root"/></bean><beanid="sessionFactory"class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/><propertyname="packagesToScan"><list><!--可以加多个包--><value>cn.zifangsky.entity</value></list></property><propertyname="hibernateProperties"><props><propkey="hibernate.show_sql">true</prop></props></property></bean></beans>
(4)加载bean配置文件spring-bean.xml,当然具体的一些bean将在下一环节中配置,路径:src/spring-bean.xml:
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.2.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.2.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.2.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.2.xsd"><beanid="usersDAO"class="cn.zifangsky.dao.UsersDAO"><propertyname="sessionFactory"ref="sessionFactory"></property></bean><beanid="userService"class="cn.zifangsky.service.UserService"><propertyname="userDao"ref="usersDAO"></property></bean></beans>
六 业务处理DAO,Service和Controller:
(1)UsersDAO.java,在cn.zifangsky.dao这个包中:
packagecn.zifangsky.dao;importjava.util.List;importorg.hibernate.HibernateException;importorg.hibernate.Query;importorg.hibernate.Session;importorg.springframework.orm.hibernate5.HibernateCallback;importorg.springframework.orm.hibernate5.support.HibernateDaoSupport;importcn.zifangsky.entity.Users;publicclassUsersDAOextendsHibernateDaoSupport{publicList<Users>getAllUser(){Objectexecute=super.getHibernateTemplate().execute(newHibernateCallback<Object>(){publicObjectdoInHibernate(Sessionsession)throwsHibernateException{Stringhql="fromusers";Queryquery=session.createQuery(hql);returnquery.list();}});return(List<Users>)execute;}}
(2)UserService.java,在cn.zifangsky.service这个包中:
packagecn.zifangsky.service;importcn.zifangsky.dao.UsersDAO;publicclassUserService{privateUsersDAOuserDao;publicintuserCount(){returnuserDao.getAllUser().size();}publicUsersDAOgetUserDao(){returnuserDao;}publicvoidsetUserDao(UsersDAOuserDao){this.userDao=userDao;}}
(3)UserController.java,在cn.zifangsky.controller这个包中:
packagecn.zifangsky.controller;importjavax.annotation.Resource;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.servlet.ModelAndView;importcn.zifangsky.service.UserService;@Controller@RequestMapping("/user")publicclassUserController{@Resource(name="userService")privateUserServiceservice;@RequestMapping(value="/manager",method=RequestMethod.GET)publicModelAndViewhello2(){ModelAndViewmv=newModelAndView();mv.addObject("message","HelloMVC");mv.setViewName("user");returnmv;}@RequestMapping(value="/count",method=RequestMethod.GET)publicModelAndViewcount(){intc=service.userCount();ModelAndViewmv=newModelAndView();mv.addObject("message",c);mv.setViewName("user");returnmv;}}
从上面的代码可以看出,定义了两个请求,分别是:http://localhost:8080/SpringDemo/user/manager 和http://localhost:8080/SpringDemo/user/count ,分别返回一个字符串和users这个表中数据的条数。下面我们将对这两个请求进行测试
七 测试:
测试结果如下:
http://localhost:8080/SpringDemo/user/manager
http://localhost:8080/SpringDemo/user/count
可以看出,这个框架已经搭建成功了
注:如果在项目启动时报错的话,第一是检查配置文件中是不是有哪个地方写错了,第二是注意看下/WEB-INF/lib下有没有aopalliance.jar和aspectjweaver-1.5.4.jar这两个jar包。因为我刚开始时就是因为没有这两个jar包,在项目启动时各种报错,真的挺坑的
PS:参考文章:http://www.cnblogs.com/leiOOlei/p/3727859.html
欢迎大家有时间来我个人独立博客(http://www.zifangsky.cn)踩踩
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。