2.4.10 SSM integration, use mybatis/ spring/ springmvc separately in SSM environment, spring integration mybatis/ springmvc, spring configuration declarative transaction

table of Contents

SSM integration

1.1 Analysis of requirements and steps

1.2 Environment setup

1.3 Writing mybatis can be used alone in the ssm environment

1.4 Writing spring can be used alone in the ssm environment

1.5 spring integration mybatis

1.6 Writing springMVC can be used alone in the ssm environment

1.7 Spring integrates springMVC

1.8 Spring configuration declarative transaction

1.9 Modify operation

1.9.1 Data Echo

1.9.2 Account update

1.10 Batch delete


 

SSM integration

1.1 Analysis of requirements and steps

demand

Use the ssm framework to complete the addition, deletion, and modification of the account table.
Step analysis

1.2 Environment setup

1) Prepare database and table records

CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `account`(`id`,`name`,`money`) values (1,'tom',1000),
(2,'jerry',1000);

2) Create a web project

 

1.3 Writing mybatis can be used alone in the ssm environment

Requirements: based on mybatis to realize the query of the account table

1) Related coordinates

<!--mybatis坐标-->
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.15</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

2) Account entity

package com.lagou.domain;

public class Account {

    private Integer id;
    private String name;
    private Double money;

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

3) AccountDao interface

package com.lagou.dao;


public interface AccountDao {

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


    void save(Account account);

    Account findById(Integer id);

    void update(Account account);

    void deleteBatch(Integer[] ids);
}

4) AccountDao.xml mapping

<?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.lagou.dao.AccountDao">
    <select id="findAll" resultType="Account">
        select * from account
    </select>
</mapper>

5) Mybatis core configuration file

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

SqlMapConfig.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>

    <!--加载properties-->
    <properties resource="jdbc.properties"/>

    <!--类型别名配置-->
    <typeAliases>
        <package name="com.lagou.domain"/>
    </typeAliases>

    <!--环境配置-->
    <environments default="dev">

        <!--使用MySQL环境数据源-->
        <environment id="dev">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--加载映射-->
    <mappers>
        <package name="com.lagou.dao"/>
    </mappers>

</configuration>

6) Test code

package com.lagou.test;

public class MybatisTest {

    @Test
    public void  testMybatis() throws IOException {

        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        AccountDao mapper = sqlSession.getMapper(AccountDao.class);

        List<Account> all = mapper.findAll();

        for (Account account : all) {
            System.out.println(account);
        }

        sqlSession.close();
    }
}

 

1.4 Writing spring can be used alone in the ssm environment

1) Related coordinates

<!--spring坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>

2) AccountService interface

package com.lagou.service;

public interface AccountService {


    public List<Account> findAll();

    void save(Account account);

    Account findById(Integer id);

    void update(Account account);

    void deleteBatch(Integer[] ids);
}

3) AccountServiceImpl implementation

package com.lagou.service.imp;

@Service    // 配置了注解, 所以要在spring配置文件中开启注解扫描
public class AccountServiceImpl implements AccountService {

    /*
        测试spring在ssm环境中的单独使用
     */
    public List<Account> findAll() {
        System.out.println("findAll执行了....");
        return null;
    }
}

4) Spring core configuration file
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"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://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/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--因为上面的Service实现类中配置了@Service注解, 所以要开启注解扫描, 只扫描service下-->
    <context:component-scan base-package="com.lagou.service"/>

</beans>

5) Test code

package com.lagou.test;

@RunWith(SpringJUnit4ClassRunner.class)
public class SpringTest {

    @Autowired  // spring自动注入
    private AccountService accountService;

    @Test
    public void testSpring(){

        List<Account> all = accountService.findAll();
        for (Account account : all) {
            System.out.println("findAll执行了....");
        }
    }
}

 

1.5 spring integration mybatis

1) Integrated thinking

    By handing the creation right of the proxy object of mybatis interface to spring management, we can inject the proxy object of dao into the service, and the integration of spring and mybatis is completed at this time.

2) Import the integration package

        <!--mybatis整合spring坐标-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

3) Spring configuration file management mybatis
Note: The main configuration file of mybatis can be deleted at this time.

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       	http://www.springframework.org/schema/beans	http://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/tx/spring-tx.xsd
       	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--配置IOC相关操作:开启注解扫描-->
    <context:component-scan base-package="com.lagou.service"></context:component-scan>

    <!--spring整合mybatis开始, ...................-->
    <!--sqlSessionFactory  sqlSession  mapper三个对象的创建都交给spring-->

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

        <!--要生产sqlSession, 需要数据源-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>

        <!--2, sqlSessionFactory的创建权交给了spring 生产sqlSession-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="typeAliasesPackage" value="com.lagou.domain"></property>

           <!--引入加载mybatis的核心配置文件,如果其中没有必要项, 也可以不用去加载-->
           <!-- <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>-->
        </bean>

        <!--3, mapper映射扫描 MapperScannerConfigurer扫描该包下所有接口,生成代理对象存到IOC容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.lagou.dao"></property>
        </bean>

    <!--spring整合mybatis结束.....................-->

</beans>

4) Modify AccountServiceImpl

package com.lagou.service.imp;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {

    //需要用到AccountDao的代理对象
    @Autowired
    private AccountDao accountDao;

    /*
        测试spring在ssm环境中的单独使用
     */
    public List<Account> findAll() {
        List<Account> all = accountDao.findAll();
        return all;
    }
}

 

1.6 Writing springMVC can be used alone in the ssm environment

Requirements: access to the method in the controller to query all accounts, and jump to the list.jsp page for list display

1) Related coordinates

        <!--springMVC坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <!--列表展示-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

2) Import page resources


3) Front controller DispathcerServlet

<?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>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>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <!--拦截所有-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!--中文乱码过滤器:解决post方式提交的乱码-->
    <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>

</bean>

4)AccountController和 list.jsp

package com.lagou.controller;

@Controller
@RequestMapping("/account")
public class AccountController {

    /*
        查询所有用户
     */
    @RequestMapping("/findAll")
    public  String findAll(Model model){

        List<Account> list = new ArrayList<>();
        list.add(new Account(1,"张三",1000d));
        list.add(new Account(2,"李四",1000d));
        model.addAttribute("list", list);
        return "list";
    }
}
 <%--从响应中拿到数据--%>
 <c:forEach items="${list}" var="account">

 <tr>
     <td>
         <input type="checkbox" name="ids" value="${account.id}">
     </td>
     <td>${account.id}</td>
     <td>${account.name}</td>
     <td>${account.money}</td>
     <td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/account/findById?id=${account.id}">修改</a>&nbsp;
         <a class="btn btn-default btn-sm" href="">删除</a></td>
 </tr>
 </c:forEach>

 

5) springMVC core configuration file

<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">


    <!--1.组件扫描:只扫描controller-->
    <context:component-scan base-package="com.lagou.controller"></context:component-scan>

    <!--2.mvc注解增强:处理器映射器及处理器适配器, 增强对json的读写-->
    <mvc:annotation-driven></mvc:annotation-driven>


    <!--3.视图解析器-->
    <bean id="resourceViewResolve" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--4.放行全部静态资源-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

</beans>

 

1.7 Spring integrates springMVC

1) Integration of thinking
spring and springMVC actually do not need to be integrated at all, they are originally one.
But we need to integrate spring and web container so that the spring configuration file is automatically loaded when the web container starts, and the spring ioc container is destroyed when the web container is destroyed.

2) Spring and web container integration

ContextLoaderListener loading [Master]
You can use the ContextLoaderListener listener in the spring-web package to monitor the creation and destruction of the servletContext container to create or destroy the IOC container at the same time.

    <!--配置spring的监听器-->
    <!--监听servletContext对象的创建与销毁, 同步加载applicationContext文件创建和销毁IOC容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
</web-app>

3) Modify AccountController

package com.lagou.controller;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;
    /*
        查询所有用户
     */

    @RequestMapping("/findAll")
    public  String findAll(Model model){

        //实现查询所有账户
        List<Account> list = accountService.findAll();

        // 把封装好的list存到model中
        model.addAttribute("list",list);

        return "list";
    }

 

1.8 Spring configuration declarative transaction

1) Add declarative transaction to spring configuration file

    <!--spring的声明式事务-->
    <!--1.事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--2.开始事务注解的支持-->
    <tx:annotation-driven/>

2)add.jsp

<form action="${pageContext.request.contextPath}/account/save" method="post">
    <div class="form-group">
        <label for="name">姓名:</label>
        <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
    </div>
          <div class="form-group">
        <label for="money">余额:</label>
        <input type="text" class="form-control" id="money" name="money" placeholder="请输入余额">
    </div>

    <div class="form-group" style="text-align: center">
        <input class="btn btn-primary" type="submit" value="提交" />
        <input class="btn btn-default" type="reset" value="重置" />
        <input class="btn btn-default" type="button" onclick="history.go(-1)" value="返回" />
    </div>
</form>

3)AccountController

package com.lagou.controller;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;
    
    @RequestMapping("/save")
    public String save(Account account){

        accountService.save(account);
        // 跳转到findAll方法重新查询一次数据库进行数据的遍历展示
        // 重定向, 要添加redirect
        return "redirect:/account/findAll";
    }
}

4) AccountService interface and implementation class

package com.lagou.service.imp;

@Service
@Transactional
public class AccountServiceImpl implements AccountService {

    //需要用到AccountDao的代理对象
    @Autowired
    private AccountDao accountDao;
  
    /*
        账户添加
     */
    @Override
    public void save(Account account) {

        accountDao.save(account);

    }
}

5)AccountDao

package com.lagou.dao;

public interface AccountDao {

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

    void save(Account account);

    Account findById(Integer id);

    void update(Account account);

    void deleteBatch(Integer[] ids);
}

6) AccountDao.xml mapping

    <!-- 添加账户  void save(Account account);-->
    <insert id="save" parameterType="account">
        insert into account(name,money)  values(#{name},#{money})
    </insert>

 

 

1.9 Modify operation

1.9.1 Data Echo

① AccountController

    /*
        根据id查询账户信息,完成账户回显
     */
    @RequestMapping("/findById")
    public String findById(Integer id,Model model){

       Account account =  accountService.findById(id);

       //存到model中
        model.addAttribute("account",account);

        //视图跳转
        return  "update";

    }

② AccountService interface and implementation class

    Account findById(Integer id);
    @Override
    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

③ AccountDao interface and mapping file

    Account findById(Integer id);
    <!--根据ID查询账户信息   Account findById(Integer id);-->
    <select id="findById" parameterType="int" resultType="account">
        select * from account where id = #{id}
    </select>

④ update.jsp

<form action="${pageContext.request.contextPath}/account/update" method="post">
    <input type="hidden" name="id" value="${account.id}">
    <div class="form-group">
        <label for="name">姓名:</label>
        <input type="text" class="form-control" id="name" name="name" value="${account.name}" placeholder="请输入姓名">
    </div>
    <div class="form-group">
        <label for="money">余额:</label>
        <input type="text" class="form-control" id="money" name="money"  value="${account.money}" placeholder="请输入余额">
    </div>

    <div class="form-group" style="text-align: center">
        <input class="btn btn-primary" type="submit" value="提交" />
        <input class="btn btn-default" type="reset" value="重置" />
        <input class="btn btn-default" type="button" onclick="history.go(-1)" value="返回" />
    </div>
</form>

 

1.9.2 Account update

<form action="${pageContext.request.contextPath}/account/update" method="post">
    <%--不显示在页面中, 但是提交的时候, 也会跟着一起被提交--%>
    <input type="hidden" name="id" value="${account.id}">
    <div class="form-group">
        <label for="name">姓名:</label>
        <input type="text" class="form-control" id="name" name="name" value="${account.name}" placeholder="请输入姓名">
    </div>
    <div class="form-group">
        <label for="money">余额:</label>
        <input type="text" class="form-control" id="money" name="money"  value="${account.money}" placeholder="请输入余额">
    </div>

    <div class="form-group" style="text-align: center">
        <input class="btn btn-primary" type="submit" value="提交" />
        <input class="btn btn-default" type="reset" value="重置" />
        <input class="btn btn-default" type="button" onclick="history.go(-1)" value="返回" />
    </div>
</form>

① AccountController

    /*
        更新账户
     */
    @RequestMapping("/update")  // 也就是表单中填写的跳转路径id
    public String update(Account account){
        accountService.update(account);
        return "redirect:/account/findAll"; // 跳转到显示全部页面
    }

② AccountService interface and implementation class

    void update(Account account);
    @Override
    public void update(Account account) {
        accountDao.update(account);
    }

③ AccountDao interface and mapping file

    void update(Account account);
    <update id="update" parameterType="account">
        update account set name = #{name},money = #{money} where id = #{id}
    </update>

 

 

1.10 Batch delete

1)list.jsp

    <%--实现全选全不选效果--%>
    <script>
    $('#checkAll').click(function () {
        /*下面获取所有的复选框, 用prop设置属性值checked */
        $('input[name="ids"]').prop('checked',$(this).prop('checked'));
    })
    </script>

...
    
    <script>
    /*给删除选中按钮绑定点击事件*/
    $('#deleteBatchBtn').click(function () {
            if(confirm('您确定要删除吗')){
                /*保证选中数大于0*/
                if($('input[name=ids]:checked').length > 0){
                    /*提交表单*/
                    $('#deleteBatchForm').submit();
                }

            }else {
                alert('想啥呢,没事瞎操作啥')
            }
    })
</script>

2)AccountController

    /*
        批量删除
     */
    @RequestMapping("/deleteBatch")
    // 多个id
    public String deleteBatch(Integer[] ids){

        accountService.deleteBatch(ids);

        return "redirect:/account/findAll";
    }

3) AccountService interface and implementation class

    void deleteBatch(Integer[] ids);
    @Override
    public void deleteBatch(Integer[] ids) {
        accountDao.deleteBatch(ids);
    }

4) AccountDao interface and mapping file

    void deleteBatch(Integer[] ids);

 

Guess you like

Origin blog.csdn.net/chengh1993/article/details/110789192