• 准备工作
create database ssm;
create table account (
    id int primary key auto_increment,
    name varchar(100),
    money double(7,2)
);
  • 创建Maven工程

  • 导入坐标

    <!--    spring相关坐标-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.20</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.15</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.3.15</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.3.20</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.20</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>
    
    <!--    mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.7</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.28</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    
  • 创建实体类

    domain.Account

    package com.mkl.domain;
    
    public class Account {
        private Integer id;
        private String name;
        private Double 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;
        }
    
        @Override
        public String toString() {
            return "Account{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", money=" + money +
                    '}';
        }
    }
    
  • 创建Mapper接口

    mapper.AccountMapper

    package com.mkl.mapper;
    
    import com.mkl.domain.Account;
    
    import java.util.List;
    
    public interface AccountMapper {
        void save(Account account); // 保存
    
        List<Account> findAll(); // 查询
    }
    
  • 创建业务层接口与实现

    • 接口

      service.AccountService

      package com.mkl.service;
      
      import com.mkl.domain.Account;
      
      import java.util.List;
      
      public interface AccountService {
          public void save(Account account);
      
          public List<Account> findAll();
      }
      
    • 实现

      service.impl.AccountServiceImpl

      @Service("accountService")
      public class AccountServiceImpl implements AccountService {
      
          @Autowired
          private AccountMapper accountMapper;
      
          @Override
          public void save(Account account) {
              accountMapper.save(account);
          }
      
          @Override
          public List<Account> findAll() {
              return accountMapper.findAll();
          }
      }
      
  • 编写控制层

    controller.AccountController

    @Controller
    @RequestMapping("/account")
    public class AccountController {
    
        @Autowired
        private AccountService accountService;
    
        //保存
        @RequestMapping(value = "/save",produces = "text/html;charset=UTF-8")
        @ResponseBody
        public String save(Account account){
            accountService.save(account);
            return "保存成功";
        }
    
        //查询
        @RequestMapping("/findAll")
        public ModelAndView findAll(){
            List<Account> accountList = accountService.findAll();
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("accountList",accountList);
            modelAndView.setViewName("accountList");
            return modelAndView;
        }
    }
    
  • 编写表单与列表页面

    创建webapp

    File > Structure > add
    
    • 表单

      save.jsp

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>Title</title>
      </head>
      <body>
          <h1>添加账户信息表单</h1>
          <form name="accountForm" action="${pageContext.request.contextPath}/account/save" method="post">
              账户名称:<input type="text" name="name"><br>
              账户金额:<input type="text" name="money"><br>
              <input type="submit" value="保存"><br>
          </form>
      </body>
      </html>
      
    • 列表

      WEB-INF/pages/accountList.jsp

      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
      <html>
      <head>
          <title>Title</title>
      </head>
      <body>
          <h1>展示账户数据列表</h1>
          <table border="1">
              <tr>
                  <th>账户id</th>
                  <th>账户名称</th>
                  <th>账户金额</th>
              </tr>
      
              <c:forEach items="${accountList}" var="account">
                  <tr>
                      <td>${account.id}</td>
                      <td>${account.name}</td>
                      <td>${account.money}</td>
                  </tr>
              </c:forEach>
      
          </table>
      </body>
      </html>
      
  • 创建配置文件

    • web.xml

      Spring监听器、Springmvc前端控制器、乱码过滤器
      webapp/WEB-INF/web.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://java.sun.com/xml/ns/javaee"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
      
          <!--spring 监听器-->
          <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>
      
          <!--springmvc的前端控制器-->
          <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:spring-mvc.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>
      
          <!--乱码过滤器-->
          <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>
      
      </web-app>
      
    • applicationContext.xml

      service和mapper组件扫描、加载properties文件、配置数据源、配置sessionFactory
      扫描mapper实现类、声明式事务、事务增强、事务织入
      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: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.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">
      
          <!--组件扫描 扫描service和mapper-->
          <context:component-scan base-package="com.mkl">
              <!--排除controller的扫描-->
              <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
          </context:component-scan>
      
          <!--加载propeties文件-->
          <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
      
          <!--配置数据源信息-->
          <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
              <property name="driverClass" value="${jdbc.driver}"></property>
              <property name="jdbcUrl" value="${jdbc.url}"></property>
              <property name="user" value="${jdbc.username}"></property>
              <property name="password" value="${jdbc.password}"></property>
          </bean>
      
          <!--配置sessionFactory-->
          <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="dataSource"></property>
              <!--加载mybatis核心文件-->
              <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property>
          </bean>
      
          <!--扫描mapper所在的包 为mapper创建实现类-->
          <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="basePackage" value="com.mkl.mapper"></property>
          </bean>
      
      
          <!--声明式事务控制-->
          <!--平台事务管理器-->
          <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource"></property>
          </bean>
      
          <!--配置事务增强-->
          <tx:advice id="txAdvice">
              <tx:attributes>
                  <tx:method name="*"/>
              </tx:attributes>
          </tx:advice>
      
          <!--事务的aop织入-->
          <aop:config>
              <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.mkl.service.impl.*.*(..))"></aop:advisor>
          </aop:config>
      
      </beans>
      
    • log4j.properties

      日志

      #
      # Hibernate, Relational Persistence for Idiomatic Java
      #
      # License: GNU Lesser General Public License (LGPL), version 2.1 or later.
      # See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
      #
      
      ### direct log messages to stdout ###
      log4j.appender.stdout=org.apache.log4j.ConsoleAppender
      log4j.appender.stdout.Target=System.err
      log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
      log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
      
      ### direct messages to file hibernate.log ###
      #log4j.appender.file=org.apache.log4j.FileAppender
      #log4j.appender.file.File=hibernate.log
      #log4j.appender.file.layout=org.apache.log4j.PatternLayout
      #log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
      
      ### set log levels - for more verbose logging change 'info' to 'debug' ###
      
      log4j.rootLogger=all, stdout
      
    • spring-mvc.xml

      controller组件扫描、mvc注解驱动、内部资源视图解析器、开发静态资源访问权限

      <?xml version="1.0" encoding="UTF-8" ?>
      <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:mvc="http://www.springframework.org/schema/mvc"
          xmlns:context="http://www.springframework.org/schema/context"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd">
      
          <!--组件扫描  主要扫描controller-->
          <context:component-scan base-package="com.mkl.controller"></context:component-scan>
          <!--配置mvc注解驱动-->
          <mvc:annotation-driven></mvc:annotation-driven>
          <!--内部资源视图解析器-->
          <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix" value="/WEB-INF/pages/"></property>
              <property name="suffix" value=".jsp"></property>
          </bean>
          <!--开发静态资源访问权限-->
          <mvc:default-servlet-handler></mvc:default-servlet-handler>
      </beans>
      
    • sqlMapConfig.xml

      加载properties文件、定义别名、环境、加载映射

      <?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>
      
          <!--加载properties文件-->
          <properties resource="jdbc.properties"></properties>
      
          <!--定义别名-->
          <typeAliases>
              <!--<typeAlias type="com.mkl.domain.Account" alias="account"></typeAlias>-->
              <package name="com.mkl.domain"></package>
          </typeAliases>
      
          <!--环境-->
          <environments default="developement">
              <environment id="developement">
                  <transactionManager type="JDBC"></transactionManager>
                  <dataSource type="POOLED">
                      <property name="driver" value="${jdbc.driver}"></property>
                      <property name="url" value="${jdbc.url}"></property>
                      <property name="username" value="${jdbc.username}"></property>
                      <property name="password" value="${jdbc.password}"></property>
                  </dataSource>
              </environment>
          </environments>
      
          <!--加载映射-->
          <mappers>
              <!--<mapper resource="com/mkl/mapper/AccountMapper.xml"></mapper>-->
              <package name="com.mkl.mapper"></package>
          </mappers>
      
      
      </configuration>
      
    • AccountMapper.xml

      编写sql语句
      com.mkl.mapper.AccountMapper.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.mkl.mapper.AccountMapper">
          <insert id="save" parameterType="account">
              insert into account values(#{id},#{name},#{money})
          </insert>
          <select id="findAll" resultType="account">
              select * from account
          </select>
      </mapper>
      
posted on 2022-09-21 11:28  _tiny_coder  阅读(18)  评论(0编辑  收藏  举报