勿谓今日不学而有来日,勿谓今年不学而有来年。
日月逝矣,岁不我延。

SSM框架的CURD案例一 环境搭建

SSM介绍

SSM是由Spring,SpringMVC,Mybatis组合成的一个框架,也是现在最流行的一个框架.主要用于web项目中.使用SSM框架的好处是在于其易复用和简化开发,掌握了每个框架的核心思想就掌握了SSM的开发。

  • Spring依赖注入DI来管理各层的组件,使用面向切面编程AOP管理事物、日志、权限等。
  • SpringMVC代表了Model(模型)View(视图)Controller(控制)接收外部请求,进行分发和处理.
  • Mybatis是基于jdbc的框架,主要用来操作数据库,并且将业务实体和数据表联系起来

工作流程简图:

创建工程

1、创建Maven工程选择webapp模板

2、完善目录结构

3、配置pom.xml

示例包括常用工具的jar

<dependencies>
  <!--SpringMVC-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.7.RELEASE</version>
  </dependency>
  <!--SpringJDBC事务管理包-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.7.RELEASE</version>
  </dependency>
  <!--Spring的Aop包-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>4.3.7.RELEASE</version>
  </dependency>
  <!--SpringTest-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.7.RELEASE</version>
  </dependency>
  <!--Mybatis-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.4</version>
  </dependency>
  <!--Mybatis-Spring整合包-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
  </dependency>
  <!--数据库连接池-->
  <dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
  </dependency>
  <!--Mysql驱动-->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.41</version>
  </dependency>
  <!--jstl-->
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
  <!--servlet-api-->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>3.0</version>
    <scope>provided</scope>
  </dependency>
  <!--pageHelper-->
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.1</version>
  </dependency>
  <!--log4j-->
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
  </dependency>
  <!--junit-->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>
</dependencies>

4、编写属性文件 jdbc.properties与log4j.properties

#jdbc.properties
#-------公共链接信息----------
jdbc.driverClass=com.mysql.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/ssmcurd?useUnicode=true&characterEncoding=utf8
#用户名
jdbc.user=root
#密码
jdbc.password=root
#-------MySql-------------------
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
#-------MybatisGenerator-------
#entity 包名和 java目录
modelPackage=cn.llanc.ssmcurd.entity
modelProject=./src/main/java
#sqlmap包名 和resources目录
sqlPackage=mapper
sqlProject=./src/main/resources
#dao包与java目录
daoPackage=cn.llanc.ssmcurd.dao
daoProject=./src/main/java
#log4j.properties
# Configure logging for testing: optionally with log file
log4j.rootLogger=WARN, stdout
# log4j.rootLogger=WARN, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

5、编写web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>SSM_CURD</display-name>
<!--启动Spring容器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!--字符编码过滤器 所有过滤器之前-->
  <filter>
    <filter-name>CharacterEncodingFilter</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>forceRequestEncoding</param-name>
      <param-value>ture</param-value>
    </init-param>
    <init-param>
      <param-name>forceResponseEncoding</param-name>
      <param-value>ture</param-value>
    </init-param>
  </filter>
  <!--Rest风格URI-->
  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--Spring核心监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--SptingMVC前端控制器-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:dispatcherServlet-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--404错误展示页面,可自行配置-->
  <!--<error-page>-->
  <!--<error-code>404</error-code>-->
  <!--<location>/WEB-INF/views/404.jsp</location>-->
  <!--</error-page>-->
  <!--设置session失效时间为30分钟 -->
  <session-config>
    <session-timeout>600</session-timeout>
  </session-config>
</web-app>

6、编写SSM的配置文件

appliactionContext.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--Spring-->
    <!--包扫描 排除controller-->
   <context:component-scan base-package="cn.llanc.ssmcurd">
       <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
   </context:component-scan>
    <!--数据源-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
        <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
        <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
        <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
        <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
    </bean>
    <!--整合Mybatis-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="pooledDataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--<property name="plugins">-->
            <!--<array>-->
                <!--<bean class="com.github.pagehelper.PageInterceptor" />-->
            <!--</array>-->
        <!--</property>-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>
    <!--配置扫描器 mybatis的接口实现加入springIOC-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.llanc.ssmcurd.dao"/>
    </bean>
    <!--注入批量执行的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
        <constructor-arg name="executorType" value="BATCH"/>
    </bean>
    <!--事务控制-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="pooledDataSource"/>
    </bean>
    <!--&lt;!&ndash;开启注解事务或配置事务(主要)&ndash;&gt;-->
    <aop:config proxy-target-class="true">
        <!--切入点-->
        <aop:pointcut id="transactionPoint" expression="execution(* cn.llanc.ssmcurd.service..*(..))"/>
        <!--配置增强-->
        <aop:advisor advice-ref="transactionAdvice" pointcut-ref="transactionPoint"/>
    </aop:config>
    <!--&lt;!&ndash;事务增强&ndash;&gt;-->
    <tx:advice id="transactionAdvice">
        <tx:attributes>
            <tx:method name="*"/>
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
</beans>

dispatcherServlet-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: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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!--SpringMVC-->
    <!--包扫描-->
    <context:component-scan base-package="cn.llanc.ssmcurd.controller"/>
    <!--视图解析器-->
    <bean 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>
    <!-- 静态资源默认TomCat中servlet配置 -->
    <mvc:default-servlet-handler/>
    <!-- 开启SpringMVC注解模式 JSR303校验 快捷Ajax... -->
    <mvc:annotation-driven/>
</beans>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--驼峰命名-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="ture"/>
    </settings>
    <!--别名扫描-->
    <typeAliases>
        <package name="cn.llanc.ssmcurd.entity"/>
    </typeAliases>
    <!--pagehelper-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
        </plugin>
    </plugins>
    
</configuration>

7、配置Mybatis逆向工程插件MybatisGenerator

generatorConfig.xm

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!--属性文件-->
    <properties resource="jdbc.properties"/>
    <!--数据库驱动-->
    <classPathEntry  location="D:\maven\repository\mysql\mysql-connector-java\5.1.41\mysql-connector-java-5.1.41.jar"/>
    <!--配置信息-->
    <context id="mysql" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否生成注释代时间戳 -->
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释-->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库连接-->
        <jdbcConnection
                driverClass="${jdbc.driverClass}"
                connectionURL="${jdbc.url}"
                userId="${jdbc.user}"
                password="${jdbc.password}"/>
        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!--java类生成地址-->
        <javaModelGenerator targetPackage="${modelPackage}" targetProject="${modelProject}"/>
        <!--mapper映射文件生成-->
        <sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
        <!--doa接口的生成-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="${daoPackage}" targetProject="${daoProject}"/>
        <!--需要生成的表-->
        <table tableName="tbl_emp" domainObjectName="Employee"/>
        <table tableName="tbl_dept" domainObjectName="Department"/>

    </context>

</generatorConfiguration>

配置启动命令

8、配置TOMCAT

环境搭建到此完成。

源码:https://github.com/llanc/SSM_CURD

赞(1)
未经允许不得转载:喋喋不休 » SSM框架的CURD案例一

评论 抢沙发

评论前必须登录!

 

精品网站

有券无忧电脑壁纸精选