SSM框架整合搭建(七)

(一)SSM整合环境搭建

注:SSM整合环境搭建源码下载
项目结构及其所需Jar包:

这里写图片描述这里写图片描述

(二)SSM框架整合步骤如下:

创建数据表

CREATE TABLE `t_customer` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `jobs` varchar(50) DEFAULT NULL,
  `phone` varchar(16) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
INSERT INTO `t_customer` VALUES ('1', '张三', '学生', '183999999');
INSERT INTO `t_customer` VALUES ('2', '李四', '程序员', '183666666');
INSERT INTO `t_customer` VALUES ('3', '王五', '程序员', '183121212');
INSERT INTO `t_customer` VALUES ('6', '赵六', '演员', '183933333');
1.编写配置文件

01.配置db.properties文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5

02.配置applicationContext.xml文件

  1. 配置db.properties
  2. 配置数据源
  3. 配置事务管理器,依赖于数据源
  4. 开启事务注解
  5. 配置MyBatis工厂SqlSessionFactory
  6. 指定核MyBatis心配置文件位置
  7. 配置mapper扫描器(基于MapperScannerConfigurer的整合)
  8. 基于Java注解配置包扫描
<?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:tx="http://www.springframework.org/schema/tx" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    <!-- 读取db.properties -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置数据源 -->
    <bean id="dataSource" 
                           class="org.apache.commons.dbcp2.BasicDataSource">
        <!--数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <!--连接数据库的url -->
        <property name="url" value="${jdbc.url}" />
        <!--连接数据库的用户名 -->
        <property name="username" value="${jdbc.username}" />
        <!--连接数据库的密码 -->
        <property name="password" value="${jdbc.password}" />
        <!--最大连接数 -->
        <property name="maxTotal" value="${jdbc.maxTotal}" />
        <!--最大空闲连接  -->
        <property name="maxIdle" value="${jdbc.maxIdle}" />
        <!--初始化连接数  -->
        <property name="initialSize" value="${jdbc.initialSize}" />
    </bean>
     <!-- 事务管理器,依赖于数据源 -->
    <bean id="transactionManager" class=
     "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean> 
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 配置MyBatis工厂SqlSessionFactory -->
    <bean id="sqlSessionFactory" 
                           class="org.mybatis.spring.SqlSessionFactoryBean">
         <!--注入数据源 -->
         <property name="dataSource" ref="dataSource" />
         <!--指定核MyBatis心配置文件位置 -->
  <property name="configLocation" value="classpath:mybatis-config.xml" />
    </bean>
    <!-- 配置mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wang.dao"/>
    </bean>
    <!-- 扫描Service --> 
    <context:component-scan base-package="com.wang.service" />
</beans>

03.配置mybatis-config.xml文件

  1. 只需配置别名即可!
<?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>
    <!-- 别名定义 -->
    <typeAliases>
        <package name="com.wang.po" />
    </typeAliases>
</configuration>

04.配置springmvc-config.xml文件

  1. 使用注解配置包扫描器
  2. 配置加载注解驱动
  3. 配置视图解析器
<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"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    <!-- 配置包扫描器,扫描@Controller注解的类 -->
    <context:component-scan base-package="com.wang.controller" />
    <!-- 加载注解驱动 -->
    <mvc:annotation-driven />
    <!-- 配置视图解析器 -->
    <bean class=
    "org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

05.配置log4j.properties文件

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

06.配置web.xml文件

  1. 引入Spring配置文件。比如:applicationContext.xml
  2. 配置字符编码过滤器解决乱码问题
  3. 映入Mybatis核心配置文件。比如:springmvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
id="WebApp_ID" version="3.1">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>
             org.springframework.web.context.ContextLoaderListener
        </listener-class>
  </listener>
  <filter>
    <filter-name>encoding</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>
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>*.action</url-pattern>
  </filter-mapping>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
             org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
2.在com.wang.po创建Customer持久化类
package com.wang.po;
public class Customer {
    private int id;
    private String username;
    private String jobs;
    private String phone;
    ---省略setter和getter方法---
    }
3.在com.wang.dao包下创建CustomerDao接口和CustomerDao.xml

01.CustomerDao.java(基于MapperScannerConfigurer的整合)

  1. CustomerDao接口+CustomerDao.xml=JDBC中操作数据库的CustomerDao.Java
  2. CustomerDao接口必须与CustomerDao.xml在一个包下
  3. 接口名必须和映射文件名称一致。
  4. CustomerDao接口方法查询参数必须与映射文件中的parameterType定义的数据类型一致。
  5. CustomerDao接口方法返回值必须与映射文件中sql返回值一致。
package com.wang.dao;
import com.wang.po.Customer;

/**
 * Customer接口文件
 */
public interface CustomerDao {
    /**
     * 根据id查询客户信息
     */
    public Customer findCustomerById(Integer id);
}

02.CustomerDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
   <mapper namespace="com.wang.dao.CustomerDao">
    <select id="findCustomerById" parameterType="Integer"
         resultType="customer">
         select*from t_customer where id=#{id} 
    </select>
   </mapper> 
4.在com.wang.service包下创建CustomerService.java接口和CustomerServiceImp.java

CustomerService.java接口

package com.wang.service;
import com.wang.po.Customer;
public interface CustomerService {

     public Customer findCustomerById(Integer id);

}

01. CustomerServiceImp.java

package com.wang.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wang.dao.CustomerDao;
import com.wang.po.Customer;
@Service
//@Transactional实现添加、删除、修改时才使用@Transactional
public class CustomerServiceImp implements CustomerService {

    @Autowired
    private CustomerDao customerDao;
    @Override
    public Customer findCustomerById(Integer id) {
       return this.customerDao.findCustomerById(id);
    }
}
5.在com.wang.controller包下创建CustomerController.java

02.CustomerController.java

package com.wang.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wang.po.Customer;
import com.wang.service.CustomerService;

@Controller
public class CustomerController {
    @Autowired
    private CustomerService customerservice;
    @RequestMapping("/findCustomerById")
    //@RequestMapping("/findCustomer")此路径无法请求
    public String findCustomerById(Integer id, Model model) {
        Customer customer = customerservice.findCustomerById(id);
        model.addAttribute("customer", customer);
        return "customer";

    }
}
6.在jsp文件夹下创建customer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>客户信息</title>
</head>
<body>
    <table border=1 >
        <tr>
            <th style="width:100px;">编号</th>
            <th style="width:100px;">名称</th>
            <th style="width:100px;">职业</th>
            <th style="width:100px;">电话</th>
        </tr>
        <tr>
            <td >${customer.id}</td>
            <td>${customer.username}</td>
            <td>${customer.jobs}</td>
            <td>${customer.phone}</td>
        </tr>
    </table>
</body>
</html>
7.结果演示
浏览器输入:http://localhost:8081/SSMProject/findCustomerById?id=1

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_36279318/article/details/80186415