Java框架篇:Spring+SpringMVC+hibernate整合開發。本站提示廣大學習愛好者:(Java框架篇:Spring+SpringMVC+hibernate整合開發)文章只能為提供參考,不一定能成為您想要的結果。以下是Java框架篇:Spring+SpringMVC+hibernate整合開發正文
前言:
最近沒什麼事做,搭個框架寫成博客記載上去,拉通一下之前所學知識.
話不多說,我們直接步入正題。
預備任務:
1/裝置並配置java運轉環境
2/數據庫的裝置配置(Mysql)
3/裝置並配置服務器(Tomcat)
4/Maven
5/ IntelliJIDEA的裝置配置(自己運用的次要軟件是IntelliJIDEA,沒用eclipse什麼的)
6/ 運用IntelliJIDEA創立一個web app項目。
貌似就這些了吧
導包
不同於以往的導包,由於我們創立的是maven的webapp項目,所以如今只需配置下pomxml這個配置文件,零碎會自動到maven的地方倉庫去下載相應的包.
自己的pom.xml配置文件如下(都寫有闡明的哈):
<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> <groupId>XRog</groupId> <artifactId>ssh</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>ssh Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 自己將配置包的版本信息都一致放入此處,方便當前管理--> <properties> <springVersion>4.3.1.RELEASE</springVersion> <hibernateVersion>4.3.5.Final</hibernateVersion> <jstlVersion>1.2</jstlVersion> <taglibVersion>1.1.2</taglibVersion> <servletVersion>3.0-alpha-1</servletVersion> <jsonVersion>1.9.13</jsonVersion> <jacksonVersion>2.5.0</jacksonVersion> <mysqlVersion>6.0.3</mysqlVersion> <c3p0Version>0.9.1.2</c3p0Version> <log4jVersion>1.2.17</log4jVersion> <fileuploadVersion>1.3.1</fileuploadVersion> <lombokVersion>1.16.10</lombokVersion> </properties> <dependencies> <!-- 單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${springVersion}</version> </dependency> <!-- spring web + spring MVC--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${springVersion}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${springVersion}</version> </dependency> <!-- hibernate配置--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernateVersion}</version> </dependency> <!-- hibernate 緩存, 視狀況添加--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>${hibernateVersion}</version> </dependency> <!-- jsp頁面運用的jstl支持--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstlVersion}</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibVersion}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servletVersion}</version> <scope>provided</scope> </dependency> <!-- DataBase數據庫銜接 mysql包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysqlVersion}</version> </dependency> <!-- 數據庫銜接池--> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>${c3p0Version}</version> </dependency> <!-- json數據 使springMVC可以前往json值 ,視狀況添加--> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${jsonVersion}</version> </dependency> <!-- Jackson可以輕松的將Java對象轉換成json對象和xml文檔,異樣也可以將json、xml轉換成Java對象--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jacksonVersion}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jacksonVersion}</version> </dependency> <!-- log4j配置, 視狀況添加--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4jVersion}</version> </dependency> <!--文件 上傳--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${fileuploadVersion}</version> </dependency> <!-- lombok插件導包--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombokVersion}</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>ssh</finalName> </build> </project>
OK,配置後運轉下maven,就會自意向地方倉庫下載相應的包啦!(這個就不多說了)。
SpringMVC配置
我如今在這裡把我配置後的構造拿出來給你們看下
我們先配置下SpringMVC的配置:resources/META-INF/spring-mvc.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 啟動注解驅動的spring MVC功用,注冊懇求url和注解POJO類辦法的映射--> <mvc:annotation-driven /> <!-- 對模型視圖稱號的解析,在懇求時模型視圖稱號添加前後綴 --> <context:component-scan base-package="com.ssh" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="views/" /> <!-- 前綴 --> <property name="suffix" value=".jsp" /> <!-- 後綴 --> </bean> <!--這裡是對靜態資源的映射--> <mvc:resources mapping="/js/**" location="/resources/js/" /> <mvc:resources mapping="/css/**" location="/resources/css/" /> <mvc:resources mapping="/img/**" location="/resources/img/" /> </beans>
好了,我們如今修正下web.xml這個配置文件,完善下SpringMVC的配置, 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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- 地址為http://localhost:8080/ 顯示的默許網頁--> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- spring MVC config start--> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 此處指向的的是SpringMVC的配置文件 --> <param-value>classpath:META-INF/spring-mvc.xml</param-value> </init-param> <!--配置容器在啟動的時分就加載這個servlet並實例化--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring MVC config end--> </web-app>
OK,SpringMVC配置完成,如今我們停止一下測試吧
在controller層新建一個MainController,內容如下
package com.ssh.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created by XRog * On 2/1/2017.12:36 AM */ @Controller public class MainController { @RequestMapping(value = "test", method = RequestMethod.GET) public String test(){ // 實踐前往的是views/test.jsp ,spring-mvc.xml中配置過前後綴 return "test"; } }
test.jsp網頁如下:
<html> <body> <center> <h2 >this is my test page!</h2> </center> </body> </html>
重啟Tomcat服務器, 然後閱讀器訪問http://localhost/test如下圖所示:
PS: Tomcat默許端口是8080,我更改了端口號,如若你們為更改,正確的訪問地址是localhost:8080/test
OK,成功訪問。
SpringMVC+Spring整合
這個就非常復雜了, 配置applicationContext.xml這個Spring的配置文件如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- 自動掃描 --> <context:component-scan base-package="com.ssh"> <!-- 掃描時跳過 @Controller 注解的JAVA類(控制器) --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
完善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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- 地址為http://localhost:8080/ 顯示的默許網頁--> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!--加載Spring的配置文件到上下文中去--> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:META-INF/applicationContext.xml </param-value> </context-param> <!-- spring MVC config start--> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 此處指向的的是SpringMVC的配置文件 --> <param-value>classpath:META-INF/spring-mvc.xml</param-value> </init-param> <!--配置容器在啟動的時分就加載這個servlet並實例化--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring MVC config end--> <!-- Spring監聽器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 字符集過濾 --> <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> </web-app>
web.xml配置文件中更改了三處:引入Spring配置文件 Spring的監聽器 以及 字符集過濾
OK,Spring+SpringMVC配置完成,上面我們開端測試:
在service寫一個TestServiceImpl完成TestService接口並完成其test()辦法, 代碼如下:
package com.ssh.service.impl; import com.ssh.service.TestService; import org.springframework.stereotype.Service; /** * Created by XRog * On 2/1/2017.12:58 AM */ @Service public class TestServiceImpl implements TestService { public String test() { return "test"; } }
PS:這裡留意寫@Service注解
MainController控制器更改如下:
package com.ssh.controller; import com.ssh.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by XRog * On 2/1/2017.12:36 AM */ @Controller public class MainController { @Autowired private TestService testService; @RequestMapping(value = "test", method = RequestMethod.GET) public String test(){ // 實踐前往的是views/test.jsp ,spring-mvc.xml中配置過前後綴 return "test"; } @RequestMapping(value = "springtest", method = RequestMethod.GET) public String springTest(){ return testService.test(); } }
控制器這裡我們運用了Spring的依賴注入自動裝配。
在閱讀器中輸出地址http://localhost/springtest調用springtest辦法
yes,成功前往,闡明我們之前的配置沒問題
Spring+SpringMVC+hibernate整合
好了,如今就缺hibernate這個框架了。。 我先給大家看些我搭建好之後的構造圖吧
我們想來編寫config.properties這個配置文件,外面寄存的是hibernate的一些配置
#database connection config jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://?????:3306/ssh?useUnicode=true&characterEncoding=utf-8 jdbc.username = root jdbc.password = ??? #hibernate config hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.show_sql = true hibernate.format_sql = true hibernate.hbm2ddl.auto = update
這裡銜接數據庫的參數由於我是銜接我早晨的數據庫,因而我數據庫地址和密碼打了“???”,你們銜接時改成自己本地的就OK了
上面配置hibernate,這裡我為了方便,就直接寫進applicationContext.xml外面。配置後的applicationContext.xml如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!--********************************************配置Spring***************************************--> <!-- 自動掃描 --> <context:component-scan base-package="com.ssh"> <!-- 掃描時跳過 @Controller 注解的JAVA類(控制器) --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--********************************************配置hibernate********************************************--> <!--掃描配置文件(這裡指向的是之前配置的那個config.properties)--> <context:property-placeholder location="classpath:/config.properties" /> <!--配置數據源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <!--數據庫銜接驅動--> <property name="jdbcUrl" value="${jdbc.url}" /> <!--數據庫地址--> <property name="user" value="${jdbc.username}" /> <!--用戶名--> <property name="password" value="${jdbc.password}" /> <!--密碼--> <property name="maxPoolSize" value="40" /> <!--最大銜接數--> <property name="minPoolSize" value="1" /> <!--最小銜接數--> <property name="initialPoolSize" value="10" /> <!--初始化銜接池內的數據庫銜接--> <property name="maxIdleTime" value="20" /> <!--最大閒暇時間--> </bean> <!--配置session工廠--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="com.ssh.entity" /> <property name="hibernateProperties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate依據實體自動生成數據庫表--> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <!--指定數據庫方言--> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <!--在控制台顯示執行的數據庫操作語句--> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <!--在控制台顯示執行的數據哭操作語句(格式)--> </props> </property> </bean> <!-- 事物管理器配置 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
OK,到了這裡,配置完畢。上面進入測試階段
實體類(entity):
package com.ssh.entity; import lombok.Data; import javax.persistence.*; /** * Created by XRog * On 2/2/2017.2:03 PM */ @Data @Entity @Table(name = "Person") public class Person { @Id @GeneratedValue private Long id; @Column(name = "created") private Long created = System.currentTimeMillis(); @Column(name = "username") private String username; @Column(name = "address") private String address; @Column(name = "phone") private String phone; @Column(name = "remark") private String remark; }
PS:我這裡用了一個@Data注解,此注解會自動生成get辦法,set辦法,toString辦法等一系列辦法,功用非常弱小,不過需求裝置插件以及導包, 有興味的可以百度下
當然,你也可以手動編寫get/set/結構辦法。
數據庫訪問層(repository):
package com.ssh.repository; import java.io.Serializable; import java.util.List; /** * Created by XRog * On 2/2/2017.2:28 PM */ public interface DomainRepository<T,PK extends Serializable>{ T load(PK id); T get(PK id); List<T> findAll(); void persist(T entity); PK save(T entity); void saveOrUpdate(T entity); void delete(PK id); void flush(); }
package com.ssh.repository; import com.ssh.entity.Person; /** * Created by XRog * On 2/2/2017.2:25 PM */ public interface PersonRepository extends DomainRepository<Person,Long> { }
package com.ssh.repository.impl; import com.ssh.repository.PersonRepository; import com.ssh.entity.Person; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by XRog * On 2/2/2017.2:30 PM */ @Repository public class PersonRepositoryImpl implements PersonRepository { @Autowired private SessionFactory sessionFactory; private Session getCurrentSession() { return this.sessionFactory.openSession(); } public Person load(Long id) { return (Person)getCurrentSession().load(Person.class,id); } public Person get(Long id) { return (Person)getCurrentSession().get(Person.class,id); } public List<Person> findAll() { return null; } public void persist(Person entity) { getCurrentSession().persist(entity); } public Long save(Person entity) { return (Long)getCurrentSession().save(entity); } public void saveOrUpdate(Person entity) { getCurrentSession().saveOrUpdate(entity); } public void delete(Long id) { Person person = load(id); getCurrentSession().delete(person); } public void flush() { getCurrentSession().flush(); } }
PS:我這裡顯示寫了一個比擬通用的接口,其他一切接口皆承繼此接口, 再編寫完成類
留意:我這裡寫的session發生是調用的SessionFactory的openSession()這個辦法。之前運用getCurrentSession()不斷報錯,後來百度了一下才知道,hibernate3版本可以運用getCurrentSession()來創立session,而hibernate4版本則不行。
服務層(service):
package com.ssh.service; import com.ssh.entity.Person; /** * Created by XRog * On 2/2/2017.2:39 PM */ public interface PersonService { Long savePerson(); }
package com.ssh.service.impl; import com.ssh.entity.Person; import com.ssh.repository.PersonRepository; import com.ssh.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by XRog * On 2/2/2017.2:40 PM */ @Service public class PersonServiceImpl implements PersonService { @Autowired private PersonRepository personRepository; public Long savePerson() { Person person = new Person(); person.setUsername("XRog"); person.setPhone("18381005946"); person.setAddress("chenDu"); person.setRemark("this is XRog"); return personRepository.save(person); } }
控制層(controller):
package com.ssh.controller; import com.ssh.entity.Person; import com.ssh.service.PersonService; import com.ssh.service.TestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by XRog * On 2/1/2017.12:36 AM */ @Controller public class MainController { @Autowired private PersonService personService; @RequestMapping(value = "savePerson", method = RequestMethod.GET) @ResponseBody public String savePerson(){ personService.savePerson(); return "success!"; } }
OK,編寫終了,我們重啟下服務器然後測試:
我們在看下數據庫,跟我們拔出的數據比照下
OK,測試終了,非常成功
以上就是本文的全部內容,希望本文的內容對大家的學習或許任務能帶來一定的協助,同時也希望多多支持!