SpringMVC+Spring3+Hibernate4开发环境搭建

早期的项目比较简单,多是用JSP 、Servlet + JDBC 直接搞定,后来使用 Struts1(Struts2)+Spring+Hibernate, 严格按照分层概念驱动项目开发,这次又使用 Spring MVC取代Struts来进行开发。
MVC已经是现代Web开发中的一个很重要的部分,下面介绍一下SpringMVC+Spring3+Hibernate4的开发环境搭建
先大致看一下项目结构:
具体的代码不再演示,主要是走了一个很平常的路线,mvc-servcie-dao-hibernate的结构,源码可以下载,主要看一下配置文件。解释见注释
web.xml
[html][/html] view plaincopyprint?

  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” 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_2_5.xsd” id=”WebApp_ID” version=”2.5″>
  3.   <display-name>SpringMVC</display-name>
  4.   <welcome-file-list>
  5.     <welcome-file>index.jsp</welcome-file>
  6.   </welcome-file-list>
  7.   <!– 配置Spring –>
  8.   <context-param>
  9.         <param-name>contextConfigLocation</param-name>
  10.         <param-value>classpath*:config/spring-*.xml</param-value>
  11.   </context-param>
  12.   <listener>
  13.      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  14.   </listener>
  15.   <!– 配置SpringMVC –>
  16.   <servlet>
  17.     <servlet-name>springMVC</servlet-name>
  18.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  19.     <init-param>
  20.       <param-name>contextConfigLocation</param-name>
  21.       <param-value>classpath*:config/spring-servlet.xml</param-value>
  22.     </init-param>
  23.     <load-on-startup>1</load-on-startup>
  24.   </servlet>
  25.   <servlet-mapping>
  26.     <servlet-name>springMVC</servlet-name>
  27.     <url-pattern>/</url-pattern>
  28.   </servlet-mapping>
  29.   <!– 设置字符集 –>
  30.   <filter>
  31.     <filter-name>encodingFilter</filter-name>
  32.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  33.     <init-param>
  34.       <param-name>encoding</param-name>
  35.       <param-value>UTF-8</param-value>
  36.     </init-param>
  37.     <init-param>
  38.       <param-name>forceEncoding</param-name>
  39.       <param-value>true</param-value>
  40.     </init-param>
  41.   </filter>
  42.   <filter-mapping>
  43.     <filter-name>encodingFilter</filter-name>
  44.     <url-pattern>/*</url-pattern>
  45.   </filter-mapping>
  46.   <!– 控制Session的开关 –>
  47.   <filter>
  48.         <filter-name>openSession</filter-name>
  49.         <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  50.   </filter>
  51.   <filter-mapping>
  52.     <filter-name>openSession</filter-name>
  53.     <url-pattern>/*</url-pattern>
  54.   </filter-mapping>
  55. </web-app>
spring-servlet.xml
[html][/html] view plaincopyprint?

  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <beans xmlns=”http://www.springframework.org/schema/beans”
  3.     xmlns:context=”http://www.springframework.org/schema/context” xmlns:p=”http://www.springframework.org/schema/p”
  4.     xmlns:mvc=”http://www.springframework.org/schema/mvc” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  5.     xsi:schemaLocation=”http://www.springframework.org/schema/beans
  6.       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7.       http://www.springframework.org/schema/context
  8.       http://www.springframework.org/schema/context/spring-context.xsd
  9.       http://www.springframework.org/schema/mvc
  10.       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”>
  11.     <!– 注解扫描的包 –>
  12.     <context:component-scan base-package=”com.jialin” />
  13.     <!– 开启注解方案1 –>
  14.     <!– 注解方法处理 –>
  15.     <!– <bean class=”org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”
  16.         /> –>
  17.     <!– 注解类映射处理 –>
  18.     <!– <bean class=”org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping”></bean> –>
  19.     <!– 开启注解方案2 –>
  20.     <mvc:annotation-driven />
  21.     <!– 静态资源访问,方案1 –>
  22.     <mvc:resources location=”/img/” mapping=”/img/**” />
  23.     <mvc:resources location=”/js/” mapping=”/js/**” />
  24.     <!– 静态资源访问,方案2 –>
  25.     <!– <mvc:default-servlet-handler/> –>
  26.     <!– 视图解释类 –>
  27.     <bean id=”viewResolver”
  28.         class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
  29.         <property name=”prefix” value=”/”></property>
  30.         <!–可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 –>
  31.         <property name=”suffix” value=”.jsp”></property>
  32.     </bean>
  33.     <!– 上传文件bean –>
  34.     <!– <bean id=”multipartResolver” class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>
  35.         <property name=”defaultEncoding” value=”utf-8″ /> <property name=”maxUploadSize”
  36.         value=”10485760000″ /> <property name=”maxInMemorySize” value=”40960″ />
  37.         </bean> –>
  38. </beans>
spring-hibernate.xml
[html][/html] view plaincopyprint?

  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <beans xmlns=”http://www.springframework.org/schema/beans”
  3.     xmlns:context=”http://www.springframework.org/schema/context” xmlns:p=”http://www.springframework.org/schema/p”
  4.     xmlns:mvc=”http://www.springframework.org/schema/mvc” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  5.     xsi:schemaLocation=”http://www.springframework.org/schema/beans
  6.       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  7.       http://www.springframework.org/schema/context
  8.       http://www.springframework.org/schema/context/spring-context.xsd
  9.       http://www.springframework.org/schema/mvc
  10.       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”>
  11.     <!– 配置数据源 –>
  12.     <bean id=”dataSource”
  13.         class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
  14.         <property name=”driverClassName” value=”com.mysql.jdbc.Driver” />
  15.         <property name=”url” value=”jdbc:mysql://127.0.0.1/springmvc” />
  16.         <property name=”username” value=”root” />
  17.         <property name=”password” value=”123456″ />
  18.     </bean>
  19.     <!–  配置hibernate SessionFactory–>
  20.     <bean id=”sessionFactory”
  21.         class=”org.springframework.orm.hibernate4.LocalSessionFactoryBean”>
  22.         <property name=”dataSource” ref=”dataSource” />
  23.         <property name=”hibernateProperties”>
  24.             <props>
  25.                 <prop key=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</prop>
  26.                 <prop key=”hibernate.hbm2ddl.auto”>update</prop>
  27.                 <prop key=”hibernate.show_sql”>true</prop>
  28.                 <prop key=”hiberante.format_sql”>true</prop>
  29.             </props>
  30.         </property>
  31.         <property name=”configLocations”>
  32.             <list>
  33.                 <value>
  34.                     classpath*:config/hibernate/hibernate.cfg.xml
  35.                 </value>
  36.             </list>
  37.         </property>
  38.     </bean>
  39.     <!– 事务管理器 –>
  40.     <bean id=”transactionManager”
  41.         class=”org.springframework.orm.hibernate4.HibernateTransactionManager”>
  42.         <property name=”sessionFactory” ref=”sessionFactory”></property>
  43.     </bean>
  44.     <!– 事务代理类 –>
  45.     <bean id=”transactionBese”
  46.         class=”org.springframework.transaction.interceptor.TransactionProxyFactoryBean”
  47.         lazy-init=”true” abstract=”true”>
  48.         <property name=”transactionManager” ref=”transactionManager”></property>
  49.         <property name=”transactionAttributes”>
  50.             <props>
  51.                 <prop key=”add*”>PROPAGATION_REQUIRED,-Exception</prop>
  52.                 <prop key=”update*”>PROPAGATION_REQUIRED,-Exception</prop>
  53.                 <prop key=”insert*”>PROPAGATION_REQUIRED,-Exception</prop>
  54.                 <prop key=”modify*”>PROPAGATION_REQUIRED,-Exception</prop>
  55.                 <prop key=”delete*”>PROPAGATION_REQUIRED,-Exception</prop>
  56.                 <prop key=”del*”>PROPAGATION_REQUIRED,-Exception</prop>
  57.                 <prop key=”get*”>PROPAGATION_NEVER</prop>
  58.             </props>
  59.         </property>
  60.     </bean>
  61. </beans>
spring-core.xml
[html][/html] view plaincopyprint?

  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <beans xmlns=”http://www.springframework.org/schema/beans”
  3.  xmlns:context=”http://www.springframework.org/schema/context”
  4.  xmlns:p=”http://www.springframework.org/schema/p”
  5.  xmlns:mvc=”http://www.springframework.org/schema/mvc”
  6.  xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
  7.  xsi:schemaLocation=”http://www.springframework.org/schema/beans
  8.       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9.       http://www.springframework.org/schema/context
  10.       http://www.springframework.org/schema/context/spring-context.xsd
  11.       http://www.springframework.org/schema/mvc
  12.       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”>
  13.     <!– 引入其他配置文件,可以为多个 –>
  14.     <import resource=”classpath*:config/spring/spring-user.xml”/>
  15.  </beans>
spring-user.xml
[html][/html] view plaincopyprint?

  1. <?xml version=”1.0″ encoding=”UTF-8″?>
  2. <!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN 2.0//EN” “http://www.springframework.org/dtd/spring-beans-2.0.dtd” [
  3. <!ENTITY contextInclude SYSTEM “org/springframework/web/context/WEB-INF/contextInclude.xml”>
  4. ]>
  5. <beans>
  6.     <!– Spring Bean –>
  7.     <bean id=”userDao” class=”com.jialin.dao.UserDao”>
  8.         <property name=”sessionFactory” ref=”sessionFactory”></property>
  9.     </bean>
  10.     <bean id=”userManagerBase” class=”com.jialin.service.UserManager”>
  11.         <property name=”userDao” ref=”userDao”></property>
  12.     </bean>
  13.     <!– parent为transactionBese,表示支持事务 –>
  14.     <bean id=”userManager” parent=”transactionBese”>
  15.         <property name=”target” ref=”userManagerBase”></property>
  16.     </bean>
  17. </beans>
hibernate.cfg.xml
[html][/html] view plaincopyprint?

  1. <!DOCTYPE hibernate-configuration PUBLIC
  2.         “-//Hibernate/Hibernate Configuration DTD 3.0//EN”
  3.         “http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd”>
  4. <hibernate-configuration>
  5.     <session-factory>
  6.         <!– 引入需要映射的类 –>
  7.         <mapping class=”com.jialin.entity.User”/>
  8.     </session-factory>
  9. </hibernate-configuration>
下面再来看看Controller
[java][/java] view plaincopyprint?

  1. package com.jialin.controller;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.util.List;
  5. import javax.annotation.Resource;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import com.jialin.entity.User;
  11. import com.jialin.service.IUserManager;
  12. @Controller   //类似Struts的Action
  13. @RequestMapping(“/user”)
  14. public class UserController {
  15.     @Resource(name=”userManager”)  // 获取spring配置文件中bean的id为userManager的,并注入
  16.     private IUserManager userManager;
  17.     @RequestMapping(“/addUser”)   // 请求url地址映射,类似Struts的action-mapping
  18.     public String addUser(User user){
  19.         if(userManager.addUser(user))
  20.         {
  21.             // 重定向
  22.             return “redirect:/user/getAllUser”;
  23.         }else
  24.         {
  25.             return “/fail”;
  26.         }
  27.     }
  28.     @RequestMapping(“/updateUser”)
  29.     public String updateUser(User user,HttpServletRequest request){
  30.         if (userManager.updateUser(user))
  31.         {
  32.             user = userManager.getOneUser(user);
  33.             request.setAttribute(“user”, user);
  34.             return “/UserEdit”;
  35.         }else
  36.         {
  37.             return “/fail”;
  38.         }
  39.     }
  40.     @RequestMapping(“/delUser”)
  41.     public void delUser(User user,HttpServletResponse response){
  42.         String result = “{\”result\”:\”error\”}”;
  43.         if(userManager.delUser(user)){
  44.             result = “{\”result\”:\”success\”}”;
  45.         }
  46.         PrintWriter out = null;
  47.         response.setContentType(“application/json”);
  48.         try {
  49.             out = response.getWriter();
  50.             out.write(result);
  51.         } catch (IOException e) {
  52.             e.printStackTrace();
  53.         }
  54.     }
  55.     @RequestMapping(“/toAddUser”)
  56.     public String toAddUser(){
  57.         return “/UserAdd”;
  58.     }
  59.     @RequestMapping(“/toUpdateUser”)
  60.     public String toUpdateUser(User user,HttpServletRequest request){
  61.         User user1=userManager.getOneUser(user);
  62.         request.setAttribute(“user1”, user1);
  63.         return “/UserEdit”;
  64.     }
  65.     @RequestMapping(“/getAllUser”)
  66.     public String getAllUser(HttpServletRequest request){
  67.         List userList=userManager.getAllUser();
  68.         request.setAttribute(“userlist”, userList);
  69.         return “/UserMain”;
  70.     }
  71. }
源码下载……

标签