SpringMVC+Spring+Hibernate整合开发

最近突然想认真研究下java web常用框架,虽然现在一直在用,但实现的整体流程不是很了解,就在网上搜索资料,尝试自己搭建,以下是自己的搭建及测试过程。

一、准备工作:

     1/安装并配置java运行环境

     2/数据库的安装配置(Mysql)

     3/安装并配置服务器(Tomcat)

     4/ IntelliJIDEA的安装配置(本人使用的主要软件是IntelliJIDEA)

     5/ 使用IntelliJIDEA创建一个web app项目

二、下载jar包(也可以用maven)

springMVC及spring需要的jar包spring-core.jar,spring-beans.jar,spring-web.jar,spring-webmvc.jar等

参考:https://www.cnblogs.com/leskang/p/5426829.html

Hibernate4需要的jar包antlr-2.7.7.jar,dom4j-1.6.1.jar,hibernate-core-4.2.21.Final.jar,hibernate-commons-annotations-4.0.2.Final.jar等

参考:https://blog.csdn.net/doodoofish/article/details/43207

三、文件结构

四、配置文件

1.springMVC配置

resources/config/springMVC-servlet.xml

 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:mvc="http://www.springframework.org/schema/mvc"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xsi:schemaLocation="http://www.springframework.org/schema/mvc
 7        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
 8        http://www.springframework.org/schema/beans
 9        http://www.springframework.org/schema/beans/spring-beans.xsd
10        http://www.springframework.org/schema/context
11        http://www.springframework.org/schema/context/spring-context-3.1.xsd">
12 
13     <!-- 定义controller扫描包 -->
14     <context:component-scan base-package="com.qc.mall" >
15         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
16     </context:component-scan>
17     <mvc:annotation-driven />
18 
19     <!-- 配置视图解析器 -->
20     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
21         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
22         <property name="prefix" value="/WEB-INF/views/"/>
23         <property name="suffix" value=".jsp"/>
24     </bean>
25     <!--这里是对静态资源的映射-->
26     <mvc:resources mapping="/js/**" location="/WEB-INF/views/js/" />
27     <mvc:resources mapping="/css/**" location="/WEB-INF/views/css/" />
28     <mvc:resources mapping="/img/**" location="/WEB-INF/views/images/" />
29 
30     <mvc:default-servlet-handler/>
31 </beans>

对应web.xml,包括springMVC的配置,且添加了字符集过滤:

 1  <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5          version="4.0">
 6     <!-- spring MVC config start-->
 7     <servlet>
 8         <servlet-name>springMVC</servlet-name>
 9         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
10         <init-param>
11             <param-name>contextConfigLocation</param-name>
12             <!-- 此处指向的的是SpringMVC的配置文件 -->
13             <param-value>classpath:config/springMVC-servlet.xml</param-value>
14         </init-param>
15         <!--配置容器在启动的时候就加载这个servlet并实例化-->
16         <load-on-startup>1</load-on-startup>
17     </servlet>
18 
19     <servlet-mapping>
20         <servlet-name>springMVC</servlet-name>
21         <url-pattern>/</url-pattern>
22     </servlet-mapping>
23     <!-- spring MVC config end-->
24     <!--  字符集过滤  -->
25     <filter>
26         <filter-name>encodingFilter</filter-name>
27         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
28         <init-param>
29             <param-name>encoding</param-name>
30             <param-value>UTF-8</param-value>
31         </init-param>
32         <init-param>
33             <param-name>forceEncoding</param-name>
34             <param-value>true</param-value>
35         </init-param>
36     </filter>
37     <filter-mapping>
38         <filter-name>encodingFilter</filter-name>
39         <url-pattern>/*</url-pattern>
40     </filter-mapping>
41 
42     <welcome-file-list>
43         <welcome-file>views/test.jsp</welcome-file>
44     </welcome-file-list>
45 </web-app>

然后写个测试方法测试下

在controller层新建一个MainController,内容如下:

 1 package com.qc.mall.controller;
 2 
 3 import com.qc.mall.webservice.TestService;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.web.bind.annotation.RequestMethod;
 7 
 8 @Controller
 9 public class MainController {
10     @Autowired
11     private TestService testService;
12 
13     @RequestMapping(value = "test", method = RequestMethod.GET)
14     public String test(){
15 //        实际返回的是views/test.jsp ,spring-mvc.xml中配置过前后缀
16         return "test";
17     }
18 }

test.jsp内容如下:

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 <center>
 8     <h2 style="color: #ff261a;">this is my test page!</h2>
 9 </center>
10 </body>
11 </html>

启动Tomcat,在浏览器中访问http://mall.jincaidongli.com:8080/test(这里我配置的自己的域名)。

成功!

2.SpringMVC+Spring整合

配置applicationContext.xml 这个Spring的配置文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
 4        xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 5        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
 6        xmlns:mvc="http://www.springframework.org/schema/mvc"  xmlns:p="http://www.springframework.org/schema/p"
 7        xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
 8        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
10         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
11         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
12         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
13         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
14         http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
15         http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
16         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
17         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
18         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
19         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"
20        default-lazy-init="false">
21 
22     <!--********************************************配置Spring***************************************-->
23     <!-- 配置自动扫描的包 -->
24     <context:component-scan base-package="com.qc.mall">
25         <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
26         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
27     </context:component-scan>
28     <context:property-placeholder location="classpath:config/config.properties"/>
29     <aop:config proxy-target-class="true"></aop:config>
30 
31     <!-- 事物管理器配置  -->
32     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
33         <property name="sessionFactory" ref="sessionFactory" />
34     </bean>
35     <!-- 开启事务注解-->
36     <tx:annotation-driven transaction-manager="transactionManager"  />
37 
38 </beans>

我这里把头文件全部写上了,因为之前因为头文件不全导致,编译一直不成功。

web.xml配置:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5          version="4.0">
 6 
 7     <!--加载Spring的配置文件到上下文中去-->
 8     <context-param>
 9         <param-name>contextConfigLocation</param-name>
10         <param-value>
11             classpath:/config/applicationContext.xml
12         </param-value>
13     </context-param>
14 
15     <!-- spring MVC config start-->
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             <!-- 此处指向的的是SpringMVC的配置文件 -->
22             <param-value>classpath:config/springMVC-servlet.xml</param-value>
23         </init-param>
24         <!--配置容器在启动的时候就加载这个servlet并实例化-->
25         <load-on-startup>1</load-on-startup>
26     </servlet>
27 
28     <servlet-mapping>
29         <servlet-name>springMVC</servlet-name>
30         <url-pattern>/</url-pattern>
31     </servlet-mapping>
32     <!-- spring MVC config end-->
33 
34     <!-- Spring监听器 -->
35     <listener>
36         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
37     </listener>
38 
39     <!--  字符集过滤  -->
40     <filter>
41         <filter-name>encodingFilter</filter-name>
42         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
43         <init-param>
44             <param-name>encoding</param-name>
45             <param-value>UTF-8</param-value>
46         </init-param>
47         <init-param>
48             <param-name>forceEncoding</param-name>
49             <param-value>true</param-value>
50         </init-param>
51     </filter>
52     <filter-mapping>
53         <filter-name>encodingFilter</filter-name>
54         <url-pattern>/*</url-pattern>
55     </filter-mapping>
56 
57     <welcome-file-list>
58         <welcome-file>views/test.jsp</welcome-file>
59     </welcome-file-list>
60 </web-app>

配置完成,开始测试:

TestService.java

 1 package com.qc.mall.webservice;
 2 
 3 import org.springframework.stereotype.Service;
 4 import org.springframework.transaction.annotation.Transactional;
 5 
 6 @Service
 7 @Transactional
 8 public class TestService {
 9     public String test() {
10         return "test";
11     }
12 }

MainController控制器代码如下:

 1 package com.qc.mall.controller;
 2 
 3 import com.qc.mall.webservice.TestService;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RequestMethod;
 8 import org.springframework.web.bind.annotation.ResponseBody;
 9 
10 @Controller
11 public class MainController {
12     @Autowired
13     private TestService testService;
14 
15     @RequestMapping(value = "test", method = RequestMethod.GET)
16     public String test(){
17 //        实际返回的是views/test.jsp ,spring-mvc.xml中配置过前后缀
18         return "test";
19     }
20 
21     @RequestMapping(value = "springtest", method = RequestMethod.GET)
22     public String springTest(){
23         return testService.test();
24     }
25 }

重启Tomcat,在浏览器地址栏输入http://mall.jincaidongli.com:8080/springtest

测试成功!

3.SpringMVC+Spring+Hibernate整合

首先配置下数据库连接及hibernate配置信息文件,config.properties

 1 jdbc.driver=com.mysql.jdbc.Driver
 2 jdbc.url=jdbc:mysql://127.0.0.1:3306/qcshop?useUnicode=true&amp;characterEncoding=utf8
 3 jdbc.username=root
 4 jdbc.password=root
 5 
 6 #hibernate config
 7 hibernate.dialect = org.hibernate.dialect.MySQLDialect
 8 hibernate.show_sql = true
 9 hibernate.format_sql = true
10 hibernate.hbm2ddl.auto = update

 接下来配置hibernate,将其配置到applicationapplicationContext.xml文件中:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
 4        xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 5        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
 6        xmlns:mvc="http://www.springframework.org/schema/mvc"  xmlns:p="http://www.springframework.org/schema/p"
 7        xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
 8        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
10         http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
11         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
12         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
13         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
14         http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
15         http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
16         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
17         http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
18         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
19         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"
20        default-lazy-init="false">
21 
22     <!--********************************************配置Spring***************************************-->
23     <!-- 配置自动扫描的包 -->
24     <context:component-scan base-package="com.qc.mall">
25         <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
26         <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
27     </context:component-scan>
28     <context:property-placeholder location="classpath:config/config.properties"/>
29     <aop:config proxy-target-class="true"></aop:config>
30 
31     <!--********************************************配置hibernate********************************************-->
32     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
33         <property name="driverClass" value="${jdbc.driver}" />  <!--数据库连接驱动-->
34         <property name="jdbcUrl" value="${jdbc.url}" />     <!--数据库地址-->
35         <property name="user" value="${jdbc.username}" />   <!--用户名-->
36         <property name="password" value="${jdbc.password}" />   <!--密码-->
37         <property name="maxPoolSize" value="40" />      <!--最大连接数-->
38         <property name="minPoolSize" value="1" />       <!--最小连接数-->
39         <property name="initialPoolSize" value="10" />      <!--初始化连接池内的数据库连接-->
40         <property name="maxIdleTime" value="20" />  <!--最大空闲时间-->
41     </bean>
42 
43     <!--配置session工厂-->
44     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
45         <property name="dataSource" ref="dataSource" />
46         <property name="hibernateProperties">
47             <props>
48                 <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
49                 <prop key="hibernate.dialect">${hibernate.dialect}</prop>           <!--指定数据库方言-->
50                 <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>         <!--在控制台显示执行的数据库操作语句-->
51                 <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>     <!--在控制台显示执行的数据哭操作语句(格式)-->
52             </props>
53         </property>
54         <!-- hibernate 映射文件  设置为自动扫描包目录-->
55         <property name="packagesToScan">
56             <list>
57                 <value>com.qc.mall.entity</value>
58             </list>
59         </property>
60     </bean>
61 
62     <!-- 事物管理器配置  -->
63     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
64         <property name="sessionFactory" ref="sessionFactory" />
65     </bean>
66     <!-- 开启事务注解-->
67     <tx:annotation-driven transaction-manager="transactionManager"  />
68 
69 </beans>

配置结束,整体测试。

实体类(Entity)

 1 package com.qc.mall.entity;
 2 
 3 import javax.persistence.*;
 4 
 5 @Entity
 6 @Table(name = "Person")
 7 public class Person {
 8 
 9     private Long id;
10     private Long created = System.currentTimeMillis();
11     private String username;
12     private String address;
13     private String phone;
14     private String remark;
15 
16     @Id
17     @GeneratedValue
18     public Long getId() {
19         return id;
20     }
21 
22     public void setId(Long id) {
23         this.id = id;
24     }
25 
26     public Long getCreated() {
27         return created;
28     }
29 
30     public void setCreated(Long created) {
31         this.created = created;
32     }
33 
34     public String getUsername() {
35         return username;
36     }
37 
38     public void setUsername(String username) {
39         this.username = username;
40     }
41 
42     public String getAddress() {
43         return address;
44     }
45 
46     public void setAddress(String address) {
47         this.address = address;
48     }
49 
50     public String getPhone() {
51         return phone;
52     }
53 
54     public void setPhone(String phone) {
55         this.phone = phone;
56     }
57 
58     public String getRemark() {
59         return remark;
60     }
61 
62     public void setRemark(String remark) {
63         this.remark = remark;
64     }
65 }

数据库访问层(DAO)

1 package com.qc.mall.dao;
2 
3 
4 import com.qc.mall.entity.Person;
5 
6 public interface PersonDao extends BaseDao<Person,Long> { }

dao层实现类

 1 package com.qc.mall.dao.impl;
 2 
 3 import com.qc.mall.dao.PersonDao;
 4 import com.qc.mall.entity.Person;
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Repository;
 9 
10 import java.util.List;
11 
12 @Repository
13 public class PersonDaoImpl implements PersonDao {
14 
15     @Autowired
16     private SessionFactory sessionFactory;
17 
18     private Session getCurrentSession() {
19         return this.sessionFactory.openSession();
20     }
21 
22     public Person load(Long id) {
23         return (Person)getCurrentSession().load(Person.class,id);
24     }
25 
26     public Person get(Long id) {
27         return (Person)getCurrentSession().get(Person.class,id);
28     }
29 
30     public List<Person> findAll() {
31         return null;
32     }
33 
34     public void persist(Person entity) {
35         getCurrentSession().persist(entity);
36     }
37 
38     public Long save(Person entity) {
39         return (Long)getCurrentSession().save(entity);
40     }
41 
42     public void saveOrUpdate(Person entity) {
43         getCurrentSession().saveOrUpdate(entity);
44     }
45 
46     public void delete(Long id) {
47         Person person = load(id);
48         getCurrentSession().delete(person);
49     }
50 
51     public void flush() {
52         getCurrentSession().flush();
53     }
54 }

 业务层(Service)

 1 package com.qc.mall.service;
 2 
 3 
 4 import com.qc.mall.dao.PersonDao;
 5 import com.qc.mall.entity.Person;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 import org.springframework.transaction.annotation.Transactional;
 9 
10 @Service
11 @Transactional
12 public class  PersonService {
13 
14     @Autowired
15     private PersonDao personDao;
16 
17     public Long savePerson() {
18         Person person = new Person();
19         person.setUsername("sijizhen");
20         person.setPhone("1526568652");
21         person.setAddress("sijizhen");
22         person.setRemark("this is sijizhen");
23         return personDao.save(person);
24     }
25 }

控制层(Controller)

 1 package com.qc.mall.controller;
 2 
 3 import com.qc.mall.service.PersonService;
 4 import com.qc.mall.webservice.TestService;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.bind.annotation.RequestMethod;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 
11 @Controller
12 public class MainController {
13     @Autowired
14     private TestService testService;
15     @Autowired
16     private PersonService personService;
17 
18     @RequestMapping(value = "test", method = RequestMethod.GET)
19     public String test(){
20 //        实际返回的是views/test.jsp ,spring-mvc.xml中配置过前后缀
21         return "test";
22     }
23 
24     @RequestMapping(value = "springTest", method = RequestMethod.GET)
25     public String springTest(){
26         return testService.test();
27     }
28 
29     @RequestMapping(value = "savePerson", method = RequestMethod.GET)
30     @ResponseBody
31     public String savePerson(){
32         personService.savePerson();
33         return "success!";
34     }
35 }

重启Tomcat,在浏览器中访问http://mall.jincaidongli.com:8080/savePerson

查看数据库数据:

完成!

参考:https://www.cnblogs.com/xrog/p/6359706.html

猜你喜欢

转载自www.cnblogs.com/sijizhen/p/10042204.html