Preface:

If you want to turn off the integration tutorial, shake your skull twice, take a big breath, and turn on the integration tutorial when everything is ready. You may have no ideas at all. Some students are still using Eclipse or Myeclipse for development. I would like to say to these friends that the compilation speed of IDEA is very fast. Life is too short to explain, so let’s get started with IDEA directly. This article has tested every step of the build process, and there should be no mistakes. This article also has a more excellent feature, is the use of idea, basically about the operation of idea are more detailed, so don’t worry too much about not masturbation idea! Finally, this article aims to clearly integrate the processes and ideas between the various frameworks.

I believe there are many friends who have learned the SSM framework, and the time to learn should be using Eclipse or Myeclipse development, with the rise of IDEA, the strength of Eclipse, IDEA compilation speed is very fast, usually 2 times faster than EC! Plus frenzied code prompts cause programmers to scream! Of course, I’m not saying Eclipse is bad, but idea is much more convenient and easier to develop, and that’s true. I believe that many friends have switched to IDEA from Eclipse (including me, who was not used to IDEA at the beginning and always kept a heart of fear and awe for fear of failing to type a beautiful Hello Word (you are all great gods, remember that I had been syso and could not type a line of output statement QAQ at that time). As an experienced person, I tell you, these are unnecessary to worry about, as long as you remember, with (tool IDEA) in my hands, code (code) in my hands, tube him 37 forty-nine, pick up the idea is a wanqiao code, I am maozi, so it has this IDEA version of the SSM framework integration, otherwise you think how to knead?

1. Build an integrated environment

1. Put together instructions

SSM integration can use a variety of ways, we choose XML + annotations, do not feel improper, in fact, the most convenient –

2. Integrated ideas:

1. Build an integrated environment first

 

2. Complete the configuration of Spring first

 

3. Then use Spring to integrate the SpringMVC framework

 

4. Then use Spring to integrate MyBatis framework

 

5. Finally, Spring integrates mybatis framework to configure transactions (Spring’s declarative transaction management)

SQL > create database and table structure statement

MySQL > select * from ‘MySQL’;

create database ssm; use ssm; create table account ( id int primary key auto_increment, name varchar(50), money double );

4. Create maven projects

For details on how to create Maven using IDEA, see creating your first Mawen project using IntelliJ Idea

  1. Create Twossm_parent project (package option POM, required)
  2. Create Twossm_web submodule (packaged as war package)
  3. Create Twossm_service submodule (packaged as jar package)
  4. Create Twossm_dao submodule (packaged as jar package)
  5. Create Twossm_domain submodule (packaged as jar package)
  6. Web depends on Service, Service depends on DAO, and DAO depends on Domain
  7. Add dependencies to the < properties > tag and < dependencies > tag in Twossm_parent’s pop. XML file The version numbers can be seen from the coordinate dependencies: spring5X, MySQL3.1.6, Mybatis3.4.5
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> Piler < maven.com. Source > 1.7 < / maven.com piler. Source > < maven.com piler. Target > 1.7 < / maven.com piler. Target > . < spring version > 5.0.2 RELEASE < / spring. Version > < slf4j. Version > 1.6.6 < / slf4j version > < log4j version > 1.2.12 < / log4j version > <. Mysql version > 5.1.6 < / mysql version > < mybatis. Version > 3.4.5 < / mybatis version > </properties> <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> < version > 1.6.8 < / version > < / dependency > < the dependency > < groupId > org. Springframework < / groupId > <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId> The < artifactId > JSTL < / artifactId > < version > 1.2 < / version > < / dependency > <! -- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <! -- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <groupId> c3P0 </groupId> <artifactId> </artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies>Copy the code
  1. To deploy Twossm_web projects, simply add Twossm_web projects to the Tomcat server

5. Write entity classes in the Twossm_domain project

Here, I remind you that you may not be familiar with idea shortcut keys, such as getSet method can not figure out haha, the idea shortcut keys used in this article integration SSM can refer to the following blue font article (click the blue font), familiar with IDEA friends can regard me as not saying, When I put PI (go, go, cover my nose….) IDEA fast implementation interface, find the implementation of the interface, getSet method fast generation and so on commonly used shortcut keys

package com.gx.domain;

import java.io.Serializable;

public class Account implements Serializable {
    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 +
                '} '; }}Copy the code

6. Write dao interfaces

Write the DAO interface IAccountdao in the DAO package

package com.gx.dao;

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

import java.util.List;

public interface IAccountdao {

    public List<Account> findAll();
  
    public void saveAccount(Account account);
}

Copy the code

7. Write the Service interface and implementation class

The service interface:

package com.gx.service;

import com.gx.domain.Account;

import java.util.List;

public interface AccountService {
    // Query all accounts
    public List<Account> findAll(a);

    // Save the account information
    public void saveAccount(Account account);
}

Copy the code

Service interface implementation class:

package com.gx.service.Impl;

import com.gx.domain.Account;
import com.gx.service.AccountService;
import org.springframework.stereotype.Service;

import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Override
    public List<Account> findAll(a) {
        System.out.println("Service Layer: Query all accounts...");
        return null;
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("Service business layer: Save accounts..."); }}Copy the code

At this point, the integration environment is set up and looks like this. Next, set up the Spring configuration!

2. Writing Spring framework code

Build and test the Spring development environment

Create a directory management XML configuration file for resources

Create a directory of resource files called Resources to manage and place XML configuration files

2. Write the applicationContext.xml configuration file

Create the applicationContext.xml configuration file in the Resources resource file and write the specific configuration information

<? The 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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <! <context:component-scan base-package="com.gx" > <context:component-scan base-package="com.gx" > <! - what comments don't scan configuration - > < context: exclude - filter type = "annotation" expression = "org. Springframework. Stereotype. Controller" / > </context:component-scan> </beans>Copy the code

3. Write test methods and conduct tests in the project

1. Create Test package

package com.gx.test;

import com.gx.domain.Account;
import com.gx.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring {
    @Test
    public void run1(a){
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        AccountService as = (AccountService) ac.getBean("accountService"); as.findAll(); }}Copy the code

If the following results are displayed, the Spring development environment is successfully set up.

3. Wrote SpringMVC framework code

Build and test the SpringMVC development environment

1. Configure the DispatcherServlet front-end controller in web. XML

<! <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! > <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <! -- Start the server, Create the servlet--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>Copy the code

2. Configure a DispatcherServlet filter in web. XML to resolve Chinese garbled characters

<! <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>Copy the code

3. The overall effect of the configuration in 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 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_3_0.xsd" version = "3.0" > <display-name>Archetype Created Web Application</display-name> <! <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! > <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <! -- Start the server, Create the servlet--> <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>Copy the code

4. Create the springmvc. XML configuration file and write the configuration file

The springMVC.xml configuration file is also created in the Resources resource folder

<? The 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"> <! -- Enable annotation scan, <context:component-scan base-package="com.gx"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <! - view configuration parser object - > < bean id = "internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <! Filter static resources - > < MVC: resources location = "/ CSS" mapping = "/ CSS / * *" / > < MVC: resources location = "/ images/" mapping ="/images / * * "/ >  <mvc:resources location="/js/" mapping="/js/**"/> <! -- Enable SpringMVC annotation support --> < MVC :annotation-driven/> </beans>Copy the code

5. Create JSP pages and write controller code

Write the index.jsp page

<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <body> <a href="account/findAll"> Test SpringMVC query </a> </body> </ HTML >Copy the code

Write code in the Class class of the AccountController in the Controller layer

package com.gx.controller;

import com.gx.domain.Account;
import com.gx.service.AccountService;
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 java.util.List;

@Controller
public class AccountController {

    @RequestMapping("/account/findAll")
    public String findAll(a){
        System.out.println("Controller presentation layer: Query all accounts...");
        return "list";  // Prefix suffixes are configured in the view parser}}Copy the code

Now create the list.jsp for the Controller jump:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: Bule Date: 2019/9/2 Time: 7:32 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title> title </title> </head> <body> <h2> Query all accounts </h2> </body> </ HTML >Copy the code

6. Deploy Tomcat for testing

7. Test run

4. Spring integrates the SpringMVC framework

Before you integrate, think about how to integrate the Spring and SpringMVC frameworks and how to count the integration as successful. Come with questions!

1. Analysis of the framework principle of Spring integration with SpringMVC

Performance of successful integration: successful invocation of a method in a Service (Spring) object in a Controller (SpringMVC). In order to call the service method in the Controller, you need to inject the service into the controller. You can only call the service method if you have a Service object. There’s nothing wrong with that, but there’s a problem. The web container will load the springmVC.xml configuration file for us. In the SpringmVC.xml configuration file, we will only scan the controller and nothing else. The spring.xml file is never executed. The solution is to load the spring configuration file when you start the server. This is where the listener comes in handy.

2. Configure ContextLoaderListener in web. XML

When the project starts, the applicationContext.xml configuration file is loaded, Configure the ContextLoaderListener listener in web.xml (this listener can only load the configuration file of applicationContext.xml in the WEB-INF directory). There are two ways to load the applicationContext.xml configuration file. The first (not recommended) :

<! -- Configure Spring's listener By default, only the applicationContext. XML configuration file in the WEB-INF directory is loaded --> <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>Copy the code

As for why we strongly recommend the second one, because we will have many configuration files in the integration process, we define a similar resource folder to manage these configuration files, convenient management, convenient maintenance!!

3. Inject the Service object into the Controller, call the service object method and test it

At this point, the spring configuration file will also be loaded when the server is started, so we can inject service into the Controller and start writing the Controller code:

package com.gx.controller;

import com.gx.domain.Account;
import com.gx.service.AccountService;
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 java.util.List;

@Controller
public class AccountController {

    @Autowired   // Inject by type
    private AccountService accountService;

    @RequestMapping("/account/findAll")
    public String findAll(Model model){
        System.out.println("Controller presentation layer: Query all accounts...");

        List<Account> list = accountService.findAll();
        return "list"; }}Copy the code

Finish writing, start testing, start Tomcat, effect

5. Wrote MyBatis framework code

Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis = Mybatis

1. Add annotations to the IAccountdao interface method and write SQL statements

package com.gx.dao;

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

import java.util.List;

@Repository  // This annotation represents a persistence layer, similar to @controller and @service
public interface IAccountdao {

    @Select("select * from account")
    public List<Account> findAll(a);
    @Insert("insert into account (name,money) value(#{name},#{money})")
    public void saveAccount(Account account);
}

Copy the code

2. Create the sqlmapconfig. XML configuration file and write it

As with the previous configuration file creation, create:

<? The 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> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///ssm"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <! -- <mappers> <! -- <mapper class="com.gx.dao.IAccountdao"/> --> <! -- <package name="com.gx.dao"/> </mappers> </configuration>Copy the code

Since I’m using annotations, I think it’s worth mentioning the following three methods:

3. Create and write Mybatis test methods

Create:

package com.gx.test;

import com.gx.dao.IAccountdao;
import com.gx.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMyBatis {

    @Test
    public void run1(a) throws IOException {
        Account account =new Account();
        account.setName("Du Yong blue");
        account.setMoney(200d);
        // Load the configuration file
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // Create the SqlSessionFactory object
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // Create a SqlSession object
        SqlSession session = factory.openSession();
        // Get the proxy object
        IAccountdao dao = session.getMapper(IAccountdao.class);

        / / save
        dao.saveAccount(account);

        // Commit the transaction
        session.commit();

        // Close the resource
        session.close();
        in.close();
    }
    
    @Test
    public void run2(a) throws Exception {
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

        SqlSession session = factory.openSession();

        IAccountdao dao = session.getMapper(IAccountdao.class);

        List<Account> list = dao.findAll();
        for(Account account: list ) { System.out.println(account); } session.close(); in.close(); }}Copy the code

Run tests:

6. Spring integrates MyBatis framework

Before Spring integrates the MyBatis framework, consider what constitutes a successful integration. In fact, this is similar to the previous spring integration of springMVC, in fact, the Service can successfully call dao objects, can do query operations or new data can be stored in the database. Now that Spring is in the IOC container, dao is an interface that can programmically generate a proxy object for the interface. If we can put this proxy object into the IOC container, then the service can take this object and do an injection in the service. Service calls the methods of the DAO proxy object. How do we implement the DAO interface to generate proxy objects into the IOC container? Actually very simple, just need the following operation! Integration purpose: To configure the contents of sqlmapconfig. XML configuration file into applicationContext.xml configuration file

1. Configure the database connection pool in applicationContext.xml

As for why to match the pool, I do not say we should also know, after all, you are to learn the SSM god

<! MyBatis framework --> <! - configure the connection pool - > < bean id = "dataSource" class = "boPooledDataSource com.mchange.v2.c3p0.Com" > < property name = "driverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql:///ssm"/> <property name="user" value="root"/> <property name="password" value="root"/> </bean>Copy the code

2. Configure the SqlSessionFactory factory in applicationContext. XML

Before the factory is configured, when we use Test, we need to create the factory first, because the factory can create SqlSession for us, and then we can use SqlSession to get proxy object. Now we configure the SqlSessionFactory factory directly in applicationContext.xml. This is equivalent to having the factory in the IOC container and creating SqlSession and retrieving proxy objects from SqlSession. There is no need to create the factory for every test.

<! - configuration SqlSessionFactory factory - > < bean id = "sqlSessonFactory" class = "org. Mybatis. Spring. SqlSessionFactoryBean" > < property name="dataSource" ref="dataSource"/> </bean>Copy the code

3. In ApplicationContext. XML, configure the package where the IAccountdao interface resides

We need to configure the package where the IAccountdao interface resides and tell SqlSession to proxy the agent in the package where the interface resides, so that it can be stored in the IOC container

<! - configuration IAccountdao interfaces are package - > < bean id = "mapperScanner" class = "org. Mybatis. Spring. Mapper. MapperScannerConfigurer" > < property name="basePackage" value="com.gx.dao"/> </bean>Copy the code

4. Summarize the three configurations above

The following is an example of how to transfer mybatis configuration (sqlmapconfig.xml) to Spring.

5. Improve the Service layer code

Write code in the AccountServiceImpl implementation class:

package com.gx.service.Impl;

import com.gx.dao.IAccountdao;
import com.gx.domain.Account;
import com.gx.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 IAccountdao iaccountdao;

    @Override
    public List<Account> findAll(a) {
        System.out.println("Service Layer: Query all accounts...");
        return iaccountdao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("Service business layer: Save accounts..."); }}Copy the code

6. Improve the Controller layer code

package com.gx.controller;

import com.gx.domain.Account;
import com.gx.service.AccountService;
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 java.util.List;

@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/account/findAll")
    public String findAll(Model model){  // Store data, Model object
        System.out.println("Controller presentation layer: Query all accounts...");
        // Call the method of the service
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);
        return "list"; }}Copy the code

7. Improve the list.jsp page

Because you are using JSTL to display database data, the list.jsp page looks like this:

<%-- Created by IntelliJ IDEA. User: Bule Date: 2019/9/2 Time: 7:32 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html; charset=UTF-8" language="java" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> < HTML > <head> <title> title </title> </head> <body> <h2> Query all accounts </h2> <c:forEach items="${list}" var="account"> ${account.name} </c:forEach> </body> </html>Copy the code

8. Run tests

7. Spring integration mybatis framework configuration transactions (Spring declarative transaction management)

Session.mit (); session.mit (); session.mit (); session.mit (); session.mit (); We must configure Spring’s declarative transaction management!

1. Configure Spring Framework declarative transaction management in ApplicationContext.xml

If you’re not particularly impressed with some execution expressions or AOP, check out my article on the basics of Spring AOP and getting started with AOP development

<! Configure Spring Framework declarative transaction management --> <! - configuration transaction manager - > < 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 :advisor advice-ref="txAdvice" pointcut="execution(*) com.gx.service.Impl.*ServiceImpl.*(..) )"/> </aop:config>Copy the code

2. Improve the index.jsp page

<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title> title </title> </head> <body> <a href="account/findAll"> <h3> <form action="account/save" method="post"> name: <input type="text" name="name" /> < input type = "text" name = "money" / > < br / > < input type = "submit" value = "save" / > < br / > < / form > < / body > < / HTML >Copy the code

3. Improve the code of Service layer and Controller layer

Service layer: The saveAccount(Account) method in the Service is called in the AccountServiceImpl implementation class

 @Override
    public void saveAccount(Account account) {
        System.out.println("Service business layer: Save accounts...");
        iaccountdao.saveAccount(account);  // Call saveAccount(account) in the service
    }
Copy the code

Controller layer code: Add a save method to the AccountController class

    @RequestMapping("/account/save")
    public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
        accountService.saveAccount(account);
        response.sendRedirect(request.getContextPath()+"/account/findAll");
        return;
    }
Copy the code

4. Test run

8, source, source, source ~ important title three times

At the same time, attach the source code to you, after all, insist to see the end, is really not easy (

Considering the C coin problem, has been shared to Baidu network disk, what? Don’t have a web disk account? Out of the door turn right, autumn famous mountain duel…

Link: pan.baidu.com/s/1lYtogVNB… Extraction code: HTOV

Welcome to pay attention to my public number, discuss technology together, yearning for technology, the pursuit of technology…