Spring+Springmvc+Hibernate框架搭建

最近学习spring框架,学习中总是磕磕绊绊的,出现这样或者那样的问题,于是就像写一篇笔记,将spring,springmvc,hibernate框架整合的过程,以及简单的实现记录下来,一来加深印象,二来一遍以后忘记好找资料(...)当然,初学者也可以借鉴一下。废话不多说,直接上干货!

平台:eclipse

1.首先看看我整个项目的结构

2.项目开始:开始配置配置文件,主要有web.xml, applicationContext.xml, springmvc这三个文件

web.xml文件如下(主要是配置spring IOC容器,springmvc的dispacherServlet, 编码的格式化:防止出现乱码,SessionFilter过滤器:防止session异常。这里主要注意的是路径问题,由于楼主的配置文件是放在src下的config包中的,所以配置的时候用classpath:包名/配置文件名.xml的形式;如果放在WebContext下,直接写文件名就行, WEB-INF下就是/WEB-INF/文件名.xml,以此类推。。

[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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">  
  3.   <display-name>springmvc_1</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>index.html</welcome-file>  
  6.     <welcome-file>index.htm</welcome-file>  
  7.     <welcome-file>index.jsp</welcome-file>  
  8.     <welcome-file>default.html</welcome-file>  
  9.     <welcome-file>default.htm</welcome-file>  
  10.     <welcome-file>default.jsp</welcome-file>  
  11.   </welcome-file-list>  
  12.     
  13.   <!-- 配置spring ioc容器 -->  
  14.     <context-param>  
  15.         <param-name>contextConfigLocation</param-name>  
  16.         <param-value>classpath:config/applicationContext.xml</param-value>  
  17.     </context-param>  
  18.   
  19.     <!-- Bootstraps the root web application context before servlet initialization -->  
  20.     <listener>  
  21.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  22.     </listener>  
  23.       
  24.     <!-- 配置springmvc 的DispatcherServlet -->  
  25.     <servlet>  
  26.         <servlet-name>dispatcherServlet</servlet-name>  
  27.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  28.         <init-param>  
  29.             <param-name>contextConfigLocation</param-name>  
  30.             <param-value>classpath:config/springmvc.xml</param-value>  
  31.         </init-param>  
  32.         <load-on-startup>1</load-on-startup>  
  33.     </servlet>  
  34.   
  35.     <!-- Map all requests to the DispatcherServlet for handling -->  
  36.     <servlet-mapping>  
  37.         <servlet-name>dispatcherServlet</servlet-name>  
  38.         <url-pattern>*.do</url-pattern>  
  39.     </servlet-mapping>  
  40.       
  41.     <filter>  
  42.         <filter-name>CharacterEncodingFilter</filter-name>  
  43.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  44.         <init-param>  
  45.             <param-name>encoding</param-name>  
  46.             <param-value>UTF-8</param-value>  
  47.         </init-param>  
  48.     </filter>  
  49.     <filter-mapping>  
  50.         <filter-name>CharacterEncodingFilter</filter-name>  
  51.         <url-pattern>/*</url-pattern>  
  52.     </filter-mapping>  
  53.       
  54.     <filter>  
  55.         <filter-name>SessionFilter</filter-name>  
  56.         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
  57.     </filter>  
  58.     <filter-mapping>  
  59.         <filter-name>SessionFilter</filter-name>  
  60.         <url-pattern>/*</url-pattern>  
  61.     </filter-mapping>  
  62. </web-app>  
springmvc.xml文件如下(主要是添加一个注解扫描,然后就是视图解析器。其中prefix表示的是跳转后的页面放置的前缀路径,楼主这里纠结了一会儿。。suffix表示的是后缀名,这个好理解。)

[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd  
  8.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  9.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd  
  10.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">  
  11.   
  12.     <!-- 配置自动扫描包 -->  
  13.     <context:component-scan base-package="com.shin">  
  14. <!--         <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> -->  
  15. <!--         <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> -->  
  16.     </context:component-scan>  
  17.       
  18.     <!-- 配置视图解析器 -->  
  19.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  20.         <property name="prefix" value="/pages/"></property>  
  21.         <property name="suffix" value=".jsp"></property>  
  22.     </bean>  
  23.       
  24.     <mvc:default-servlet-handler/>  
  25.       
  26.     <mvc:annotation-driven/>  
  27. </beans>  
applicationContext.xml配置如下(1.注解扫描  2.加载db.properties文件:配合数据库连接池配置实用,这里的路径与web.xml中路径同理 3.配置数据源:与dp.properties中的各个属性对应 4.配置sessionFactory:配置hibernate中的一些方言,属性等,这里将这些写在spring配置文件中,去除了hibernate.cfg.xml文件,当然也可以将添加这个文件,只需在sessionFactory中添加映射路径即可 5.配置事务管理器 )

[java]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  7.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd  
  8.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">  
  9.   
  10.   
  11.     <!-- 配置自动扫描的包 -->  
  12.     <context:component-scan base-package="com.shin">  
  13. <!--         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> -->  
  14. <!--         <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> -->  
  15.     </context:component-scan>  
  16.       
  17.     <context:property-placeholder location="classpath:config/db.properties"/>  
  18.       
  19.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >  
  20.         <property name="user" value="${jdbc.user}"></property>  
  21.         <property name="password" value="${jdbc.password}"></property>  
  22.         <property name="driverClass" value="${jdbc.driverClass}"></property>  
  23.         <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>      
  24.     </bean>  
  25.       
  26.     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >  
  27.         <property name="dataSource" ref="dataSource"></property>  
  28.         <property name="namingStrategy">   
  29.             <bean class="org.hibernate.cfg.ImprovedNamingStrategy"></bean>  
  30.         </property>  
  31.         <property name="packagesToScan" value="com.shin.entities"></property>  
  32.           
  33.         <property name="hibernateProperties">  
  34.             <props>  
  35.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect </prop>  
  36.                 <prop key="hibernate.show_sql">true</prop>  
  37.                 <prop key="hibernate.format_sql">true</prop>  
  38.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  39.                 <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>  
  40.             </props>  
  41.         </property>  
  42.         <property name="mappingResources" >  
  43.             <list>  
  44.                 <value>com/shin/entities/User.hbm.xml</value>  
  45.             </list>  
  46.         </property>  
  47.     </bean>  
  48.       
  49.     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  50.         <property name="sessionFactory" ref="sessionFactory"></property>  
  51.     </bean>  
  52.       
  53. </beans>  
db.properties文件:

[java]  view plain  copy
  1. jdbc.user=root  
  2. jdbc.password=123456  
  3. jdbc.driverClass=com.mysql.jdbc.Driver  
  4. jdbc.jdbcUrl=jdbc:mysql:///test  

然后开始java代码的编写:

楼主只是做了一个简单的用户添加应用,所以代码比较简单,主要是实现这个基本框架,还有很多东西需要去学习;

先来实体类 User.Java  然后我用hibernate插件自动生成hbm.xml文件(当然也可以手动配置,挺简单的)

[java]  view plain  copy
  1. package com.shin.entities;  
  2.   
  3. public class User {  
  4.   
  5.     private Integer id;  
  6.     private String name;  
  7.     private String password;  
  8.   
  9.     public Integer getId() {  
  10.         return id;  
  11.     }  
  12.   
  13.     public void setId(Integer id) {  
  14.         this.id = id;  
  15.     }  
  16.   
  17.     public String getName() {  
  18.         return name;  
  19.     }  
  20.   
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.   
  25.     public String getPassword() {  
  26.         return password;  
  27.     }  
  28.   
  29.     public void setPassword(String password) {  
  30.         this.password = password;  
  31.     }  
  32.   
  33. }  

[java]  view plain  copy
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!-- Generated 2016-7-12 10:59:16 by Hibernate Tools 3.5.0.Final -->  
  5. <hibernate-mapping>  
  6.     <class name="com.shin.entities.User" table="USER">  
  7.         <id name="id" type="java.lang.Integer">  
  8.             <column name="ID" />  
  9.             <generator class="native" />  
  10.         </id>  
  11.         <property name="name" type="java.lang.String">  
  12.             <column name="NAME" />  
  13.         </property>  
  14.         <property name="password" type="java.lang.String">  
  15.             <column name="PASSWORD" />  
  16.         </property>  
  17.     </class>  
  18. </hibernate-mapping>  


然后是dao层,分别是UserDao.java接口 和 UserDaoImpl.java实现

[java]  view plain  copy
  1. package com.shin.dao;  
  2.   
  3. import com.shin.entities.User;  
  4.   
  5. public interface UserDao {  
  6.   
  7.     public void addUser(User user);  
  8. }  

[java]  view plain  copy
  1. package com.shin.dao.impl;  
  2.   
  3. import org.hibernate.SessionFactory;  
  4. import org.springframework.beans.factory.annotation.Autowired;  
  5. import org.springframework.stereotype.Repository;  
  6. import org.springframework.transaction.annotation.Transactional;  
  7.   
  8. import com.shin.dao.UserDao;  
  9. import com.shin.entities.User;  
  10.   
  11. @Repository("userDao")  
  12. public class UserDaoImpl implements UserDao {  
  13.   
  14.     @Autowired  
  15.     private SessionFactory sessionFactory;  
  16.       
  17.     public SessionFactory getSessionFactory() {  
  18.         return sessionFactory;  
  19.     }  
  20.       
  21.     public void addUser(User user) {  
  22.           
  23.         sessionFactory.getCurrentSession().save(user);  
  24.   
  25.     }  
  26.   
  27. }  

再就是service层,分别是UserService.java接口和UserServiceImpl,java实现类

[java]  view plain  copy
  1. package com.shin.service;  
  2.   
  3. import com.shin.entities.User;  
  4.   
  5. public interface UserService {  
  6.   
  7.     public void addUser(User user);  
  8. }  
[java]  view plain  copy
  1. package com.shin.service.impl;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Service;  
  5.   
  6. import com.shin.dao.UserDao;  
  7. import com.shin.entities.User;  
  8. import com.shin.service.UserService;  
  9.   
  10. @Service("userService")  
  11. public class UserServiceImpl implements UserService {  
  12.   
  13.     @Autowired  
  14.     private UserDao userDao;  
  15.   
  16.     public void setUserDao(UserDao userDao) {  
  17.         this.userDao = userDao;  
  18.     }  
  19.   
  20.     @Override  
  21.     public void addUser(User user) {  
  22.         // TODO Auto-generated method stub  
  23.         userDao.addUser(user);  
  24.     }  
  25.   
  26. }  
最后是controller: UserController.java(controller是核心,页面的处理跳转都要经过他,requestMapping中的值和.jsp中的action对应,由于web.xml中springmvc拦截的是.do结尾的动作,这里在处理方法上复制以此结尾)

[java]  view plain  copy
  1. package com.shin.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.web.bind.annotation.RequestMapping;  
  8.   
  9. import com.shin.entities.User;  
  10. import com.shin.service.UserService;  
  11.   
  12. @Controller  
  13. @RequestMapping("/user")  
  14. public class UserController {  
  15.   
  16.     @Autowired  
  17.     private UserService userService;  
  18.       
  19.     @RequestMapping(value="sucess.do")  
  20.     public String add(HttpServletRequest request){  
  21.         String username = request.getParameter("username");  
  22.         String password = request.getParameter("password");  
  23.         System.out.println(username+" "+password);  
  24.           
  25.         User user = new User();  
  26.         user.setName(username);  
  27.         user.setPassword(password);  
  28.           
  29.         userService.addUser(user);  
  30.         return "sucess";  
  31.           
  32.     }  
  33. }  
然后是简单的jsp页面,测试用的。

add.jsp

[java]  view plain  copy
  1. <%@ page language="java" contentType="text/html; charset=utf-8"  
  2.     pageEncoding="utf-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  7. <title>Insert title here</title>  
  8. </head>  
  9. <body>  
  10.     <h1>添加用户</h1>  
  11.     <form action="user/sucess.do" method="post">  
  12.         用户  <input type="text" name="username"/><br/>  
  13.         密码  <input type="text" name="password"/><br/>  
  14.         <input type="submit" value="添加">  
  15.     </form>  
  16.       
  17. </body>  
  18. </html>  

sucess.jsp

[java]  view plain  copy
  1. <%@ page language="java" contentType="text/html; charset=utf-8"  
  2.     pageEncoding="utf-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">  
  7. <title>Insert title here</title>  
  8. </head>  
  9. <body>  
  10.     添加成功!  
  11. </body>  
  12. </html>  

测试

其他渠道来源, 紧个人学习使用不得用于商业经营;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值