First, create a Maven project and then dump the coordinates to create dependencies

<? 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>com.jd.ssm</groupId>
    <artifactId>ssm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
 
    <properties>
        <spring.version>5.02..RELEASE</spring.version>
        <slf4j.version>1.66.</slf4j.version>
        <log4j.version>1.212.</log4j.version>
        <shiro.version>1.23.</shiro.version>
        <mysql.version>5.16.</mysql.version>
        <mybatis.version>3.4. 5</mybatis.version> </properties> <dependencies> <! -- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.68.</version>
        </dependency>
 
        <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>junit</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>jstl</groupId>
            <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>
 
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.91.2.</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
 
 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok-maven-plugin</artifactId>
            <version>1.1610.. 0</version>
        </dependency>
 
    </dependencies>
 
    <build>
        <finalName>ssm</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                        <showWarnings>true</showWarnings>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
 
</project>
Copy the code

1. Write entity classes

@Data
public class Account {
    private Integer id;
    private String name;
    private Double money;
}
Copy the code

2. Write the business layer interface

public interface AccountService {
 
    /** * save the account */
    public void saveAccount(Account account);
 
    /** * query account */
    public List<Account> findAccount(a);
}
Copy the code

3. Write the persistence layer interface

public interface AccountMapper {
    public void saveAccount(Account account);
    public List<Account> findAccount(a);
}
Copy the code

4. Ensure that the Spring framework runs independently in web projects

Step 1: Write the Spring configuration file and import the constraints

<? 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- - configures the package to scan when the Spring container startspackage="com.jd"> <! - Set the packet scanning rule and do not scan packets@ControllerAnnotated JAVA classes, other classes to scan --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
 
</beans>
Copy the code

Step 2: Configure the business layer and persistence layer with annotations, implement the business layer interface class, and implement the persistence layer interface class

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    AccountMapperImpl accountMapperImpl;
 
    @Override
    public void saveAccount(Account account){
        accountMapperImpl.saveAccount(account);
    }
    @Override
    public List<Account> findAccount(a){
        accountMapperImpl.findAccount();
        return null; }}Copy the code
@Repository
public class AccountMapperImpl implements AccountMapper {
 
    @Override
    public void saveAccount(Account account){
        System.out.println("Saved account");
    }
    @Override
    public List<Account> findAccount(a){
        System.out.println("Account Query");
        return null; }}Copy the code

Step 3: Test whether Spring can run independently

In the applicationContext. XML file, add a bean to inject the AccountServiceImpl class into the Spring container

   <bean id="accountServiceImpl" class="com.jd.service.impl.AccountServiceImpl"/>
Copy the code
public class TestSpring {
    @Test
    public void test1(a){
        // Load the configuration file
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        // Get the object
        AccountService as = (AccountService) applicationContext.getBean("accountServiceImpl");
       // Call the methodas.findAccount(); }}Copy the code

5. Ensure SpringMVC runs independently in web projects

Step 1: Configure the core controller (DispatcherServlet) in 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"
         version="2.5"> <! - the core of the configuration for springMVC controllers - > < servlet > < servlet - name > springMVCDispatcherServlet < / servlet - name > < servlet -class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <! -- Configures initialization parameters for readingspringmvcConfig file --> <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param> <! - the configurationservletIs created when the application is loaded. The value can only be a non-0 positive integer, indicating the startup order.load-on-startup< / a > 1load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVCDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping> <! - the configurationspringMVCEncoding filter --> <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <! Set the value of the attribute in the filter --> <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF- 8 < /param-value>
        </init-param> <! -- Start filter --> <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter> <! Filter all requests --> <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern/ * < / >url-pattern>
    </filter-mapping>
 
    <welcome-file-list>
        <welcome-file>index.html</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>
Copy the code

Step 2: Write the SpringMVC configuration file, which mainly configures the view parser and automatically loads the configuration processor mapper and processor adapter

<? 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"> <! <context:component-scan base- - configures the package to scan when creating the Spring containerpackage="com.jd"> <! -- Specifies the packet scanning rule, which is used only for scanning@ControllerJAVA class for annotations --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <! Configure the view parser --> <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property> </bean> <! - automatic loading RequestMappingHandlerMapping mapper (processing) and RequestMappingHandlerAdapter adapter (processing), alternative annotation processing and adapter -- -- > <mvc:annotation-driven></mvc:annotation-driven> </beans>Copy the code

Step 3: Write Controller and JSP pages

@Controller
@RequestMapping("/account")
public class AcconutController {
 
    @RequestMapping("/findAccount")
    public ModelAndView findAccount(a){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("success");
        System.out.println("Account query performed");
        returnmv; }}Copy the code

Create an index.jsp page

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"% > <! DOCTYPE html PUBLIC"- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 
<head>
    <meta http-equiv="content-type" content="text/html"; charset="UTF-8"> <title> home </title> </head> <body> <a href="account/findAccount"</a> </body> </ HTML >Copy the code

Create a success.jsp page

<%@ page contentType="text/html; charset=UTF-8" language="java"% > < HTML > < head > < title > title < / title > < / head > < body > < h3 > success page < / h3 > < / body > < / HTML >Copy the code

The results

6. Integrate Spring and SpringMVC principles

Configure listeners in the web.xml file to configure the spring-provided listeners to load the container when the service is started. This listener can only load configuration files named applicationContext.xml in the WEB-INF directory

<! Configure the spring-provided listener to load the container at startup. This listener can only load the applicationContext. XML file in the WEB-INF directory --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> <! -- Manually specifyspringConfig file --> <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
Copy the code

Then inject the Service class into the Controller layer and call the methods in the Service directly

7. Ensure that Mybatis framework can run independently in Web project

Create sqlmapconfig.xml in the Resources directory

<? 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> <! -- Configure the environment --> <environmentsdefault="mysql">
        <environment id="mysql"> <! Use JDBC transaction processing --> <transactionManager type="JDBC"/ > <! --> <dataSource type="POOLED">
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <property name="url" value="jdbc:mysql:///ssm? characterEncoding=utf-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="123456"/> </dataSource> </environment> </environments> <! --> <mappers> <! --<package name="com.jd.dao"/ > -- > <! --<mapperclass="com.jd.dao.AccountMapper"/>-->
        <mapper resource="mapper/AccountMapper.xml"/>
    </mappers>
</configuration>
Copy the code
public class TestMybatis {
    /** * test query */
    @Test
    public void run(a) throws IOException {
 
        // 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
        AccountMapper dao=session.getMapper(AccountMapper.class);
        // Query all data
        List<Account> list=dao.findAccount();
 
        for(Account account : list){
            System.out.println(account);
        }
        // Close the resource
        session.close();
        in.close();
    }
 
 
    /** * Test save */
    @Test
    public void run1(a) throws IOException {
        Account account = new Account();
        account.setName("Zhang");
        account.setMoney(3333.00);
        // 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
        AccountMapper dao=session.getMapper(AccountMapper.class);
        // Save data
        dao.saveAccount(account);
        // Commit the transaction
        session.commit();
        // Close the resourcesession.close(); in.close(); }}Copy the code

Write the mapper file 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.jd.dao.AccountMapper"> <! --> <select id="findAccount" resultType="com.jd.domain.Account"> select id,name,money FROM account </select> <! --> <insert id="saveAccount" parameterType="com.jd.domain.Account"
            useGeneratedKeys="true" keyProperty="id" keyColumn="id">
        insert into account(name,money) values (#{name},#{money})
    </insert>
</mapper>
Copy the code

8. Integrate Spring with MyBatis

Mybatis configuration is loaded into the Spring container when the Spring container is started, and the Mybatis configuration is created.

Step 1: Configure the connection pool

<! --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssm? characterEncoding=utf-8"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>
Copy the code

Step 2: Configure the Session factory for Mybatis

Use the spring ioc container to create an SqlSession. If you have a session, you can create a proxy object, put the proxy in the IOC container, and put the service in the container. Then you can use dependency injection. Note that when writing SQL using mapper. XML, add the scan XML path to the SqlSessionFactory factory

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>
Copy the code

Step 2: Configure automatic scanning for all Mapper interfaces and files

<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         <property name="basePackage" value="com.jd.dao"/>
    </bean>
Copy the code

Step 3: Configure Spring transactions

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

Step 4: Test the integration results

9. Test the SSM integration results

The first step, write test JSP

<! <% @page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"% > <! DOCTYPE html PUBLIC"- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 
<head>
    <meta http-equiv="content-type" content="text/html"; charset="UTF-8"> <title> home </title> </head> <body> <a href="account/findAccount"> Query account </a> <form action="account/saveAccount" method="post"> Name :<input type="text" name="name"/><br> <input type="text" name="money"/><br>
     <input type="submit" value="Save"><br>
 </form>
</body>
</html>
Copy the code
<! <% @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> <h3> Query all users </h3> <c:forEach items="${list}" var="account">
         ${account.name}
    </c:forEach>
 
 
</body>
</html>
Copy the code

Step 2: Modify the methods in the controller

@Controller
@RequestMapping("/account")
public class AcconutController {
    @Autowired
    AccountServiceImpl accountServiceImpl;
 
    @RequestMapping("/findAccount")
    public String findAccount(Model model){
        System.out.println("Presentation layer, performed query account");
        List<Account> list=accountServiceImpl.findAccount();
        model.addAttribute("list",list);
        for(Account account:list){
            System.out.println(account);
        }
        return "list";
    }
    @RequestMapping("/saveAccount")
    public void saveAccount(Account account, HttpServletResponse response, HttpServletRequest request) throws IOException {
        accountServiceImpl.saveAccount(account);
        response.sendRedirect(request.getContextPath()+"/account/findAccount");
        return; }}Copy the code

The third step is to test the running results