SSM integration to realize the operation of adding, deleting, modifying and checking [nanny teaching]

preparation

Environmental preparation

  • IDEA
  • MySQL 5.7.31
  • Tomcat 8.5.64
  • Maven 3.6.3

This is my environment. Don't make a big difference in the version.

Database preparation

CREATE DATABASE `ssmtest`;

USE `ssmtest`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user`(
	`userid` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'user ID',
	`username` VARCHAR(100) NOT NULL COMMENT 'user name',
	`password` VARCHAR(100) NOT NULL COMMENT 'User password',
	`value` INT(10) NOT NULL DEFAULT 1 COMMENT 'Status, 1 normal',
	 KEY `userid`(`userid`)
	
) ENGINE=INNODB DEFAULT CHARSET=utf8;



INSERT INTO `user`(`userid`,`username`,`password`,`value`)VALUES
(1,'keafmd','666',1),
(2,'keafod','888',1);

Start working

Create a Maven project ssmtest with Web support




Effect of creation completion:

Add dependency

<properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!--Unified version management-->
    <spring.version>5.2.7.RELEASE</spring.version>
    <slf4j.version>1.7.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.49</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
</properties>

<dependencies>
  
  <!-- spring -->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.5</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>

  <!--Junit-->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>compile</scope>
  </dependency>

  <!--Database driven-->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
  </dependency>

  <!-- Database connection pool -->
  <dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.1</version>
    <type>jar</type>
    <scope>compile</scope>
  </dependency>

  <!--Servlet - JSP -->
  <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>

  <!--Mybatis-->
  <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.2</version>
  </dependency>

  <!-- log  -->
  <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>

</dependencies>

Complete POM xml

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.keafmd</groupId>
  <artifactId>ssmtest</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

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

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <!--Unified version management-->
    <spring.version>5.2.7.RELEASE</spring.version>
    <slf4j.version>1.7.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.49</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>
  </properties>

  <dependencies>

    <!-- spring -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.5</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>

    <!--Junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>

    <!--Database driven-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>

    <!-- Database connection pool -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.1</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>

    <!--Servlet - JSP -->
    <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>

    <!--Mybatis-->
    <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.2</version>
    </dependency>

    <!-- log  -->
    <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>

  </dependencies>

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

Create entity, dao, service and controller packages

Entity class writing

Add lombook


User:

package com.keafmd.entity;

import lombok.Data;

import java.io.Serializable;

/**
 * Keafmd
 *
 * @ClassName: User
 * @Description: User entity class
 * @author: Coax Conan
 * @Date: 2021-04-19 9:11
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Data
public class User implements Serializable {

    private Integer userId;
    private String userName;
    private String password;

}

Persistence layer interface writing

IUserDao :

package com.keafmd.dao;

import com.keafmd.entity.User;

import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: IUserDao
 * @Description: User dao interface
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:20
 * @Blog: https://keafmd.blog.csdn.net/
 */
public interface IUserDao {

    //Query all
    public List<User> findAll();

    //Save user
    public void saveUser(User user);
}

Business layer interface writing

IUserService:

package com.keafmd.service;

import com.keafmd.entity.User;

import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: IUserService
 * @Description: user Business layer interface
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:23
 * @Blog: https://keafmd.blog.csdn.net/
 */
public interface IUserService {

    //Query all
    public List<User> findAll();

    //Save user
    public void saveUser(User user);

}

Business layer implementation class writing

UserServiceImpl :

package com.keafmd.service.impl;

import com.keafmd.entity.User;
import com.keafmd.service.IUserService;

import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: UserService
 * @Description: user Business layer implementation class
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:25
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class UserServiceImpl implements IUserService {
    @Override
    public List<User> findAll() {
        System.out.println("user Business layer implementation class--findAll");
        return null;
    }

    @Override
    public void saveUser(User user) {
        System.out.println("user Business layer implementation class--saveUser");
    }
}

Presentation layer compilation

UserController :

package com.keafmd.controller;

/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description: user Control layer
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:28
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class UserController {
}

Integration steps

Ensure that the Spring framework runs independently in the web project

Step 1: write the spring configuration file and import the constraints

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

    <!-- Start annotation scanning. What to scan is service and dao The annotation of the layer should be ignored web Layer annotation, because web Layer let SpringMVC Framework to manage -->
    <context:component-scan base-package="com.keafmd">
        <!-- Configure annotations to ignore -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

Step 2: configure the business layer with annotations

Add @ Service("userService") to the UserServiceImpl method

package com.keafmd.service.impl;

import com.keafmd.entity.User;
import com.keafmd.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: UserService
 * @Description: user Business layer implementation class
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:25
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Service("userService")
public class UserServiceImpl implements IUserService {
    @Override
    public List<User> findAll() {
        System.out.println("user Business layer implementation class--findAll");
        return null;
    }

    @Override
    public void saveUser(User user) {
        System.out.println("user Business layer implementation class--saveUser");
    }
}

Step 3: import log4j Properties configuration file

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

Step 4: test whether spring can run independently

Test code:

package com.keafmd;

import com.keafmd.service.IUserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Keafmd
 *
 * @ClassName: TestSpring
 * @Description: Test whether spring can run independently
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:38
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class TestSpring {

    @Test
    public void test1(){
        //Load profile
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        //Get object
        IUserService userService = (IUserService)ac.getBean("userService");
        //Call method
        userService.findAll();

    }
}

Test effect:

Ensure that spring MVC runs independently in web projects

Step 1: write the spring MVC configuration file

springmvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns: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 scanning controller Notes, others are not scanned -->
    <context:component-scan base-package="com.keafmd">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- Configure view parser -->
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- JSP Directory where the file is located -->
        <property name="prefix" value="/WEB-INF/pages/"/>
        <!-- File suffix -->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- Filter static resources, set static resources not to filter -->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>

    <!-- Open pair SpringMVC Annotation support -->
    <mvc:annotation-driven/>

</beans>

Step 2: on the web Configure the core controller (DispatcherServlet) in XML

web.xml:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!-- Configure the front-end controller: the server must be loaded when starting, and it needs to be loaded springmvc.xml configuration file -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- Configure initialization parameters and load springmvc.xml configuration file -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- Start the server and 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 for solving Chinese garbled code-->
    <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>

Step 3: write Controller and jsp pages

UserController :

package com.keafmd.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description: user Control layer
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:28
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("Presentation layer--All users query");
        return "user_list";
    }
}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/4/19
  Time: 9:52
  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>

    <a href="user/findAll">Query all users</a>

</body>
</html>

user_list.jsp:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/4/19
  Time: 9:55
  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>

    <h1>Query all users</h1>

</body>
</html>

Step 4: deploy tomcat server






-Dfile.encoding=utf-8

Step 5: start the server and test


Effect after clicking:

Spring integrates the framework of spring MVC

Step 1: configure the listener to start the service and create the container

<!-- to configure spring Listener provided to load the container when starting the service.
	This listener can only load WEB-INF The name in the directory is applicationContext.xml Configuration file for -->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Manual assignment spring Profile location -->
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>

Complete web xml:

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- Configure the front-end controller: the server must be loaded when starting, and it needs to be loaded springmvc.xml configuration file -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- Configure initialization parameters and load springmvc.xml configuration file -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!-- Start the server and create the servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!-- to configure spring Listener provided to load the container when starting the service.
   This listener can only load WEB-INF The name in the directory is applicationContext.xml Configuration file for -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- Manual assignment spring Profile location -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>


  <!--Filter for solving Chinese garbled code-->
  <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>

Step 2: inject the service object into the controller and call the method of the service object to test

UserController :

package com.keafmd.controller;

import com.keafmd.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description: user Control layer
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:28
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;


    @RequestMapping("/findAll")
    public String findAll(){
        System.out.println("Presentation layer--Query all users");
        
        //Method of calling service
        userService.findAll();

        return "user_list";
    }
}

Restart Tomcat and click to query all users. The console output effect is as follows:

Ensure that MyBatis framework runs independently in web projects

Step 1: write sqlmapconfig. In the web project XML configuration file and write the core configuration file

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>
    <!-- Configure information for connecting to the database -->
    <properties resource="jdbcConfig.properties"></properties>
    <!-- to configure mybatis Environment -->
    <environments default="mysql">
        <environment id="mysql">
            <!-- Configure transaction management -->
            <transactionManager type="JDBC"></transactionManager>
            <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>

    <!-- Specify mapping file location -->
    <mappers>
        <!--<mapper class="com.keafmd.dao.IAccountDao"/>
        <mapper class="com.keafmd.dao.IUserDao"/>-->
        <package name="com.keafmd.dao"/>
    </mappers>
</configuration>

jdbcConfig.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmtest
jdbc.username=root
jdbc.password=18044229

Step 2: add annotation on the method of IUserDao interface and write SQL statement

IUserDao :

package com.keafmd.dao;

import com.keafmd.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: IUserDao
 * @Description: User dao interface
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:20
 * @Blog: https://keafmd.blog.csdn.net/
 */
public interface IUserDao {

    //Query all
    @Select("select * from user")
    public List<User> findAll();

    //Save user
    @Insert("insert into user(username,password) values(#{userName},#{password})")
    public void saveUser(User user);
}

Step 3: write test methods

TestMybatis :

package com.keafmd;

import com.keafmd.dao.IUserDao;
import com.keafmd.entity.User;
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.After;
import org.junit.Before;
import org.junit.Test;

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

/**
 * Keafmd
 *
 * @ClassName: TestMybatis
 * @Description:
 * @author: Coaxed Conan
 * @Date: 2021-04-19 10:20
 * @Blog: https://keafmd.blog.csdn.net/
 */
public class TestMybatis {
    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession session;
    private IUserDao userDao;

    @Before
    public void init() throws Exception{
        //Load profile
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //Create SqlSessionFactory object
        factory = new SqlSessionFactoryBuilder().build(in);
        //Create SqlSession object
        session = factory.openSession();
        //Get proxy object
        userDao = session.getMapper(IUserDao.class);
    }

    @After
    public void destory() throws Exception{
        session.commit();
        session.close();
        in.close();
    }

    /**
     * Query all
     */
    @Test
    public void run1(){
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }

    /**
     * Test save
     */
    @Test
    public void saveUser(){
        User user = new User();
        user.setUserName("Maori Kogoro");
        user.setPassword("999");
        userDao.saveUser(user);
    }


}

Test effect:


Spring integrates MyBatis framework

Configure the contents of the mybatis configuration file (SqlMapConfig.xml) into the spring configuration file, and clear the contents of the mybatis configuration file at the same time.

Step 1: put sqlmapconfig Configure the content in the XML configuration file to ApplicationContext XML configuration file

Add the following to ApplicationContext XML configuration file:

<!--Spring integration Mybatisl frame-->
<!-- to configure C3P0 Connection pool object for -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql:///ssmtest"/>
    <property name="user" value="root"/>
    <property name="password" value="18044229"/>
</bean>
<!-- to configure SqlSession Factory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
</bean>
<!-- Configure scan dao My bag -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.keafmd.dao"/>
</bean>

<!--SqlMapConfig.xml and jdbcConfig.properties It can be deleted-->

Add and configure the Spring framework declarative transaction management:

<!--to configure Spring Framework declarative transaction management-->
<!--Configure transaction manager-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>
<!-- Configure notifications for transactions -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        <tx:method name="*" isolation="DEFAULT"/>
    </tx:attributes>
</tx:advice>
<!-- to configure AOP enhance -->
<aop:config>
    <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.keafmd.service.impl.*.*(..))"/>-->
    <!-- Configure pointcut expressions -->
    <aop:pointcut expression="execution(* com.keafmd.service.impl.*.*(..))" id="pt1"/>
    <!-- Establish the relationship between notification and pointcut expression -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>

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

    <!-- Start annotation scanning. What to scan is service and dao The annotation of the layer should be ignored web Layer annotation, because web Layer let SpringMVC Framework to manage -->
    <context:component-scan base-package="com.keafmd">
        <!-- Configuration of annotations to ignore -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>


    <!--Spring integration Mybatisl frame-->
    <!-- to configure C3P0 Connection pool object for -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssmtest?characterEncoding=utf8"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!-- to configure SqlSession Factory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- Configure scan dao My bag -->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.keafmd.dao"/>
    </bean>

    <!--SqlMapConfig.xml and jdbcConfig.properties It can be deleted-->

    <!--to configure Spring Framework declarative transaction management-->
    <!--Configure transaction manager-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- Configure notifications for transactions -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>
    <!-- to configure AOP enhance -->
    <aop:config>
        <!--<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.keafmd.service.impl.*.*(..))"/>-->
        <!-- Configure pointcut expressions -->
        <aop:pointcut expression="execution(* com.keafmd.service.impl.*.*(..))" id="pt1"/>
        <!-- Establish the relationship between notification and pointcut expression -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>


</beans>

Step 3: add @ Repository annotation in IUserDao interface

package com.keafmd.dao;

import com.keafmd.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: IUserDao
 * @Description: User dao interface
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:20
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Repository
public interface IUserDao {

    //Query all
    @Select("select * from user")
    public List<User> findAll();

    //Save user
    @Insert("insert into user(username,password) values(#{userName},#{password})")
    public void saveUser(User user);
}

Step 4: inject dao object into UserServiceImpl

package com.keafmd.service.impl;

import com.keafmd.dao.IUserDao;
import com.keafmd.entity.User;
import com.keafmd.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: UserService
 * @Description: user Business layer implementation class
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:25
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Service("userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    IUserDao userDao;

    @Override
    public List<User> findAll() {
        System.out.println("user Business layer implementation class--findAll");
        return userDao.findAll();
    }

    @Override
    public void saveUser(User user) {
        System.out.println("user Business layer implementation class--saveUser");
        userDao.saveUser(user);
    }
}

Step 5: modify the UserController code

package com.keafmd.controller;

import com.keafmd.entity.User;
import com.keafmd.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description: user Control layer
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:28
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;


    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("Presentation layer--Query all users");

        //Method of calling service
        List<User> userList = userService.findAll();
        model.addAttribute("userList",userList);

        return "user_list";
    }

    @RequestMapping("/save")
    public void save(User user , HttpServletRequest request, HttpServletResponse response) throws IOException {
        userService.saveUser(user);
        response.sendRedirect(request.getContextPath()+"/user/findAll");
        return;

    }
}

Step 5: modify user_list.jsp code to display account information

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/4/19
  Time: 9:55
  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>
    <h1>Query all users</h1>

<%--    ${userList}--%>

    <c:forEach items="${userList}" var="user">
        ${user.userName}
        ${user.password}
    </c:forEach>

</body>
</html>

Step 6: test query

effect:

Step 7: Test save

Modify index Jsp code, add the code saved by the test:

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/4/19
  Time: 9:52
  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>

    <a href="user/findAll">Query all users</a>

    <h1>Test save</h1>
    <form action="user/save" method="post">
        Account Name:<input type="text" name="userName" /><br/>
        password:<input type="text" name="password" /><br/>
        <input type="submit" value="preservation">
    </form>

</body>
</html>

Modify the UserController code and add the save method:

package com.keafmd.controller;

import com.keafmd.entity.User;
import com.keafmd.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description: user Control layer
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:28
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;


    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("Presentation layer--Query all users");

        //Method of calling service
        List<User> userList = userService.findAll();
        model.addAttribute("userList",userList);

        return "user_list";
    }

    @RequestMapping("/save")
    public void save(User user , HttpServletRequest request, HttpServletResponse response) throws IOException {
        userService.saveUser(user);
        response.sendRedirect(request.getContextPath()+"/user/findAll");
        return;

    }
}

Test effect:

Addition, deletion, modification and query (separation of front and rear ends)

lookup

In actual development, the front and back ends are mostly separated, so we need to modify our presentation layer code and add jackson's dependency.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.11.0</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.11.0</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>2.11.0</version>
</dependency>

UserController:

package com.keafmd.controller;

import com.keafmd.common.CommonResult;
import com.keafmd.entity.User;
import com.keafmd.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * Keafmd
 *
 * @ClassName: UserController
 * @Description: user Control layer
 * @author: Coaxed Conan
 * @Date: 2021-04-19 9:28
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;


    // http://127.0.0.1:8080/ssmtest/user/findAll
    @RequestMapping("/findAll")
    @ResponseBody
    public List<User> findAll(){
        System.out.println("Presentation layer--Query all users");

        //Method of calling service
        List<User> userList = userService.findAll();
//        model.addAttribute("userList",userList);

//        return "user_list";

        return userList;
    }

    @RequestMapping("/save")
    public void save(User user , HttpServletRequest request, HttpServletResponse response) throws IOException {
        userService.saveUser(user);
        response.sendRedirect(request.getContextPath()+"/user/findAll");
        return;

    }
}

visit: http://127.0.0.1:8080/ssmtest/user/findAll

Front end vue project

We need to have relevant environment here. I won't elaborate here.

Create an empty vue item

Find a folder, enter the command line, and enter: vue create ssmtest

Close the code format verification tool

In the root directory of the project (the same level as package.json), add the name Vue. JSON config. JS files can be automatically loaded by Vue cli.

module.exports = {
    lintOnSave:false, //Close the code format verification tool
    devServer:{
        port: 80 //Modify boot port
    }
}

Install related tools

1. Installing Vue router

npm install vue-router

2. Installing the element UI plug-in

npm i element-ui -S

3. Install axios

npm install axios

directory structure

Write main js

Introduce various components here and write router.

import Vue from 'vue'
import App from './App.vue'

import router from '@/router'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);

Vue.config.productionTip = false

new Vue({

	render: h => h(App),
	router
}).$mount('#app')

Write app vue

Write < router View > < / router View > in div and use the routing control interface.

<template>
  <div id="app">

	<router-view></router-view>

  </div>
</template>

<script>
// import First from './components/First.vue'

export default {
  name: 'App',
  components: {
	// First
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Write index. In router folder js

Here, use router to configure various paths

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
// import A from '@/components/A'
// import B from '@/components/B'

export default new Router({
	mode: 'history',
	routes: [{
			path: '/',
			name: 'Index',
			component: () => import('@/views'),
			children: [{
					path: '/user',
					name: 'User',
					component: () => import('@/views/user')
				}
			]
		}
		// ,
		// {
		// 	path: '/user',
		// 	name: 'User',
		// 	component: () => import('@/views/user')
		// }
		// {
		//   path: '/aaa',
		//   name: 'A',
		//   component: A
		// },
		// {
		//   path: '/bbb',
		//   name: 'B',
		//   component: B
		// }
	]
})

Write the menu of the public part vue

Note: insert router into the El menu tag.

<template>

    <el-menu router >

        <el-submenu index="1">
            <template slot="title">
                <span>Administration</span>
            </template>
            <el-menu-item-group>
                <el-menu-item index="/user"> <i class="el-icon-location"></i>user management </el-menu-item>
                <!-- <el-menu-item index="/menu"> <i class="el-icon-location"></i>Menu management</el-menu-item> -->
            </el-menu-item-group>
        </el-submenu>

       <!-- <el-submenu index="2">
            <template slot="title">
                <span>ElementUI assembly</span>
            </template>
            <el-menu-item-group>
                <el-menu-item index="/table"> <i class="el-icon-location"></i>Table component</el-menu-item>
            </el-menu-item-group>
        </el-submenu> -->

    </el-menu>

</template>

<script>
    export default {
        name: 'Menu'
    }
</script>

<style>
</style>

Write index. Under views vue

<template>

	<el-container class="wrap">
		<el-header class="header">
			<el-row>
				<el-col :span="20">information system</el-col>
				<el-col :span="4">
					<el-dropdown>
						<span class="el-dropdown-link">
							keafmd<i class="el-icon-arrow-down el-icon--right"></i>
						</span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item command="Personal">Personal settings</el-dropdown-item>
							<el-dropdown-item command="Logout">sign out</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>


				</el-col>
			</el-row>

		</el-header>
		<el-container>
			<el-aside width="200px" class="aside">
				<Menu></Menu>
			</el-aside>
			<el-main>
				<!-- <User></User> -->
				<router-view></router-view>
			</el-main>
		</el-container>
	</el-container>

</template>

<script>
	// import User from './user/index.vue'
	import Menu from '@/components/menu'
	export default {
		name: 'Index',
		components: {
			Menu
			// User

		},
		data() {
			return {}
		},
		methods: {

		},
		created() {}
	}
</script>

<style scoped>
	.wrap {
		height: 100vh;
	}

	.header {
		border-bottom: 1px solid aqua;
	}

	.aside {
		border-right: 1px solid aqua;
	}
</style>

Write the index under user under views vue

<template>
	<div>

		<el-table :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
			style="width: 100%">
			<el-table-column label="userName" prop="userName">
			</el-table-column>
			<el-table-column label="Password" prop="password">
			</el-table-column>
			<el-table-column align="right">
				<template slot="header" slot-scope="scope">
					<el-input v-model="search" size="mini" placeholder="Enter keyword search" />
				</template>
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
					<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete
					</el-button>
				</template>
			</el-table-column>
		</el-table>



	</div>
</template>

<script>
	import axios from 'axios';
	axios.defaults.baseURL = 'http://127.0.0.1:8080/ssmtest';

	export default {
		name: 'User',
		components: {

		},
		data() {
			return {
				tableData: [],
				search: ''
			}
		},
		methods: {
			getData() {

				axios.get('/user/findAll')
					.then((res) => {
						this.tableData = res.data
					})
					.catch(function(error) {
						console.log(error);
					});

			},
			handleEdit(index, row) {
				console.log(index, row);
			},
			handleDelete(index, row) {
				console.log(index, row);
			}
		},
		created() {
			this.getData();
		}
	}
</script>

<style>
</style>

Effect display

Query effect:

After reading, if it helps you, thank you for your praise and support!
If you are a computer terminal, do you see the "one key three links" in the lower right corner? Yes, click it [HA HA]

come on.

make joint efforts!

Keafmd

Keywords: SSM

Added by unify34 on Sat, 19 Feb 2022 15:27:02 +0200