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

三、文件结构

SpringMVC+Spring+Hibernate整合开发

四、配置文件

1.springMVC配置

resources/config/springMVC-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- 定义controller扫描包 -->
<context:component-scan base-package="com.qc.mall" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
<mvc:annotation-driven /> <!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--这里是对静态资源的映射-->
<mvc:resources mapping="/js/**" location="/WEB-INF/views/js/" />
<mvc:resources mapping="/css/**" location="/WEB-INF/views/css/" />
<mvc:resources mapping="/img/**" location="/WEB-INF/views/images/" /> <mvc:default-servlet-handler/>
</beans>

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

  <?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_4_0.xsd"
version="4.0">
<!-- spring MVC config start-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 此处指向的的是SpringMVC的配置文件 -->
<param-value>classpath:config/springMVC-servlet.xml</param-value>
</init-param>
<!--配置容器在启动的时候就加载这个servlet并实例化-->
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring MVC config end-->
<!-- 字符集过滤 -->
<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> <welcome-file-list>
<welcome-file>views/test.jsp</welcome-file>
</welcome-file-list>
</web-app>

然后写个测试方法测试下

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

 package com.qc.mall.controller;

 import com.qc.mall.webservice.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod; @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";
}
}

test.jsp内容如下:

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<center>
<h2 style="color: #ff261a;">this is my test page!</h2>
</center>
</body>
</html>

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

SpringMVC+Spring+Hibernate整合开发

成功!

2.SpringMVC+Spring整合

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

 <?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:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"
default-lazy-init="false"> <!--********************************************配置Spring***************************************-->
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.qc.mall">
<!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:config/config.properties"/>
<aop:config proxy-target-class="true"></aop:config> <!-- 事物管理器配置 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager" /> </beans>

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

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_4_0.xsd"
version="4.0"> <!--加载Spring的配置文件到上下文中去-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/config/applicationContext.xml
</param-value>
</context-param> <!-- spring MVC config start-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 此处指向的的是SpringMVC的配置文件 -->
<param-value>classpath:config/springMVC-servlet.xml</param-value>
</init-param>
<!--配置容器在启动的时候就加载这个servlet并实例化-->
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springMVC</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> <welcome-file-list>
<welcome-file>views/test.jsp</welcome-file>
</welcome-file-list>
</web-app>

配置完成,开始测试:

TestService.java

 package com.qc.mall.webservice;

 import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; @Service
@Transactional
public class TestService {
public String test() {
return "test";
}
}

MainController控制器代码如下:

 package com.qc.mall.controller;

 import com.qc.mall.webservice.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; @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();
}
}

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

SpringMVC+Spring+Hibernate整合开发

测试成功!

3.SpringMVC+Spring+Hibernate整合

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

 jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/qcshop?useUnicode=true&amp;characterEncoding=utf8
jdbc.username=root
jdbc.password=root #hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

接下来配置hibernate,将其配置到applicationapplicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:task="http://www.springframework.org/schema/task" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"
default-lazy-init="false"> <!--********************************************配置Spring***************************************-->
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.qc.mall">
<!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:config/config.properties"/>
<aop:config proxy-target-class="true"></aop:config> <!--********************************************配置hibernate********************************************-->
<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="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>
<!-- hibernate 映射文件 设置为自动扫描包目录-->
<property name="packagesToScan">
<list>
<value>com.qc.mall.entity</value>
</list>
</property>
</bean> <!-- 事物管理器配置 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager" /> </beans>

配置结束,整体测试。

实体类(Entity)

 package com.qc.mall.entity;

 import javax.persistence.*;

 @Entity
@Table(name = "Person")
public class Person { private Long id;
private Long created = System.currentTimeMillis();
private String username;
private String address;
private String phone;
private String remark; @Id
@GeneratedValue
public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public Long getCreated() {
return created;
} public void setCreated(Long created) {
this.created = created;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public String getRemark() {
return remark;
} public void setRemark(String remark) {
this.remark = remark;
}
}

数据库访问层(DAO)

 package com.qc.mall.dao;

 import com.qc.mall.entity.Person;

 public interface PersonDao extends BaseDao<Person,Long> { }

dao层实现类

 package com.qc.mall.dao.impl;

 import com.qc.mall.dao.PersonDao;
import com.qc.mall.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; @Repository
public class PersonDaoImpl implements PersonDao { @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();
}
}

业务层(Service)

 package com.qc.mall.service;

 import com.qc.mall.dao.PersonDao;
import com.qc.mall.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; @Service
@Transactional
public class PersonService { @Autowired
private PersonDao personDao; public Long savePerson() {
Person person = new Person();
person.setUsername("sijizhen");
person.setPhone("1526568652");
person.setAddress("sijizhen");
person.setRemark("this is sijizhen");
return personDao.save(person);
}
}

控制层(Controller)

 package com.qc.mall.controller;

 import com.qc.mall.service.PersonService;
import com.qc.mall.webservice.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; @Controller
public class MainController {
@Autowired
private TestService testService;
@Autowired
private PersonService personService; @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();
} @RequestMapping(value = "savePerson", method = RequestMethod.GET)
@ResponseBody
public String savePerson(){
personService.savePerson();
return "success!";
}
}

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

SpringMVC+Spring+Hibernate整合开发

查看数据库数据:

SpringMVC+Spring+Hibernate整合开发

完成!

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

上一篇:php中的字符串常用函数(一) strpos() 子字符首次出现的位置


下一篇:UVALive 7327 Digit Division (模拟)