SpringMVC+Spring3+Hibernate4開發環境搭建

來源:互聯網
上載者:User
早期的項目比較簡單,多是用JSP 、Servlet + JDBC 直接搞定,後來使用 Struts1(Struts2)+Spring+Hibernate, 嚴格按照分層概念驅動項目開發,這次又使用 Spring MVC取代Struts來進行開發。MVC已經是現代Web開發中的一個很重要的部分,下面介紹一下SpringMVC+Spring3+Hibernate4的開發環境搭建先大致看一下項目結構: 具體的代碼不再示範,主要是走了一個很平常的路線,mvc-servcie-dao-hibernate的結構,源碼可以下載,主要看一下設定檔。解釋見注釋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_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>SpringMVC</display-name>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>    <!-- 配置Spring -->   <context-param>  <param-name>contextConfigLocation</param-name>  <param-value>classpath*:config/spring-*.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/spring-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.hibernate4.support.OpenSessionInViewFilter</filter-class>  </filter>    <filter-mapping>  <filter-name>openSession</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping>  </web-app>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><!-- 註解掃描的包 --><context:component-scan base-package="com.jialin" /><!-- 開啟註解方案1 --><!-- 註解方法處理 --><!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> --><!-- 註解類映射處理 --><!-- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> --><!-- 開啟註解方案2 --><mvc:annotation-driven /><!-- 靜態資源訪問,方案1 --><mvc:resources location="/img/" mapping="/img/**" /><mvc:resources location="/js/" mapping="/js/**" /><!-- 靜態資源訪問,方案2 --><!-- <mvc:default-servlet-handler/> --><!-- 視圖解釋類 --><bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/"></property><!--可為空白,方便實現自已的依據副檔名來選擇視圖解釋類的邏輯 --><property name="suffix" value=".jsp"></property></bean><!-- 上傳檔案bean --><!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8" /> <property name="maxUploadSize" value="10485760000" /> <property name="maxInMemorySize" value="40960" /> </bean> --></beans>  
spring-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><!-- 配置資料來源 --><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://127.0.0.1/springmvc" /><property name="username" value="root" /><property name="password" value="123456" /></bean><!--  配置hibernate SessionFactory--><bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop><prop key="hibernate.hbm2ddl.auto">update</prop><prop key="hibernate.show_sql">true</prop><prop key="hiberante.format_sql">true</prop></props></property><property name="configLocations"><list><value>classpath*:config/hibernate/hibernate.cfg.xml</value></list></property></bean>    <!-- 交易管理員 --><bean id="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean>        <!-- 事務代理類 --><bean id="transactionBese"class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"lazy-init="true" abstract="true"><property name="transactionManager" ref="transactionManager"></property><property name="transactionAttributes"><props><prop key="add*">PROPAGATION_REQUIRED,-Exception</prop><prop key="update*">PROPAGATION_REQUIRED,-Exception</prop><prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop><prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop><prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop><prop key="del*">PROPAGATION_REQUIRED,-Exception</prop><prop key="get*">PROPAGATION_NEVER</prop></props></property></bean></beans>  
         spring-core.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"   xmlns:context="http://www.springframework.org/schema/context"   xmlns:p="http://www.springframework.org/schema/p"   xmlns:mvc="http://www.springframework.org/schema/mvc"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">         <!-- 引入其他設定檔,可以為多個 -->    <import resource="classpath*:config/spring/spring-user.xml"/> </beans>  
         spring-user.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">]><beans>    <!-- Spring Bean --><bean id="userDao" class="com.jialin.dao.UserDao"><property name="sessionFactory" ref="sessionFactory"></property></bean><bean id="userManagerBase" class="com.jialin.service.UserManager"><property name="userDao" ref="userDao"></property></bean><!-- parent為transactionBese,表示支援事務 --><bean id="userManager" parent="transactionBese"><property name="target" ref="userManagerBase"></property></bean></beans>
           hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>        <!-- 引入需要映射的類 -->        <mapping class="com.jialin.entity.User"/>    </session-factory></hibernate-configuration>
下面再來看看Controller
package com.jialin.controller;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.jialin.entity.User;import com.jialin.service.IUserManager;@Controller   //類似Struts的Action@RequestMapping("/user")  public class UserController {@Resource(name="userManager")  // 擷取spring設定檔中bean的id為userManager的,並注入private IUserManager userManager;@RequestMapping("/addUser")   // 請求url地址映射,類似Struts的action-mappingpublic String addUser(User user){if(userManager.addUser(user)){// 重新導向return "redirect:/user/getAllUser";}else{return "/fail";}}@RequestMapping("/updateUser")public String updateUser(User user,HttpServletRequest request){if (userManager.updateUser(user)){user = userManager.getOneUser(user);request.setAttribute("user", user);return "/UserEdit";}else{return "/fail";}}@RequestMapping("/delUser")public void delUser(User user,HttpServletResponse response){String result = "{\"result\":\"error\"}";if(userManager.delUser(user)){result = "{\"result\":\"success\"}";}PrintWriter out = null;response.setContentType("application/json");try {out = response.getWriter();out.write(result);} catch (IOException e) {e.printStackTrace();}}@RequestMapping("/toAddUser")public String toAddUser(){return "/UserAdd";}@RequestMapping("/toUpdateUser")public String toUpdateUser(User user,HttpServletRequest request){User user1=userManager.getOneUser(user);request.setAttribute("user1", user1);return "/UserEdit";}@RequestMapping("/getAllUser")public String getAllUser(HttpServletRequest request){List userList=userManager.getAllUser();request.setAttribute("userlist", userList);return "/UserMain";}}
源碼下載……下面還會介紹一些Struts2與SpringMVC的區別  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.