原创

maven整合Spring+SpringMVC+Mybatis(ssm)


项目源码:https://gitee.com/wu_xu_bin/newssm

第一步、新建一个有webapp框架的maven项目

点击新建项目选择sdk版本,选中Maven勾选添加框架,选中maven下的webapp框架,点击下一步

在这里插入图片描述

填写路径和工程名字,点击下一步

在这里插入图片描述

为了加快ssm工程的创建可以手动添加一对Property

Name为archetypeCatalog

Value为internal

添加之后可以提升2~3倍的创建速度

在这里插入图片描述

选择Maven版本,点击下一步

在这里插入图片描述

填写项目名和项目存储路径,点击完成

在这里插入图片描述

第二步、创建相关文件夹

创建在mian文件夹下创建java和resources文件夹

在这里插入图片描述

然后设置java为Sources Root

在这里插入图片描述

然后设置resources为Resources Root

在这里插入图片描述

完成后结果如图

在这里插入图片描述

第三步、配置pom.xml、web.xml、applicationContext.xml、springmvc.xml、jdbcConfig.properties、log4j.properties文件

先在pom.xml文件导入相关依赖(对应的依赖都有注释)

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.mogong</groupId>
  <artifactId>ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
      <!--spring和springmvc-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>5.1.9.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>5.0.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.0.2.RELEASE</version>
      </dependency>
      <!--/spring和springmvc-->
      <!--单元测试-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>5.0.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>compile</scope>
      </dependency>
      <!--/单元测试-->
      <!--事务-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>5.0.2.RELEASE</version>
      </dependency>
      <!--/事务-->
      <!--jdbc模板的技术-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.0.2.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.6</version>
      </dependency>
      <!--/jdbc模板的技术-->
      <!--导入servlet-->
      <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.0</version>
          <scope>provided</scope>
      </dependency>
      <!--/导入servlet-->
      <!--写el表达式-->
      <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>
      <!--/写el表达式-->
      <!--添加log4j和slf4j日志框架-->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.25</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-log4j12</artifactId>
          <version>1.7.25</version>
      </dependency>
      <!--/添加日志框架-->
      <!--添加mybatis框架-->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.5</version>
      </dependency>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.0</version>
      </dependency>
      <!--/添加mybatis框架-->
      <!--添加c3p0连接池-->
      <dependency>
          <groupId>c3p0</groupId>
          <artifactId>c3p0</artifactId>
          <version>0.9.1.2</version>
      </dependency>
      <!--/添加c3p0连接池-->
      <!--导入jackson,作用:将ajax对象封装到bean对象中-->
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.9.0</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.9.0</version>
      </dependency>
      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.9.0</version>
      </dependency>
      <!--导入jackson,作用:将ajax对象封装到bean对象中-->
  </dependencies>

  <build>
    <finalName>ssm</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

编写配置文件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>Archetype Created Web Application</display-name>

    <!-- 配置监听器 -->
    <!--配置spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 配置监听器,监听request域对象的创建和销毁的 -->
    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>
    <!--所以要配置文件的路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>
    <!--配置前端控制器(加载classpath:springmvc.xml 服务器启动创建servlet)-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--服务器启动的时候,让DispatcherServlet对象创建-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--解决中文乱码的过滤器-->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 委派过滤器 -->
<!--    <filter>-->
<!--        <filter-name>springSecurityFilterChain</filter-name>-->
<!--        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>-->
<!--    </filter>-->
<!--    <filter-mapping>-->
<!--        <filter-name>springSecurityFilterChain</filter-name>-->
<!--        <url-pattern>/*</url-pattern>-->
<!--    </filter-mapping>-->

<!--    <welcome-file-list>-->
<!--        <welcome-file>index.html</welcome-file>-->
<!--        <welcome-file>index.htm</welcome-file>-->
<!--        <welcome-file>index.jsp</welcome-file>-->
<!--        <welcome-file>default.html</welcome-file>-->
<!--        <welcome-file>default.htm</welcome-file>-->
<!--        <welcome-file>default.jsp</welcome-file>-->
<!--    </welcome-file-list>-->
</web-app>

在resources文件夹下创建applicationContext.xml配置文件(将spring和mybatis的相关配置整合到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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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/tx
        http://www.springframework.org/schema/context/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 开启注解扫描,管理service和dao -->
    <context:component-scan base-package="cn.service">
    </context:component-scan>
    <context:component-scan base-package="cn.dao">
    </context:component-scan>

    <!--开启aop注解,若在此处开启无效,则使用注解开启-->
<!--    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>-->

    <!--导入jdbc配置文件-->
    <context:property-placeholder location="classpath:jdbcConfig.properties"/>

    <!--spring整合mybatis框架-->
    <!--配置连接池-->
    <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>
    <!--配置SqlSessionFactory工厂-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--传入pagehelper插件(分页插件)-->
<!--        <property name="plugins">-->
<!--            <array>-->
                <!--传入插件的对象-->
<!--                <bean class="com.github.pagehelper.PageInterceptor">-->
<!--                    <property name="properties">-->
<!--                        <props>-->
<!--                            <prop key="helperDialect">mysql</prop>-->
<!--                            <prop key="reasonable">true</prop>-->
<!--                        </props>-->
<!--                    </property>-->
<!--                </bean>-->
<!--            </array>-->
<!--        </property>-->
    </bean>
    <!--配置AccountDao接口所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.dao"/>
    </bean>
    <!--配置Spring框架声明式事务管理-->
    <!--配置事务管理器-->
<!--    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">-->
<!--        <property name="dataSource" ref="dataSource"/>-->
<!--    </bean>-->
    <!--配置事务通知-->
<!--    <tx:advice id="txAdvice" transaction-manager="transactionManager">-->
<!--        <tx:attributes>-->
<!--            <tx:method name="find*" read-only="true"/>-->
<!--            <tx:method name="*" isolation="DEFAULT"/>-->
<!--        </tx:attributes>-->
<!--    </tx:advice>-->
    <!--配置AOP增强-->
<!--    <aop:config>-->
<!--        <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.service.impl.AccountServiceImpl.*(..))"/>-->
<!--    </aop:config>-->
</beans>

在resources文件夹下创建jdbcConfig.properties配置文件(为mybatis中的dataSource提供连接数据)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=12345678

在resources文件夹下创建springmvc.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启注解扫描,只扫描Controller注解-->
    <context:component-scan base-package="cn">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--配置视图解析器-->
    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--过滤静态资源-->
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/img/**" location="/img/"/>
    <mvc:resources mapping="/plugins/**" location="/plugins/"/>
    <!--开启springmvc注解的支持-->
    <mvc:annotation-driven/>
</beans>

在resources文件夹下创建log4j.properties配置文件(配置log4j日志格式)

#Set root category priority to INFO and its only appender to CONSOLE.
#log4j. rootCategory=INFO, CONSOLEdebug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

至此一个ssm项目已经创建完成。

第四步、编写测试类

接下来通过编写测试类来测试ssm项目是否可以运行。

先在java文件夹下创建如下包

在这里插入图片描述

然后在controller包下创建AccountController.java类

并写入如下测试代码:

package cn.controller;

import cn.domain.Account;
import cn.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        System.out.println("表现层,查询所有账户...");
        ModelAndView mv=new ModelAndView();
        //调用service的方法
        List<Account> accounts=accountService.findAll();
        mv.addObject("accounts",accounts);
        mv.setViewName("account-list");
        return mv;
    }
    @RequestMapping("/save")
    public String save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("表现层,保存账户...");
        accountService.saveAccount(account);
        return "redirect:findAll";
    }
}

在domain包下创建单元对象Account,代码如下

package cn.domain;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }
}

在service包下创建AccountService接口,并在该包下创建一个impl包可供存放service包下的接口实现类

AccountService接口,代码入下:

package cn.service;

import cn.domain.Account;
import org.springframework.stereotype.Service;

import java.util.List;

public interface AccountService {
    //查询所有账户
    public List<Account> findAll();

    //保存账户信息
    public void saveAccount(Account account);
}

impl包下的AccountService接口的实现类AccountServiceImpl代码如下

package cn.service.impl;

import cn.dao.AccountDao;
import cn.domain.Account;
import cn.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAll() {
        System.out.println("业务层:查询所有账户");
        return accountDao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层:保存账户");
        accountDao.saveAccount(account);
    }
}

在dao包下创建AccountDao持久层接口,详细代码如下

package cn.dao;

import cn.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface AccountDao {
    //查询所有账户
    @Select("select * from account")
    public List<Account> findAll();

    //保存账户信息
    @Insert("insert into account (name,money) values(#{name},#{money})")
    public void saveAccount(Account account);
}

这是accoun表t的建表语句

create table account(
id int not null primary key AUTO_INCREMENT,
name varchar(32),
money double
)

在test包下编写测试类TestSpring.java,测试service层中的findAll方法,代码如下

package cn.test;

import cn.domain.Account;
import cn.service.AccountService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestSpring {

    private ApplicationContext ac;
    @Before
    public void init(){
        ac=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }
    @After
    public void closesql(){
    }

    @Test
    public void testFindAll(){
        AccountService as=(AccountService) ac.getBean("accountService");
        List<Account> accounts=as.findAll();
        for (Account account:accounts) {
            System.out.println(account);
        }
    }
}

右键选择testFindAll方法,运行此方法,若是运行结果如下

在这里插入图片描述

则说明service层的findAll方法没有问题

接下来编写index.jsp测试页面,代码如下

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<html>
<body>
<a href="${pageContext.request.contextPath}/account/findAll">查询全部</a><br>
<form action="${pageContext.request.contextPath}/account/save" method="post">
    name:<input name="name" type="text"/><br>
    money:<input name="money" type="text"/>(只允许输入数字)<br>
    <button type="submit" value="提交">提交</button>
</form>
</body>
</html>

然后在webapp的pages包下创建一个显示表数据的account-list.jsp页面,代码如下

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <table>
        <tr>
            <th>id</th>
            <th>name</th>
            <th>money</th>
        </tr>
        <c:forEach items="${accounts}" var="account">
        <tr>
            <td>${account.id}</td>
            <td>${account.name}</td>
            <td>${account.money}</td>
        </tr>
        </c:forEach>
    </table>
</body>
</html>

至此ssm项目的测试测试部分就创建好了

最后将ssm部署到tomcat上,详细步骤如下图

在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

至此运行项目

出现index页面,如下图

在这里插入图片描述

点击查询全部,如下图

在这里插入图片描述

然后填写表单并提交页面自动转跳至account-list页面,如下图

在这里插入图片描述

在这里插入图片描述

到此ssm项目创建并测试成功,结束。

java
Spring
SpringMVC
Mybatis
maven
  • 作者:陌攻(联系作者)
  • 发表时间:2021-03-22 14:27
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 公众号转载:请在文末添加作者公众号二维码
  • 评论