先說一下SpringMVC+Spring+Hibernate 框架整合實例流程思路:
流程講解1:
首先訪問會先定位到控制器。這就用到了過濾器配置文件“spring-mvc.xml”。這個文件負責定義控制器的包路徑、視圖的格式等。
其次從“控制器->service層->dao層”,期間用的都是spring的依賴注入,所以就需要一個bean容器配置文件,將所有的“等待被注入的類”在xml文件裡申明一下。這個xml文件就是“spring-beans.xml”。
之後,dao層要操作entity裡面的持久化類。dao必須通過sessionFactory裡面的session才能操作持久化類。於是需要一個xml文件配置sessionFactory類,這個sessionFactory作為一個bean,可被注入到dao層。這個文件還需要將“entity裡面所有的持久化類”申明出來。這個文件就是“spring-hibernate.xml”。
最後將這些xml配置文件全部在web.xml裡面加載。
流程講解2:
通過url地址,定位到控制器的具體方法。
之後控制器調用service層的實例做點什麼(service層的實例是注入進來的)並且返回一個jsp頁面。
service層的實例再調用dao層的實例做點什麼(dao層的實例是注入進來的)。
dao層是底層數據層,dao層的實例通過sessionFactory來創建一個session操作具體的持久化類對象(sessionFactory對象是被注入進來的)對數據庫進行“增刪查改”等操作。
流程講解3:
這個實例具體干的事是:UserDaoImpl從數據庫裡查詢出用戶信息列表,並將用戶信息列表返回給UserServiceImpl。
UserServiceImpl經過處理得到某一個用戶的用戶名,並將用戶名返回給控制器。
控制器再將這個用戶名打印出來,然後調用一下視圖jsp文件。
結構如下:
pom.xml:<?xml version="1.0" encoding="UTF-8"?> <!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>java-ssh-demo3</name> <groupId>java-ssh-demo</groupId> <artifactId>java-ssh-demo3</artifactId> <version>1.0-SNAPSHOT</version> <!--項目依賴 --> <dependencies> <!--日志包--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <!--j2ee相關包 servlet、jsp、jstl--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--spring相關包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.1.RELEASE</version> </dependency> <!--其他需要的包--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- hibernate內置日志記錄所需包--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.21</version> </dependency> <!--mariadb驅動--> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>1.5.5</version> </dependency> <!-- 代碼生成類庫 --> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2.2</version> </dependency> <!--hibernate包--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.6.Final</version> </dependency> <!--hibernate校驗器--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> </dependencies> <build> <finalName>maven-springmvc</finalName> <resources> <!--表示把java目錄下的有關xml文件,properties文件編譯/打包的時候放在resource目錄下--> <resource> <directory>${basedir}/src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> <resource> <directory>${basedir}/src/main/resources</directory> </resource> </resources> <plugins> <!--servlet容器 jetty插件--> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.3.10.v20160621</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>java-springmvc-demo5</display-name> <!-- 配置Spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring-*.xml</param-value> </context-param> <!--listener用於在Web 應用啟動時,啟動某些後台程序,此處啟動的是spring--> <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> <!-- 默認的servlet.xml文件是放在WEB-INF目錄下,名稱與<servlet-name>的名字要相關。但可以通過以下設置重新自定義servlet.xml配置文件的位置和名稱。--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring-mvc.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> <!--歡迎頁面--> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 設置OpenSessionInViewFilter 的過濾器,由 Spring 來控制 Hibernate 的 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>
spring-mvc.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 啟動時自動掃描該包下所有的Bean --> <context:component-scan base-package="pers.cly.ssh_demo3.controller" /> <!-- 添加注解驅動 --> <mvc:annotation-driven /> <!--所有的訪問都統一先由InternalResourceViewResolver類處理--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--定義跳轉的文件的前綴(jsp文件所在目錄)--> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 定義跳轉的文件的後綴 --> <property name="suffix" value=".jsp" /> </bean> </beans>
spring-beans.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:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--啟動時自動掃描該包下所有的Bean--> <context:component-scan base-package="pers.cly.ssh_demo3" /> <!--注冊一個UserDaoImpl對象,實例名為“userDao”--> <bean id="userDao" class="pers.cly.ssh_demo3.dao.impl.UserDaoImpl"/> <!--注冊一個UserServiceImpl對象,實例名為“userService”--> <bean id="userService" class="pers.cly.ssh_demo3.service.impl.UserServiceImpl"/> </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: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/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd "> <!-- 聲明事務管理器 --> <bean id="myHibTxManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 定義事務通知 --> <tx:advice id="tx_Advice" transaction-manager="myHibTxManager"> <!-- 定義事務傳播規則 --> <tx:attributes> <!-- 對get/load/search開頭的方法應用只讀事務規則 --> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> <tx:method name="load*" propagation="SUPPORTS" read-only="true" /> <tx:method name="search*" propagation="SUPPORTS" read-only="true" /> <!-- 對其他方法應用REQUIRED事務規則 --> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!--<aop:config>--> <!--<!– 對com.zxpm.biz包下的所有類的所有方法都應用事務規則 –>--> <!--<aop:pointcut id="bizMethods"--> <!--expression="execution(* cn.zifangsky.service.*.*(..))" />--> <!--<!– 將事務通知和切面組合 –>--> <!--<aop:advisor advice-ref="tx_Advice" pointcut-ref="bizMethods" />--> <!--</aop:config>--> <!-- 配置數據源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.mariadb.jdbc.Driver"></property> <property name="url" value="jdbc:mariadb://localhost:3306/daixu"></property> <property name="username" value="root"></property> <property name="password" value="123"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan"> <list> <!-- 申明entity中所有持久化類 --> <value>pers.cly.ssh_demo3.entity</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> </beans>
HelloController.java:
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import pers.cly.ssh_demo3.service.UserService; import javax.annotation.Resource; @Controller//該注解用來識別控制器 @RequestMapping("hello")//該注解用來控制url書寫時,控制器的選擇 public class HelloController { @Resource(name="userService") // 獲取spring配置文件中bean的id為userService的具體實現類,並注入 private UserService userServiceImpl;//service層的用戶接口類。 @RequestMapping("helloworld")//該注解用來控制url書寫時,具體方法的選擇(還可以綁定參數等) public String helloworld() { System.out.print("用戶姓名:"+userServiceImpl.select_user_name());//調用接口方法獲取用戶姓名,打印用戶姓名 return "hello_world";//跳轉到jsp頁面 } }
UserService.java:
import pers.cly.ssh_demo3.entity.UserEntity; /** * Created by CLY on 2016/12/26. */ public interface UserService { public String select_user_name();//這個方法負責查詢用戶姓名 }
UserServiceImpl.java:
import pers.cly.ssh_demo3.dao.UserDao; import pers.cly.ssh_demo3.entity.UserEntity; import pers.cly.ssh_demo3.service.UserService; import javax.annotation.Resource; import java.util.List; /** * Created by CLY on 2016/12/26. */ public class UserServiceImpl implements UserService { @Resource(name = "userDao")//使用注解配置,將id為“userDao”的bean注入到“userDaoImpl”裡面 private UserDao userDaoImpl;//定義dao層的“接口” @Override public String select_user_name() { String user_name=""; List<UserEntity> users = userDaoImpl.select_user();//通過接口方法,獲取用信息列表 for (UserEntity u : users) {//迭代列表,將裡面的最後一個用戶的姓名提取出來 user_name = u.getUserName(); } return user_name;//返回用戶名 } }
UserDao.java:
import pers.cly.ssh_demo3.entity.UserEntity; import java.util.List; /** * Created by CLY on 2016/12/26. */ public interface UserDao { public List<UserEntity> select_user();//將用戶信息查出,並返回用用戶持久化類列表 }
UserDaoImpl.java:
import org.hibernate.SessionFactory; import org.hibernate.query.Query; import pers.cly.ssh_demo3.dao.UserDao; import pers.cly.ssh_demo3.entity.UserEntity; import javax.annotation.Resource; import java.util.List; /** * Created by CLY on 2016/12/26. */ public class UserDaoImpl implements UserDao { @Resource(name = "sessionFactory") private SessionFactory sessionFactory;//注入sessionFactory @Override public List<UserEntity> select_user() { String hql = "from UserEntity";//hql語句 Query query = sessionFactory.getCurrentSession().createQuery(hql); return query.list(); } }
UserEntity.java是我用idea根據表自動生成,就不貼代碼了。
hello_world.jsp和index.jsp寫什麼隨意,也不貼代碼了。
之後用“http://localhost:8080/hello/helloworld”路徑可訪問出結果。