SSM框架整合--MAVEN依赖

spring方面(包含了springmvc):

  1. spring-webmvc:spring与mvc的整合依赖,主要包括spring的核心包和springmvc需要的包
  2. spring-jdbc:spring-JDBC
  3. spring-test:spring整合Junit实现测试
  4. spring-aspects:spring面向切面编程

mybatis方面:

  1. mybatis:mybatis核心jar包
  2. mybatis-spring:mybatis整合spring的jar包,适配器
  3. mybatis-generator-core:mybatis逆向工程核心jar包
  4. pagehelper:mybatis提供的分页插件

数据库连接方面:

  1. c3p0:数据库连接池
  2. mysql-connector-java:数据库连接驱动

其他:

  1. jackson-databind:springmvc进行数据绑定,返回json字符串

  2. jstl-api:jsp标准标签库(需要与taglibs一块用)

    taglibs-standard-impl:jstl的实现

  3. javax.servlet-api:MVC三层代码测试使用(项目启动时会使用tomcat里的)

  4. junit:java单元测试(@Test)

  5. hibernate-validator:支持JSR303数据校验(Bean Validation 1.0)

SSM框架整合--web.xml配置

(web.xml是网页启动时即加载的配置信息,ssm工程最基本的需要加载运行spring容器、加载springmvc的前端控制器,使组件都开始工作)

  1. 配置启动Spring的容器:

    <!-- 1.  启动Spring的容器 -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
    <!-- applicationContext.xml是Spring的配置文件 -->
    </context-param>
    <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener
    </listener-class>
    </listener>
  2. 配置SpringMVC的前端控制器:

    <!-- 2. SpringMVC的前端控制器,拦截所有请求 -->
    <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 加载springmvc配置 -->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 配置文件的地址
    如果不配置contextConfigLocation,
    默认查找的配置文件名称classpath下的:servlet名称+"-servlet.xml"即:springmvc-servlet.xml -->
    <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    </servlet> <servlet-mapping>
    <!-- url-pattern 拦截 / 而不是 /*
    原因:如果使用 /* ,那么请求时可以通过DispatcherServlet转发到相应的Action或者Controller中,
    但是返回的内容,如返回一个jsp还会被再次拦截,这样导致404错误 -->
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
    </servlet-mapping>
  3. 配置log4j:(可选)

    <!-- 加载log4j配置 -->
    <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:config/loog4j/log4j.properties</param-value>
    </context-param> <!-- 设置每60秒扫描一次log4j的配置文件 -->
    <context-param>
    <param-name>log4jRefreshIntervel</param-name>
    <param-value>60000</param-value>
    </context-param> <!-- 加载log4j的监听器 -->
    <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
  4. 配置过滤器:(可选)

    <!-- 3. 字符编码过滤器, 必须放在所有过滤器之前 -->
    <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>true</param-value>
    </init-param>
    <init-param>
    <param-name>forceResponseEncoding</param-name>
    <param-value>true</param-value>
    </init-param>
    </filter>
    <!-- 4.使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求 -->
    <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 这个过滤器用于将POST请求转化为PUT或DELETE请求 -->
    <filter>
    <filter-name>HttpPutFormContentFilter</filter-name>
    <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
    </filter>
    <filter-mapping>
    <filter-name>HttpPutFormContentFilter</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
  5. 配置session:(可选)

    <!-- 设置session的过期时间:5分钟 -->
    <session-config>
    <session-timeout>65</session-timeout>
    </session-config>

SSM框架整合--SpringMVC配置文件(springmvc.xml)

  1. 配置扫描器:

    <context:component-scan base-package="cn.zzuli" use-default-filters="false">
    <!-- 只扫描注解控制器 -->
    <context:include-filter type="annotation"
    expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
  2. 配置视图解析器:

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" /> <!-- 前缀 -->
    <property name="suffix" value=".jsp" /> <!-- 后缀 -->
    </bean>
  3. 配置静态资源映射:

    <!--静态资源映射
    通过mvc:resources 设置静态资源映射,这样servlet就会处理这些静态资源,而不通过控制器 -->
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/js/**" location="/js/" />
    <mvc:resources mapping="/img/**" location="/img/" />
    <mvc:resources mapping="" location="" />

  4. 其他配置:

    <!-- 两个标准配置 -->
    <!-- 将springmvc不能处理的请求交给tomcat -->
    <mvc:default-servlet-handler/>
    <!-- 能支持springmvc更高级的一些功能,JSR303校验,快捷的ajax...映射动态请求 -->
    <mvc:annotation-driven/> <!-- 开启文件上传支持 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"

SSM框架整合--Spring配置文件(applicationContext.xml)

其核心点在配置(数据源、与mybatis的整合,事务控制)

  1. 扫描bean:

    <context:component-scan base-package="cn.zzuli">
    <!-- 排除掉controller注解的组件,因为他们不需要注入 -->
    <context:exclude-filter type="annotation"
    expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
  2. 配置数据源:

    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}" />
    <property name="jdbcUrl" value="${jdbc.url}" />
    <property name="user" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    </bean>
  3. 配置与mybatis的整合:

    <!-- 配置SqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!-- 指定mybatis全局配置文件的位置 -->
    <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
    <!-- 指定mybatis,mapper文件的位置 -->
    <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean> <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
    <!-- MapperScannerConfigurer:mapper的扫描器,将包下边的mapper接口自动创建代理对象,自动创建到spring容器中,bean的id是mapper的类名(首字母小写)
    这个类会在扫描时自动给mapper创建映射器,使得我们不用在dao层写注解即可被实例化为bean-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!--扫描所有dao接口的实现,加入到ioc容器中 -->
    <property name="basePackage" value="cn.zzuli.crud.dao"></property>
    </bean> <!-- 配置一个可以执行批量的sqlSession,sqlSession在对数据库进行批量操作时很高效 -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
    <constructor-arg name="executorType" value="BATCH"></constructor-arg>
    </bean>
  4. 配置事务:

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--控制住数据源 -->
    <property name="dataSource" ref="dataSource"></property>
    </bean> <!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式) -->
    <aop:config>
    <!-- 切入点表达式 -->
    <aop:pointcut expression="execution(* cn.zzuli.crud.service..*(..))" id="txPoint"/>
    <!-- 配置事务增强 -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config> <!-- 配置事务增强,事务如何切入 (通知) -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    <tx:method name="save*" propagation="REQUIRED"/>
    <tx:method name="insert*" propagation="REQUIRED"/>
    <tx:method name="update*" propagation="REQUIRED"/>
    <tx:method name="delete*" propagation="REQUIRED"/>
    <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
    <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
    <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
    </tx:attributes>
    </tx:advice>

SSM框架整合--MyBatis配置文件(SqlMapConfig.xml)

mybatis配置已在spring的配置文件中配置过了,所以可以不要mybatis的配置文件。这里使用其引用主要是配置一些设置

  1. 设置启用驼峰命名规则和别名:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "https://www.mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration> <settings>
    <!-- 设置启用驼峰命名法 -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
    <setting name="" value="" />
    </settings> <!-- 设置别名:将包内的bean的非大写的非限定类名注册为别名 -->
    <typeAliases>
    <package name="cn.zzuli.crud.bean"/>
    </typeAliases> <!-- 其他 --> </configuration>
  2. 添加mybatis提供的分页插件:

    <plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
    <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
    <property name="param1" value="value1"/>
    </plugin>
    </plugins>
  3. 更多mybatis配置文件属性设置请参考:

SSM框架整合--MyBatis逆向工程

  • 步骤1. xml文件
    <?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> <context id="DB2Tables" targetRuntime="MyBatis3"> <!-- 不生成注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator> <!-- 配置数据库连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm_crud"
userId="root"
password="123456">
</jdbcConnection> <javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver> <!-- 指定javaBean生成的位置 -->
<javaModelGenerator targetPackage="cn.zzuli.crud.bean" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator> <!-- 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator> <!-- 指定dao接口生成的位置, mapper接口 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.zzuli.crud.dao" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator> <!-- 指定每个表的生成策略 -->
<table tableName="table1" domainObjectName="Employee"></table>
<table tableName="table2" domainObjectName="Department"></table> </context>
</generatorConfiguration>
  • 步骤2:运行java代码

    public static void main(String[] args) throws Exception {
    List<String> warnings = new ArrayList<String>();
    boolean overwrite = true;
    File configFile = new File("mybatis_generator.xml"); // 逆向工程配置文件
    ConfigurationParser cp = new ConfigurationParser(warnings);
    Configuration config = cp.parseConfiguration(configFile);
    DefaultShellCallback callback = new DefaultShellCallback(overwrite);
    MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
    myBatisGenerator.generate(null);
    }

SSM框架整合--Spring整合JUnit

  • 步骤一:导入spring-test依赖(去掉scope)

    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.8.RELEASE</version>
    </dependency>
  • 步骤二:使用@ContextConfiguration指定Spring配置文件的位置,使用@RunWith指定运行环境

  • 步骤三:直接注入要使用的组件

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations= {"classpath:applicationContext.xml"})
    public class MapperTest { @Autowired
    DepartmentMapper departmentMapper; @Autowired
    EmployeeMapper employeeMapper; @Autowired
    SqlSession sqlSession; @Test
    public void testCRUD(){ }

    }

SSM框架整合--PageHelper的使用

  • 步骤一:引入maven依赖或jar包:

    <!-- 引入pageHelper分页插件 -->
    <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.10</version>
    </dependency>
  • 步骤二:在MyBatis配置文件(SqlMapConfig.xml)中引入PageHelper插件:

    <plugins>
    <!-- com.github.pagehelper为PageHelper类所在包名 -->
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
    <!-- 使用下面的方式配置参数,详细参数参看PageHelper官网技术手册 -->
    <property name="param1" value="value1"/>
    </plugin>
    </plugins>
  • 步骤三:在代码中引入使用即可,具体参看官网技术手册 (这里贴出两种常用方式):

    //第二种,Mapper接口方式的调用,推荐这种使用方式。
    PageHelper.startPage(1, 10);
    List<Country> list = countryMapper.selectIf(1); //第三种,Mapper接口方式的调用,推荐这种使用方式。
    PageHelper.offsetPage(1, 10);
    List<Country> list = countryMapper.selectIf(1);

SSM框架整合--MVC三层代码测试

(web层测试主要是模拟http请求,向服务器发出请求,测试从发出请求到服务器返回数据的整个过程)

  • 步骤一:引入发出Http请求需要的maven依赖或jar包

    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
    </dependency>
  • 步骤二:代码测试整个过程(以查询员工分页信息为例)

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @ContextConfiguration(locations= {"classpath:applicationContext.xml","classpath:springmvc.xml"})
    public class MvcTest { //传入SpringMVC的IOC容器
    @Autowired
    WebApplicationContext context; //虚拟mvc请求,获取到处理结果
    MockMvc mockMvc; @Before
    public void initMockMvc() {
    mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    } @Test
    public void testPage() throws Exception {
    MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pageNo", "1")).andReturn(); //请求成功以后,请求域中会有pageInfo;可以取出pageInfo进行验证
    MockHttpServletRequest request = result.getRequest();
    PageInfo pageInfo = (PageInfo)request.getAttribute("pageInfo"); System.out.println("当前页码:"+pageInfo.getPageNum());
    System.out.println("总页码:"+pageInfo.getPages());
    System.out.println("总记录数:"+pageInfo.getTotal());
    System.out.println("在页面需要连续显示的页码:");
    int[] nums = pageInfo.getNavigatepageNums();
    for(int i: nums) {
    System.out.println(" " + i);
    } //获取员工数据
    List<Employee> list = pageInfo.getList();
    for(Employee employee : list) {
    System.out.println("ID:" + employee.getEmpId() + "==>Name:" +employee.getEmpName());
    } } }

最新文章

  1. AMD and CMD are dead之Why Namespace?
  2. HttpClientUtil工具类,待更新
  3. Wampserver2.5配置虚拟主机出现403 Forbidden的处理方案
  4. Tire树入门专题
  5. 自制javascript游戏-点燃火绳
  6. Swift常量和变量
  7. python2.7_2.2_在套接字服务器上使用ForkingMixIn
  8. CSS Filter
  9. 【HTTP权威指南】第二章-URL与资源
  10. Vue深度学习(4)-方法与事件处理器
  11. java多线程(五)-访问共享资源以及加锁机制(synchronized,lock,voliate)
  12. [洛谷P4234] 最小差值生成树
  13. linux device drivers ch02
  14. 二叉树遍历之三(Moriis traversal)
  15. MySQL系列详解八:MySQL多线程复制演示-技术流ken
  16. oracle数据库导出与导入
  17. 简述JavaScript作用域与作用域链
  18. Orchard模块开发全接触2:新建 ProductPart
  19. Linux内核配置.config文件
  20. sqljdbc 无法连接到主机

热门文章

  1. Python & PyQt学习随笔:PyQt主程序的基本框架
  2. 攻防世界 web进阶区 ics-06
  3. 最简单的Go Dockerfile编写姿势,没有之一!
  4. Windows的API功能查询
  5. 查看java程序中对象占用空间大小
  6. nginx优化-转载
  7. .net5+nacos+ocelot 配置中心和服务发现实现
  8. Hexo博客框架10分钟搭建个人博客
  9. Mycat安全配置
  10. jmeter__问题记录,中文乱码问题(json参数化)