欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java框架篇:Spring+SpringMVC+hibernate整合开发

程序员文章站 2024-03-08 08:31:27
前言: 最近没什么事做,搭个框架写成博客记录下来,拉通一下之前所学知识. 话不多说,我们直接步入正题。 准备工作:   1/安装并配置java运行环境   2/数...

前言:

最近没什么事做,搭个框架写成博客记录下来,拉通一下之前所学知识.

话不多说,我们直接步入正题。

准备工作:

  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配置

我现在在这里把我配置后的结构拿出来给你们看下

 Java框架篇:Spring+SpringMVC+hibernate整合开发

我们先配置下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 style="color: #ff261a;">this is my test page!</h2>
</center>
</body>
</html>

重启tomcat服务器, 然后浏览器访问如下图所示:

 Java框架篇:Spring+SpringMVC+hibernate整合开发

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的依赖注入自动装配。

在浏览器中输入地址调用springtest方法    

 Java框架篇:Spring+SpringMVC+hibernate整合开发

yes,成功返回,说明我们之前的配置没问题

spring+springmvc+hibernate整合

好了,现在就缺hibernate这个框架了。。 我先给大家看些我搭建好之后的结构图吧

 Java框架篇:Spring+SpringMVC+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,编写完毕,我们重启下服务器然后测试:

Java框架篇:Spring+SpringMVC+hibernate整合开发

我们在看下数据库,跟我们插入的数据对比下

Java框架篇:Spring+SpringMVC+hibernate整合开发

Java框架篇:Spring+SpringMVC+hibernate整合开发

ok,测试完毕,十分成功

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!