Spring+SpringMVC+Hibernate三大框架整合的SSH

Spring 同时被 3 个专栏收录
2 篇文章 0 订阅
2 篇文章 0 订阅
2 篇文章 0 订阅

1、三大框架简介

1.1、Spring

Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。
简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式) 轻量级开源框架。

1.2、SpringMVC

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。
Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。
使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等。

1.3、Hibernate

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系。
是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。
Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序使用,也可以在Servlet/JSP的Web应用中使用。
最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成数据持久化的重任。

2、三大框架整合步骤

2.1、准备工作

①安装JDK;
②安装Tomcat;
③安装Maven;
④安装一个IDE,如IntelliJ IDEA或者Eclipse等;

2.2、配置步骤

①创建一个Maven的webapp项目;
②在main目录下新建一个java的目录。如果使用的是IntelliJ IDEA,右键将java目录标记为Sources Root,并建立好相关包目录。如果使用的是Eclipse,则右键项目然后build path,config build path进行配置。建立如下图所示的基本架子;


③配置pom.xml,导入架包;
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>com.sshblog</groupId>
  <artifactId>SSHBlog</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SSHBlog Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <properties>

    <!--JDK源配置-->
    <maven.compiler.sourse>1.8</maven.compiler.sourse>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.resources.version>2.5</maven.resources.version>

    <!--项目源码配置-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <!--Spring版本号-->
    <spring.version>4.3.9.RELEASE</spring.version>

    <!--Hibernate版本号-->
    <hibernate.version>4.3.11.Final</hibernate.version>

    <!--MySQL驱动版本号-->
    <mysql-driver.version>5.1.43</mysql-driver.version>

    <!--freemarker版本号-->
    <freemarker.version>2.3.23</freemarker.version>

    <!--日志文件管理框架版本号-->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>

    <!--c3p0版本号-->
    <c3p0.version>0.9.1.2</c3p0.version>
  </properties>

  <dependencies>

    <!--以下是Junit测试依赖-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>RELEASE</version>
    </dependency>

    <!--以下是Spring依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--以下是druid依赖-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>0.2.9</version>
    </dependency>

    <!--以下是JSON依赖-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.1.18</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.8.5</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.5</version>
    </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>

    <!--以下是集合collections依赖-->
    <dependency>
      <groupId>commons-collections</groupId>
      <artifactId>commons-collections</artifactId>
      <version>3.2.1</version>
    </dependency>

    <!--以下是编码依赖-->
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>

    <!--以下是文件上传以及IO依赖-->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!--以下是封装了各种网络协议的客户端的依赖-->
    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>1.4.1</version>
    </dependency>

    <!--以下是读取文件资源依赖-->
    <dependency>
      <groupId>commons-configuration</groupId>
      <artifactId>commons-configuration</artifactId>
      <version>1.9</version>
    </dependency>

    <!--以下是Hibernate依赖-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>${hibernate.version}</version>
    </dependency>

    <!--以下是jstl依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!--以下是c3p0依赖-->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>${c3p0.version}</version>
    </dependency>

    <!--以下是日志文件依赖-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <!--以下是cglig-nodep代理的AOP以及AOP的依赖-->
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
      <version>2.1_3</version>
    </dependency>
    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>
    </dependency>

    <!--以下是Java参数注入配置-->
    <dependency>
      <groupId>org.javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.17.1-GA</version>
    </dependency>

    <!--以下是commons-lang3的工具类配置-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.4</version>
    </dependency>

    <!--以下是事务依赖-->
    <dependency>
      <groupId>javax.transaction</groupId>
      <artifactId>jta</artifactId>
      <version>1.1</version>
    </dependency>

    <!--以下是MySQL连接配置-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql-driver.version}</version>
    </dependency>

    <!--以下是读写xml依赖-->
    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
    </dependency>

    <!--以下是jsoup解释和操作DOM的依赖-->
    <dependency>
      <groupId>org.jsoup</groupId>
      <artifactId>jsoup</artifactId>
      <version>1.7.2</version>
    </dependency>

    <!--以下是语言识别工具依赖-->
    <dependency>
      <groupId>antlr</groupId>
      <artifactId>antlr</artifactId>
      <version>2.7.7</version>
    </dependency>

    <!--以下是servlet依赖-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>

    <!--以下是注解依赖-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.16.6</version>
    </dependency>

    <!--以下是freemarker依赖-->
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>${freemarker.version}</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>SSHBlog</finalName>

    <plugins>
      <!--jetty服务器插件-->
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.19</version>
        <configuration>
          <systemProperties>
            <systemProperty>
              <name>org.mortbay.jetty.Request.maxFormContentSize</name>
              <value>100000000</value>
            </systemProperty>
          </systemProperties>
          <scanIntervalSeconds>10</scanIntervalSeconds>
          <stopKey>foo</stopKey>
          <stopPort>9999</stopPort>
          <!-- 设置jetty启动该web站点的context -->
          <webAppConfig>
            <contextPath>/</contextPath>
          </webAppConfig>
          <!-- 每2秒的间隔扫描一次,实现热部署 -->
          <reload>automatic</reload>
          <scanIntervalSeconds>2</scanIntervalSeconds>
        </configuration>
        <executions>
          <execution>
            <id>start-jetty</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>run</goal>
            </goals>
            <configuration>
              <scanIntervalSeconds>0</scanIntervalSeconds>
              <daemon>true</daemon>
            </configuration>
          </execution>
          <execution>
            <id>stop-jetty</id>
            <phase>post-integration-test</phase>
            <goals>
              <goal>stop</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!--maven编译源管理插件配置-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <source>${maven.compiler.sourse}</source>
          <target>${maven.compiler.target}</target>
        </configuration>
      </plugin>

      <!--maven资源管理插件配置-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>${maven.resources.version}</version>
        <executions>
          <execution>
            <id>copy-resources</id>
            <phase>package</phase>
            <goals>
              <goal>copy-resources</goal>
            </goals>
            <configuration>
              <encoding>UTF-8</encoding>
              <outputDirectory>${project.build.directory}/lantooease/WEB-INF/
              </outputDirectory>
              <resources>
                <resource>
                  <directory>/src/main/resources</directory>
                  <includes>
                    <include>*.xml</include>
                    <include>*.properties</include>
                    <include>*.conf</include>
                  </includes>
                </resource>
              </resources>
            </configuration>
          </execution>
        </executions>
      </plugin>




    </plugins>

  </build>
</project>
④配置applicationContext.xml;
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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-3.0.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!--扫描驱动配置-->
    <context:annotation-config/>
    <!--自动扫描所有注解路径-->
    <context:component-scan base-package="com.sshblog"/>

    <!--属性配置-->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:config.properties</value>
            </list>
        </property>
    </bean>

    <!--消息源配置-->
    <bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource"
          p:basename="Message">
    </bean>

    <!--数据源配置-->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.url}"
          p:username="${jdbc.username}"
          p:password="${jdbc.password}">
    </bean>

    <!--SessionFactory配置-->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <!--以下是Hibernate的基础配置-->
                <!--是否自动更新表格-->
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <!--Hibernate方言配置-->
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <!--是否显示SQL语句-->
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <!--是否使用格式化SQL语句-->
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <!--在格式化的SQL语句的基础之上加强可读性-->
                <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
                <!--Hibernate缓存统计策略配置-->
                <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>

                <!--以下是Hibernate的c3p0配置-->
                <!-- 最大连接数 -->
                <prop key="hibernate.c3p0.max_size">${hibernate.c3p0.max_size}</prop>
                <!-- 最小连接数 -->
                <prop key="hibernate.c3p0.min_size">${hibernate.c3p0.min_size}</prop>
                <!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
                <prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop>
                <!-- 最大的PreparedStatement的数量 -->
                <prop key="hibernate.c3p0.max_statements">${hibernate.c3p0.max_statements}</prop>
                <!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒-->
                <prop key="hibernate.c3p0.idle_test_period">${hibernate.c3p0.idle_test_period}</prop>
                <!-- 当连接池里面的连接用完的时候,C3P0一下获取的新的连接数 -->
                <prop key="hibernate.c3p0.acquire_increment">${hibernate.c3p0.acquire_increment}</prop>
                <!-- 每次都验证连接是否可用 -->
                <prop key="hibernate.c3p0.validate">${hibernate.c3p0.validate}</prop>
            </props>
        </property>
        <!--扫描的实体类路径配置-->
        <property name="packagesToScan" value="com.sshblog.entity"/>
    </bean>

    <!--Hibernate事务配置-->
    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory">
    </bean>

    <!--freemarker配置-->
    <bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <!--端载入路径配置-->
        <property name="templateLoaderPath" value="/src/main/webapp/frontend/"/>
        <!--freemarker设置配置-->
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">UTF-8</prop>
                <prop key="number_format">0.##########</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="template_exception_handler">ignore</prop>
            </props>
        </property>
    </bean>

    <!--事务配置-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
其中,属性配置文件配置如下:
config.properties:
################### JDBC Configuration ##########################
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/SSHBlog?useUnicode=true&characterEncoding=utf8&useSSL=true&zeroDateTimeBehavior=convertToNull 
jdbc.username=root
jdbc.password=qwer1234

################### Hibernate Configuration ##########################
#Hibernate方言配置
hibernate.dialect=org.hibernate.dialect.MySQLDialect
#是否显示SQL语句
hibernate.show_sql=true
#是否自动更新表格
hibernate.hbm2ddl.auto=update
#Hibernate缓存统计策略配置
hibernate.generate_statistics=false
#是否使用格式化SQL语句
hibernate.format_sql=false
#在格式化的SQL语句的基础之上加强可读性
hibernate.use_sql_comments=false

################### 以下是Hibernate的c3p0配置 ##########################
#最大连接数
hibernate.c3p0.max_size=20
#最小连接数
hibernate.c3p0.min_size=5
#获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒
hibernate.c3p0.timeout=120
#最大的PreparedStatement的数量
hibernate.c3p0.max_statements=100
#每隔120秒检查连接池里的空闲连接 ,单位是秒
hibernate.c3p0.idle_test_period=120
#当连接池里面的连接用完的时候,C3P0一下获取的新的连接数
hibernate.c3p0.acquire_increment=2
每次都验证连接是否可用
hibernate.c3p0.validate=true
⑤配置spring-mvc.xml;
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:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       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-3.0.xsd">

    <!--扫描注解配置-->
    <context:annotation-config/>
    <!--扫描注解了@Controller配置的类-->
    <context:component-scan base-package="com.sshblog.controller"/>

    <!--JSON消息转换配置-->
    <bean id="jsonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonHttpMessageConverter"/>
            </list>
        </property>
        <property name="webBindingInitializer">
            <bean class="com.sshblog.action.converter.DateConverter"/>
        </property>
    </bean>

    <!--文件上传配置-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
          p:defaultEncoding="UTF-8">
        <!--文件最大上传大小配置-->
        <property name="maxUploadSize">
            <value>51200000</value>
        </property>
    </bean>
    <bean id="exceptionResolver"
          class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
            </props>
        </property>
    </bean>

    <!--设置使用了freemarker的页面路径的配置-->
    <bean id="freemarkerConfiguration"
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    </bean>
    <!--html视图解析器 必须先配置freemarkerConfig,注意html是没有prefix前缀属性的-->
    <bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath">
            <value>/frontend/</value>
        </property>
    </bean>
    <bean id="htmlviewResolver"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="suffix" value=".html"/>
        <property name="order" value="0"></property>
        <property name="contentType" value="text/html;charset=UTF-8"></property>
    </bean>


</beans>
⑥配置web.xml;
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <display-name>sshblog</display-name>

  <!--Spring ApplicationContext配置文件路径,可使用通配符,多个路径用","号分隔 此参数用于后面的Spring Context Loader-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext*.xml</param-value>
  </context-param>

  <!--过滤器源码配置-->
  <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>
  </filter>

  <!--以下是log4j的日志配置-->
  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <context-param>
    <param-name>log4jRefreshInteval</param-name>
    <param-value>600000</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>

  <!--过滤.html请求-->
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>*.html</url-pattern>
  </filter-mapping>
  <!--过滤.json-->
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>*.json</url-pattern>
  </filter-mapping>

  <!--以下是与Hibernate的延迟有关的配置-->
  <filter>
    <filter-name>openSessionInView</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>openSessionInView</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--Spring ApplicationContext 载入监听-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--Spring 刷新Introspector防止内存泄漏-->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>

  <!--Spring MVC 配置以便拦截-->
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.json</url-pattern>
  </servlet-mapping>

  <!--session超时定义,单位为分钟-->
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

  <!--欢迎页面定义-->
  <welcome-file-list>
    <welcome-file>/index.html</welcome-file>
    <welcome-file>/index.jsp</welcome-file>
  </welcome-file-list>


  <error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/frontend/common/500.html</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/frontend/common/500.html</location>
  </error-page>
  <error-page>
    <error-code>404</error-code>
    <location>/frontend/common/404.html</location>
  </error-page>

</web-app>
其中,日志属性文件配置如下:
log4j.properties:
log4j.rootCategory=info,stdout,R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) -%m%n
#日志文件存储路径配置
log4j.appender.R.file=./logFile.log
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c -%m%n

3、案例测试整合

3.1、Entity层

Entity层的实体类代码可以自动生成,生成方法参见: Hibernate实体类以及配置文件自动生成的方法
Contacts.java:
package com.sshblog.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "contacts")
@JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler","operations","roles","menus"})
public class Contacts {
    private int id;
    private String name;
    private String address;
    private String gender;
    private Date dob;
    private String email;
    private Long mobile;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "address")
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Basic
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Basic
    @Column(name = "dob")
    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    @Basic
    @Column(name = "email")
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Basic
    @Column(name = "mobile")
    public Long getMobile() {
        return mobile;
    }

    public void setMobile(Long mobile) {
        this.mobile = mobile;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Contacts contacts = (Contacts) o;

        if (id != contacts.id) return false;
        if (name != null ? !name.equals(contacts.name) : contacts.name != null) return false;
        if (address != null ? !address.equals(contacts.address) : contacts.address != null) return false;
        if (gender != null ? !gender.equals(contacts.gender) : contacts.gender != null) return false;
        if (dob != null ? !dob.equals(contacts.dob) : contacts.dob != null) return false;
        if (email != null ? !email.equals(contacts.email) : contacts.email != null) return false;
        if (mobile != null ? !mobile.equals(contacts.mobile) : contacts.mobile != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (address != null ? address.hashCode() : 0);
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (dob != null ? dob.hashCode() : 0);
        result = 31 * result + (email != null ? email.hashCode() : 0);
        result = 31 * result + (mobile != null ? mobile.hashCode() : 0);
        return result;
    }
}
Contacts.hbm.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.sshblog.entity.Contacts" table="contacts" schema="SSHBlog">
        <id name="id" column="id"/>
        <property name="name" column="name"/>
        <property name="address" column="address"/>
        <property name="gender" column="gender"/>
        <property name="dob" column="dob"/>
        <property name="email" column="email"/>
        <property name="mobile" column="mobile"/>
    </class>
</hibernate-mapping>

3.2、DAO层

ContactsDAOI.java:
package com.sshblog.dao;

import com.sshblog.entity.Contacts;

import java.util.List;

public interface ContactsDAOI {
    public List<Contacts> findAllContacts();

    public void saveContact(Contacts contacts);

    public Contacts findById(int id);

    public void deleteContact(int id);

    public void updateContact(Contacts contacts);

    public List<Contacts> findByContactName(String name);
}
ContactsImpl.java:
package com.sshblog.dao.impl;

import com.sshblog.dao.ContactsDAOI;
import com.sshblog.entity.Contacts;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

@Repository
@Transactional
public class ContactsDAOImpl implements ContactsDAOI {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<Contacts> findAllContacts() {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Contacts.class);
        return criteria.list();
    }

    @Override
    public void saveContact(Contacts contacts) {
        sessionFactory.getCurrentSession().save(contacts);
    }

    @Override
    public Contacts findById(int id) {
        Contacts contacts = (Contacts) sessionFactory.getCurrentSession().get(Contacts.class, id);
        return contacts;
    }

    @Override
    public void deleteContact(int id) {
        Contacts contacts = findById(id);
        sessionFactory.getCurrentSession().delete(contacts);
    }

    @Override
    public void updateContact(Contacts contacts) {
        sessionFactory.getCurrentSession().update(contacts);
    }

    @Override
    public List<Contacts> findByContactName(String name) {
        String hql = "from Contacts c where c.name like '%" + name + "%'";
        return sessionFactory.getCurrentSession().createQuery(hql).list();
    }
}

3.3、Service层

ContactsServiceI.java:
package com.sshblog.service;

import com.sshblog.entity.Contacts;

import java.util.List;

public interface ContactsServiceI {

    public List<Contacts> findAllUsers();

    public void saveContact(Contacts contacts);

    public void deleteContact(int id);

    public Contacts findById(int id);

    public void updateContact(Contacts contacts);

    public List<Contacts> findByUserName(String name);

}
ContactsServiceImpl.java:
package com.sshblog.service.impl;

import com.sshblog.dao.ContactsDAOI;
import com.sshblog.entity.Contacts;
import com.sshblog.service.ContactsServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service("contactsService")
@Transactional
public class ContactsServiceImpl implements ContactsServiceI {
    @Autowired
    private ContactsDAOI contactsDAOI;

    public void setContactsDAOI(ContactsDAOI contactsDAOI) {
        this.contactsDAOI = contactsDAOI;
    }

    @Override
    public List<Contacts> findAllUsers() {
        return this.contactsDAOI.findAllContacts();
    }

    @Override
    public void saveContact(Contacts contacts) {
        this.contactsDAOI.saveContact(contacts);
    }

    @Override
    public void deleteContact(int id) {
        this.contactsDAOI.deleteContact(id);
    }

    @Override
    public Contacts findById(int id) {
        return this.contactsDAOI.findById(id);
    }

    @Override
    public void updateContact(Contacts contacts) {
        this.contactsDAOI.updateContact(contacts);
    }

    @Override
    public List<Contacts> findByUserName(String name) {
        return this.contactsDAOI.findByContactName(name);
    }
}

3.4、Controller层

SSHBlogController.java:
package com.sshblog.controller;

import com.sshblog.entity.Contacts;
import com.sshblog.service.ContactsServiceI;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/")
public class SSHBlogController {
    @Autowired
    private ContactsServiceI contactsServiceI;

    public void setContactsServiceI(ContactsServiceI contactsServiceI) {
        this.contactsServiceI = contactsServiceI;
    }

    @RequestMapping("index")
    public ModelAndView indexPage(){
        ModelAndView mav = new ModelAndView("index");
        List<Contacts> contacts = this.contactsServiceI.findAllUsers();
        mav.addObject("contacts",contacts);
        return mav;
    }

    @RequestMapping(value = "save", method = RequestMethod.GET)
    public ModelAndView newContactPage(){
        ModelAndView mav = new ModelAndView("newContact");
        return mav;
    }

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String newContact(@RequestParam("dateOfb")String dob, Contacts contacts) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(dob);
        contacts.setDob(date);
        this.contactsServiceI.saveContact(contacts);
        return "redirect:index.html";
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String deleteContact(int id) {
        this.contactsServiceI.deleteContact(id);
        return "redirect:index.html";
    }

    @RequestMapping(value = "update", method = RequestMethod.GET)
    public ModelAndView editContactPage(int id){
        ModelAndView mav = new ModelAndView("editContact");
        Contacts contacts = this.contactsServiceI.findById(id);
        mav.addObject("editContact",contacts);
        return mav;
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String editContact(@RequestParam("dateOfb")Date date, Contacts contacts){
        contacts.setDob(date);
        this.contactsServiceI.updateContact(contacts);
        return "redirect:index.html";
    }

    @RequestMapping(value = "search", method = RequestMethod.POST)
    public ModelAndView searchByContactName(String name){
        ModelAndView mav = new ModelAndView("index");
        List<Contacts> contacts = this.contactsServiceI.findByUserName(name);
        mav.addObject("contacts",contacts);
        return mav;
    }

    @RequestMapping(value = "findAllUsers", method = RequestMethod.GET)
    @ResponseBody
    public List<Contacts> findAllUsers(){
        return this.contactsServiceI.findAllUsers();
    }
}

3.5、案例完成后的项目展开

如下图所示:

4、运行测试

如果是使用的如上所示的jetty服务器,则以clean jetty:run命令运行项目;如果使用的是导入pom.xml中的tomcat服务器,则使用tomcat*:run来运行项目,其中*代表的是tomcat服务器的版本,tomcat6则*为6,tomcat7则*为7;如果是本地的tomcat服务器的话则在本地配置服务器运行项目即可。
运行后在浏览器上进行测试,如下图所示,则代表整合配置成功。

测试能够访问到JSON,配置成功。

5、源码下载

本篇博客提供源码下载地址:

  • 1
    点赞
  • 0
    评论
  • 2
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

参与评论 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

sam199510

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值