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

SSM 框架快速搭建与整合

程序员文章站 2022-03-19 15:31:38
1、创建Maven项目并导入依赖在 IDEA 中创建一个空的 Maven 项目添加 WEB 项目支持导入 SSM 环境相关依赖pom.xml 相关代码如下: junit junit

1、创建Maven项目并导入依赖

在 IDEA 中创建一个空的 Maven 项目
SSM 框架快速搭建与整合
添加 WEB 项目支持

SSM 框架快速搭建与整合

1.1、导入 SSM 环境相关依赖

pom.xml 相关代码如下:

    <dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--数据库连接池-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!--Servlet - JSP-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
    </dependencies>

1.2、防止静态资源导出失败

在 pom.xml 中继续增加以下代码:

    <!-- 在bulid中配置resources,防止资源导出失败问题   -->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

到此为止,Maven 环境已经搭建完毕

1.3、添加 lib 依赖到 WEB 项目中

在 Project Structure 中,创建 lib 目录

SSM 框架快速搭建与整合
同时添加并选中 Maven 中的依赖!
ps:这一步很重要,一旦忘记配置的话后面项目就跑不起来!!!
SSM 框架快速搭建与整合

1.4、创建各个包

项目的结构如下:
有 4 个包,分别为 controller, dao, pojo, service
pojo 为实体类,dao 为数据库层, service 为业务层, controller 为前端控制器
resource 下有 5 个 xml 文件以及 1 个 properties 文件:
applicationContext 负责整合 spring-dao, spring-mvc, spring-service
database.properties 为数据库配置文件,后续在 mybatis 的数据库连接池中读入

SSM 框架快速搭建与整合

2、Mybatis 模块搭建

2.1、创建数据库表

这里创建一个订单表

use `mybatis`;
drop table if exists `order`;

/*==============================================================*/
/* Table: "order"                                               */
/*==============================================================*/
create table `order`
(
   `orderId`              int(10) not null auto_increment comment '订单Id',
   `orderType`            varchar(10) not null comment '订单类型',
   `money`                double not null comment '订单交易金额',
   `orderRemark`          varchar(100) not null comment '订单备注',
   primary key (orderId)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

alter table `order` comment '订单实体类';

insert into `order` (`orderId`,`orderType`,`money`,`orderRemark`) values 
(1,'买入','100.00','买入5个冰淇淋'),
(2,'卖出','250.00','卖出10个冰淇淋'),
(3,'买入','150.00','买入15个大蛋糕')

2.2、编写 database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

2.3、编写 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>

    <typeAliases>
        <package name="com.ssm.pojo"/>
    </typeAliases>

</configuration>

2.4、编写 spring-dao.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:database.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}"/>
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <property name="autoCommitOnClose" value="false"/>
        <property name="checkoutTimeout" value="10000"/>
        <property name="acquireIncrement" value="2"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.ssm.dao"/>
    </bean>

</beans>

2.5、编写 pojo 实体类

要生成 getter , setter 以及构造方法。

public class Order {
    private int orderId;
    private String orderType;
    private double money;
    private String orderRemark;
}

2.6、编写 dao 接口 及 Mapper

OrderMapper

public interface OrderMapper {
    int addOrder(Order order);
    int deleteOrder(@Param("orderId") int id);
    Order queryOrderById(@Param("orderId") int id);
    List<Order> queryAllOrders();
}

OrderMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.dao.OrderMapper">

    <insert id="addOrder" parameterType="Order">
        insert into mybatis.order (orderType,money,orderRemark)
        values (#{orderType},#{money},#{orderRemark})
    </insert>

    <delete id="deleteOrder" parameterType="int">
        delete from mybatis.order where orderId = #{orderId}
    </delete>

    <select id="queryOrderById" parameterType="int" resultType="Order">
        select * from mybatis.order where orderId = #{orderId}
    </select>

    <select id="queryAllOrders" resultType="Order">
        select * from mybatis.order;
    </select>

</mapper>

2.7、编写 service 接口及 实现类

OrderService

public interface OrderService {
    int addOrder(Order order);
    int deleteOrder(int id);
    Order queryOrderById(int id);
    List<Order> queryAllOrders();
}

OrderServiceImpl

public class OrderServiceImpl implements OrderService {

    private OrderMapper orderMapper;

    public void setOrderMapper(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    public int addOrder(Order order) {
        return orderMapper.addOrder(order);
    }

    public int deleteOrder(int id) {
        return orderMapper.deleteOrder(id);
    }

    public Order queryOrderById(int id) {
        return orderMapper.queryOrderById(id);
    }

    public List<Order> queryAllOrders() {
        return orderMapper.queryAllOrders();
    }
}

至此,Mybatis 模块基本完成。

3、Mybatis 整合 Spring

3.1、添加到同一个 ApplicationContext 下

SSM 框架快速搭建与整合

3.2、编写 applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>

</beans>

3.3、编写 spring-service.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.ssm.service"/>

    <bean id="OrderServiceImpl" class="com.ssm.service.OrderServiceImpl">
        <property name="orderMapper" ref="orderMapper"/>
    </bean>

    <bean id = "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref = "dataSource"/>
    </bean>

</beans>

至此, Mybatis 与 Spring 的整合完成。

4、整合 Spring MVC

4.1、配置 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <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:applicationContext.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>

    <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>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

4.2、编写 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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <context:component-scan base-package="com.ssm.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

4.3、整合 spring-mvc.xml

在 applicationContext 下,导入 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>

</beans>

5、测试 CRUD

在 test 目录下新建一个类用于单元测试

public class DaoTest {
    @Test
    public void test() {
        ApplicationContext cpx = new ClassPathXmlApplicationContext("applicationContext.xml");
        OrderService orderService = (OrderService) cpx.getBean("OrderServiceImpl");
        List<Order> orderList = orderService.queryAllOrders();
        for (Order order : orderList) {
            System.out.println(order);
        }
    }
}

测试成功:

SSM 框架快速搭建与整合
其他几个功能也是类似的,只要能够跑通其中一个,基本上问题不大。
以上就是 SSM 环境的基本搭建过程,Spring MVC 后面再说。

6、Spring MVC 测试

6.1、部署Tomcat

SSM 框架快速搭建与整合

6.2、前后端请求测试

后端返回数据

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @RequestMapping("/allOrder")
    public String getAllOrder(Model model){
        List<Order> orderList = orderService.queryAllOrders();
        model.addAttribute("orderList",orderList);
        return "main";
    }

}

前端发送请求

<a href="${pageContext.request.contextPath}/order/allOrder">跳转到首页</a>

前端获取数据

<c:forEach var="order" items="${orderList}">
      <tr>
          <td>${order.orderId}</td>
          <td>${order.orderType}</td>
          <td>${order.money}</td>
          <td>${order.orderRemark}</td>
      </tr>
  </c:forEach>

6.3、运行结果

SSM 框架快速搭建与整合
以上结果说明 Spring MVC 运行环境没问题。
至此,SSM 环境搭建完毕。

本文地址:https://blog.csdn.net/qq_45716120/article/details/111771362