Spring+SprinMVC+MyBatis注解方式简易模板

这篇具有很好参考价值的文章主要介绍了Spring+SprinMVC+MyBatis注解方式简易模板。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Spring+SprinMVC+MyBatis注解方式简易模板代码Demo GitHub访问 ssm-tpl-anno

一、数据准备

创建数据库test,执行下方SQL创建表ssm-tpl-cfg

/*
 Navicat Premium Data Transfer

 Source Server         : 127.0.0.1
 Source Server Type    : MySQL
 Source Server Version : 80030
 Source Host           : 127.0.0.1:3306
 Source Schema         : test

 Target Server Type    : MySQL
 Target Server Version : 80030
 File Encoding         : 65001

 Date: 17/10/2022 00:52:07
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for ssm-tpl-cfg
-- ----------------------------
DROP TABLE IF EXISTS `ssm-tpl-cfg`;
CREATE TABLE `ssm-tpl-cfg` (
  `id` bigint NOT NULL COMMENT '主键编号',
  `name` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '测试名称',
  PRIMARY KEY (`id`)
) COMMENT '初始SSM表结构数据' ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

-- ----------------------------
-- Records of ssm-tpl-cfg
-- ----------------------------
BEGIN;
INSERT INTO `ssm-tpl-cfg` (`id`, `name`) VALUES (2210162246100000, '左翰林');
INSERT INTO `ssm-tpl-cfg` (`id`, `name`) VALUES (2210162257100000, '刘卓神');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

二、代码实现

2.1 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.tpl.ssm.anno</groupId>
    <artifactId>ssm-tpl-anno</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <spring_version>5.1.18.RELEASE</spring_version>
        <jackson_version>2.9.7</jackson_version>
    </properties>

    <dependencies>
        <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-aop</artifactId>
            <version>${spring_version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring_version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</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-context-support</artifactId>
            <version>${spring_version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring_version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring_version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring_version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>${spring_version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</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-test</artifactId>
            <version>${spring_version}</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-annotation</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.15.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.15.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.15.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.7</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.36</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.7</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>annotations</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.25</version>
        </dependency>
    </dependencies>
</project>

2.2 Spring和Mybatis配置

package com.tpl.ssm.anno.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
 * Spring配置类
 *
 * <!-- 扫描service -->
 * <context:component-scan base-package="com.tpl.ssm.cfg.service"/>
 */
@ComponentScan(basePackages = {"com.tpl.ssm.anno.service"}, excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = org.springframework.stereotype.Controller.class)
})
@EnableTransactionManagement
@Configuration
public class SpringConfig {

    private static final Logger logger = LoggerFactory.getLogger(SpringConfig.class);

    /*
     * <!-- 配置数据库连接池 -->
     * <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
     *     <!-- 四大连接参数 -->
     *     <property name="driverClassName" value="${jdbc.driverClassName}"/>
     *     <property name="url" value="${jdbc.url}"/>
     *     <property name="username" value="${jdbc.username}"/>
     *     <property name="password" value="${jdbc.password}"/>
     *     <!-- 连接池配置信息 -->
     *     <property name="initialSize" value="${jdbc.initialSize}"/>
     *     <property name="minIdle" value="${jdbc.minIdle}"/>
     *     <property name="maxActive" value="${jdbc.maxActive}"/>
     *     <property name="maxWait" value="${jdbc.maxWait}"/>
     *     <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
     *     <property name="timeBetweenEvictionRunsMillis" value="60000"/>
     *     <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
     *     <property name="minEvictableIdleTimeMillis" value="300000" />
     *     <!-- Druid用来测试连接是否可用的SQL语句,默认值每种数据库都不相同-->
     *     <property name="validationQuery" value="SELECT 'x'" />
     *     <!-- 指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除. -->
     *     <property name="testWhileIdle" value="true" />
     *     <!-- 指明是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 -->
     *     <property name="testOnBorrow" value="false" />
     *     <!-- 指明是否在归还到池中前进行检验 -->
     *     <property name="testOnReturn" value="false" />
     *     <!-- 配置监控统计拦截的filters -->
     *     <property name="filters" value="wall,stat" />
     * </bean>
     */
    @Bean(name = "dataSource")
    public DruidDataSource druidDataSource() {
        // 基本属性 url、user、password
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/test");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");

        // 配置初始化大小、最小、最大
        druidDataSource.setInitialSize(10);
        druidDataSource.setMinIdle(10);
        druidDataSource.setMaxActive(50);

        // 配置获取连接等待超时的时间
        druidDataSource.setMaxWait(60000);
        // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        druidDataSource.setTimeBetweenEvictionRunsMillis(60000);

        // 配置一个连接在池中最小生存的时间,单位是毫秒
        druidDataSource.setMinEvictableIdleTimeMillis(300000);

        druidDataSource.setValidationQuery("SELECT 1");
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);

        // 打开PSCache,并且指定每个连接上PSCache的大小
        // 如果用Oracle,则把poolPreparedStatements配置为true,
        // mysql可以配置为false。
        druidDataSource.setPoolPreparedStatements(true);
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);

        // 配置监控统计拦截的filters
        try {
            druidDataSource.setFilters("wall,stat");
        } catch (SQLException e) {
            logger.error("配置监控统计拦截的filters error: ", e);
        }
        return druidDataSource;
    }

    /*
     * <!-- 配置sessionFactory -->
     * <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     *     <!-- 注入数据源 -->
     *     <property name="dataSource" ref="dataSource"/>
     *     <!-- mapper文件位置 -->
     *     <property name="mapperLocations" value="classpath:mapper/*DAO.xml"/>
     *     <!-- mybatis核心配置文件位置 -->
     *     <property name="configLocation" value="classpath:config/mybatis-config.xml"/>
     * </bean>
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setMapperLocations(resolveMapperLocations());
        sqlSessionFactory.setDataSource(druidDataSource());
        /*
         * <?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>
         *
         *     <!-- 配置信息 -->
         *     <settings>
         *         <!-- 映射下划线到驼峰命名 -->
         *         <setting name="mapUnderscoreToCamelCase" value="true"/>
         *         <!-- 配置开启二级缓存 -->
         *         <setting name="cacheEnabled" value="true"/>
         *         <!-- 开启控制台打印SQL -->
         *         <setting name="logImpl" value="STDOUT_LOGGING"/>
         *     </settings>
         *
         *     <!-- 别名 -->
         *     <typeAliases>
         *         <package name="com.tpl.ssm.cfg.entity"/>
         *     </typeAliases>
         * </configuration>
         */
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setMapUnderscoreToCamelCase(true);
        mybatisConfiguration.setCacheEnabled(true);
        mybatisConfiguration.setLogImpl(StdOutImpl.class);
        mybatisConfiguration.getTypeAliasRegistry().registerAliases("com.tpl.ssm.anno.entity");

        sqlSessionFactory.setConfiguration(mybatisConfiguration);
        return sqlSessionFactory;
    }

    // https://wenku.baidu.com/view/1b9ade1640323968011ca300a6c30c225901f0c2.html
    public Resource[] resolveMapperLocations() {
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath:mapper/*DAO.xml");
        List<Resource> resources = new ArrayList<>();
        for (String mapperLocation : mapperLocations) {
            Resource[] mappers = new Resource[0];
            try {
                mappers = resolver.getResources(mapperLocation);
            } catch (IOException e) {
                e.printStackTrace();
            }
            resources.addAll(Arrays.asList(mappers));
        }
        return resources.toArray(new Resource[0]);
    }

    /*
     * <!-- 配置扫描mapper生成代理对象 -->
     * <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     *     <property name="basePackage" value="com.tpl.ssm.cfg.dao"/>
     *     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
     * </bean>
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.tpl.ssm.anno.dao");
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return mapperScannerConfigurer;
    }

    /* 事务管理器配置
     * <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
     *     <property name="dataSource" ref="dataSourceProxy"/>
     * </bean>
     */
    @Bean(name = "transactionManager")
    public DataSourceTransactionManager transactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}

2.3 SpringMVC配置

package com.tpl.ssm.anno.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

/* 开启controller注解支持
 * 注意事项请参考:http://jinnianshilongnian.iteye.com/blog/1762632
 *
 * <context:component-scan base-package="com.tpl.ssm.cfg.controller"/>
 */
@ComponentScan(basePackages = {
        "com.tpl.ssm.anno.controller"
}, includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = org.springframework.stereotype.Controller.class),
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = org.springframework.web.bind.annotation.ControllerAdvice.class)
}, useDefaultFilters = false)
@EnableWebMvc
@Configuration
// <import resource="spring-mvc-xxx.xml"/>
// @Import(value = {SpringMvcXxxConfig.class})
public class SpringMVCConfig implements WebMvcConfigurer {

    /* <!-- 配置SpringMVC视图解析器 -->
     * <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     *     <property name="prefix" value="/pages/"/>
     *     <property name="suffix" value=".jsp"/>
     * </bean>
     */
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
        resolver.setPrefix("/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    /* <!-- 释放静态资源文件 -->
     * <mvc:resources mapping="/js/" location="/js/**"/>
     * <mvc:resources mapping="/css/" location="/css/**"/>
     * <mvc:resources mapping="/images/" location="/images/**"/>
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/").addResourceLocations("/js/**");
        registry.addResourceHandler("/css/").addResourceLocations("/css/**");
        registry.addResourceHandler("/images/").addResourceLocations("/images/**");
    }

    // 文件解析器
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        // maxUploadSizePerFile:单个文件大小限制(byte)
        // maxUploadSize:整个请求大小限制(byte)
        commonsMultipartResolver.setMaxUploadSizePerFile(10 * 1024 * 1024); // 10M
        commonsMultipartResolver.setMaxUploadSize(100 * 1024 * 1024); // 100M
        return commonsMultipartResolver;
    }

}

2.4 web.xml配置

package com.tpl.ssm.anno.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * Web应用启动入口
 * <p/>
 * <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 * xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 * xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
 * http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 * </web-app>
 */
public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // 父容器配置
        AnnotationConfigWebApplicationContext springCtx = new AnnotationConfigWebApplicationContext();
        springCtx.setDisplayName("ssm-tpl-anno"); // 部署应用的名称 <display-name>ssm-tpl-anno</display-name>

        /*
         * <!-- Spring配置文件开始  -->
         * <context-param>
         *     <param-name>contextConfigLocation</param-name>
         *     <param-value>
         *         classpath:spring-config.xml
         *     </param-value>
         * </context-param>
         * <listener>
         *     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
         * </listener>
         * <!-- Spring配置文件结束 -->
         */
        springCtx.register(SpringConfig.class);
        // 通过监听器加载配置信息
        servletContext.addListener(new ContextLoaderListener(springCtx));

        /* 可以使用RequestContextHolder.currentRequestAttributes() 获取到请求的attr
         * <listener>
         *     <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
         * </listener>
         */
        servletContext.addListener(org.springframework.web.context.request.RequestContextListener.class);

        // 子容器配置
        AnnotationConfigWebApplicationContext mvcCtx = new AnnotationConfigWebApplicationContext();
        /*
         * <!-- SpringMVC配置文件开始  -->
         * <servlet>
         *     <servlet-name>springMVC</servlet-name>
         *     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         *     <init-param>
         *         <param-name>contextConfigLocation</param-name>
         *         <param-value>classpath:spring-mvc.xml</param-value>
         *     </init-param>
         *     <load-on-startup>1</load-on-startup>
         *     <async-supported>true</async-supported>
         * </servlet>
         * <servlet-mapping>
         *     <servlet-name>springMVC</servlet-name>
         *     <url-pattern>/</url-pattern>
         * </servlet-mapping>
         * <!-- SpringMVC配置文件结束  -->
         */
        mvcCtx.register(SpringMVCConfig.class);
        ServletRegistration.Dynamic servlet = servletContext.addServlet(
                "DispatcherServlet",
                new DispatcherServlet(mvcCtx));
        servlet.setLoadOnStartup(1);
        servlet.setAsyncSupported(true);
        servlet.addMapping("/");

        /*
         * <!-- 设置servlet编码开始 -->
         * <filter>
         *     <filter-name>CharacterEncodingFilter</filter-name>
         *     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
         *     <async-supported>true</async-supported>
         *     <init-param>
         *         <param-name>encoding</param-name>
         *         <param-value>UTF-8</param-value>
         *     </init-param>
         *     <init-param>
         *         <param-name>forceEncoding</param-name>
         *         <param-value>true</param-value>
         *     </init-param>
         * </filter>
         * <filter-mapping>
         *     <filter-name>CharacterEncodingFilter</filter-name>
         *     <url-pattern>/*</url-pattern>
         * </filter-mapping>
         * <!-- 设置servlet编码结束 -->
         */
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter(
                "CharacterEncodingFilter",
                new CharacterEncodingFilter("UTF-8", true));
        encodingFilter.setAsyncSupported(true);
        encodingFilter.addMappingForUrlPatterns(null, false, "/*");
    }
}

2.5 Entity

package com.tpl.ssm.anno.entity;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 测试实体
 */
public class TestEntity {

    /**
     * 主键编号
     */
    private Long id;

    /**
     * 测试名称
     */
    private String name;

    private JSONObject flowImg;
    private String flowImgStr;


    /**
     * 扩展字段
     */
    @JsonIgnore
    @TableField(exist = false)
    private Map<String, Object> ext = new LinkedHashMap<>(5);

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Map<String, Object> getExt() {
        return ext;
    }

    public void setExt(Map<String, Object> ext) {
        this.ext = ext;
    }

    public JSONObject getFlowImg() {
        return flowImg;
    }

    public void setFlowImg(JSONObject flowImg) {
        this.flowImg = flowImg;
    }

    public String getFlowImgStr() {
        return flowImgStr;
    }

    public void setFlowImgStr(String flowImgStr) {
        this.flowImgStr = flowImgStr;
    }
}

2.6 Controller

package com.tpl.ssm.anno.controller;

import com.tpl.ssm.anno.entity.TestEntity;
import com.tpl.ssm.anno.service.TestService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * 1. Spring5.1.x -> jackson2.9.x
 * 2.The origin server did not find a current representation for the target resource
 * 原因是WEB-INF只能转发进去, 重定向是进不去的
 */
@Controller
@RequestMapping("/test")
public class TestController {

    private final TestService testService;

    public TestController(TestService testService) {
        this.testService = testService;
    }

    @GetMapping("/")
    public String listTests(TestEntity test, Model model) {
        List<TestEntity> tests = testService.listTests(test);
        model.addAttribute("tests", tests);
        return "test";
    }

    @PostMapping("/save")
    public String saveTest(@RequestBody TestEntity test) {
        testService.saveTest(test);
        return "redirect:/test/";
    }

    @PostMapping("/modify")
    public String modifyTest(TestEntity test) {
        testService.modifyTest(test);
        return "redirect:/test/";
    }

    @RequestMapping("/remove")
    public String removeTest(TestEntity test) {
        testService.removeTest(test);
        return "redirect:/test/";
    }

}

2.7 Service

package com.tpl.ssm.anno.service;

import com.tpl.ssm.anno.entity.TestEntity;

import java.util.List;

public interface TestService {

    /**
     * 测试集
     *
     * @param cond 查询条件
     * @return 测试集
     */
    public List<TestEntity> listTests(TestEntity cond);

    /**
     * 单一测试实体
     *
     * @param cond 查询条件
     * @return 测试实体
     */
    public TestEntity singleTest(TestEntity cond);

    /**
     * 新增测试记录
     *
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public boolean saveTest(TestEntity cond);

    /**
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public boolean modifyTest(TestEntity cond);

    /**
     * 删除一条测试记录
     *
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public boolean removeTest(TestEntity cond);

    /**
     * 删除多条测试记录
     *
     * @param testIds 测试实体主键集
     * @return 受影响的条数
     */
    public boolean removeTests(List<Long> testIds);

}
package com.tpl.ssm.anno.service.impl;

import com.tpl.ssm.anno.dao.TestDAO;
import com.tpl.ssm.anno.entity.TestEntity;
import com.tpl.ssm.anno.service.TestService;
import com.tpl.ssm.anno.util.MajorKeyUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TestServiceImpl implements TestService {

    private final TestDAO testDAO;

    public TestServiceImpl(TestDAO testDAO) {
        this.testDAO = testDAO;
    }

    @Override
    public List<TestEntity> listTests(TestEntity cond) {
        return testDAO.listTests(cond);
    }

    @Override
    public TestEntity singleTest(TestEntity cond) {
        return testDAO.singleTest(cond);
    }

    @Override
    public boolean saveTest(TestEntity cond) {
        cond.setId(MajorKeyUtil.idSeq());
        cond.setFlowImgStr(cond.getFlowImg().toString());
        return testDAO.insertTest(cond) > 0;
    }

    @Override
    public boolean modifyTest(TestEntity cond) {
        return testDAO.updateTest(cond) > 0;
    }

    @Override
    public boolean removeTest(TestEntity cond) {
        return testDAO.deleteTest(cond) > 0;
    }

    @Override
    public boolean removeTests(List<Long> testIds) {
        return testDAO.deleteTests(testIds) > 0;
    }
}

2.8 DAO

package com.tpl.ssm.anno.dao;

import com.tpl.ssm.anno.entity.TestEntity;

import java.util.List;

/**
 * 测试DAO
 * <p>
 * 1.查询测试记录列表 - listTests
 * 2.查询单个测试记录 - singleTest
 * 3.新增测试记录 - insertTest
 * 4.修改测试记录 - updateTest
 * 5.删除测试记录 - deleteTest
 * 6.根据主键集删除测试记录 - deleteTests
 */
public interface TestDAO {

    /**
     * 测试集
     *
     * @param cond 查询条件
     * @return 测试集
     */
    public List<TestEntity> listTests(TestEntity cond);

    /**
     * 单一测试实体
     *
     * @param cond 查询条件
     * @return 测试实体
     */
    public TestEntity singleTest(TestEntity cond);

    /**
     * 新增测试记录
     *
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public int insertTest(TestEntity cond);

    /**
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public int updateTest(TestEntity cond);

    /**
     * 删除一条测试记录
     *
     * @param cond 查询条件
     * @return 受影响的条数
     */
    public int deleteTest(TestEntity cond);

    /**
     * 删除多条测试记录
     *
     * @param testIds 测试实体主键集
     * @return 受影响的条数
     */
    public int deleteTests(List<Long> testIds);

}
<?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.tpl.ssm.anno.dao.TestDAO">

    <!-- 基础查询 sql 片段 -->
    <sql id="baseSelect">
        SELECT id, name
    </sql>

    <!-- 基础查询 where 片段 -->
    <sql id="baseWhere">
        <if test="id != null">
            AND id = #{id}
        </if>
        <if test="name != null and name != ''">
            AND name like CONCAT('%', #{name})
        </if>
    </sql>

    <!-- 查询测试记录列表 -->
    <select id="listTests" parameterType="com.tpl.ssm.anno.entity.TestEntity" resultType="com.tpl.ssm.anno.entity.TestEntity">
        <include refid="baseSelect"/>
        FROM `ssm-tpl-cfg`
        WHERE
        1 = 1
        <include refid="baseWhere"/>
    </select>

    <!-- 查询单个测试记录 -->
    <select id="singleTest" parameterType="com.tpl.ssm.anno.entity.TestEntity" resultType="com.tpl.ssm.anno.entity.TestEntity">
        <include refid="baseSelect"/>
        FROM `ssm-tpl-cfg`
        WHERE
        1 = 1
        <include refid="baseWhere"/>
        limit 1
    </select>

    <!-- 新增测试记录 -->
    <insert id="insertTest" parameterType="com.tpl.ssm.anno.entity.TestEntity">
        INSERT INTO `ssm-tpl-cfg`(id, name, flow_img)
        VALUES (#{id}, #{name}, #{flowImgStr})
    </insert>

    <!-- 修改测试记录 -->
    <update id="updateTest" parameterType="com.tpl.ssm.anno.entity.TestEntity">
        UPDATE `ssm-tpl-cfg`
        SET
        <if test="name != null and name != ''">
            name = #{name}
        </if>
        WHERE id = #{id}
    </update>

    <!-- 删除测试记录 -->
    <delete id="deleteTest" parameterType="com.tpl.ssm.anno.entity.TestEntity">
        DELETE
        FROM `ssm-tpl-cfg`
        WHERE 1 = 1
        <include refid="baseWhere"/>
    </delete>

    <!-- 根据主键集删除测试记录 -->
    <delete id="deleteTests" parameterType="long">
        DELETE
        FROM `ssm-tpl-cfg`
        WHERE id in
        <foreach collection="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </delete>
</mapper>

2.9 webapps/pages/test.jsp

<%--
  Created by IntelliJ IDEA.
  User: wangfeihu
  Date: 2022/10/16
  Time: 18:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>CRUD TEST</title>
</head>
<body>
<table>
    <c:forEach items="${tests}" var="test">
        <tr>
            <td>${test.id}</td>
            <td>${test.name}</td>
            <td>
                <button onclick="let modifyForms = document.getElementsByName('modifyForm'); modifyForms.forEach(item => item.style.display = 'none'); document.getElementById('form${test.id}').style.display = 'inline'">修改</button>
                <button onclick="location.href='${pageContext.request.contextPath}/test/remove?id=${test.id}'">删除</button>
            </td>
            <td>
                <form id="form${test.id}" name="modifyForm" action="${pageContext.request.contextPath}/test/modify" method="post" style="display: none">
                    <input hidden name="id" value="${test.id}">
                    <input name="name" value="${test.name}">
                    <button type="submit">确认修改</button>
                </form>
            </td>
        </tr>
    </c:forEach>
</table>

<form action="${pageContext.request.contextPath}/test/save" method="post">
    <label>
        <input name="name" id="name" placeholder="请输入测试名称~">
    </label>
    <button type="submit">提交</button>
</form>
</body>
</html>

2.10 配置项目访问路径

Spring+SprinMVC+MyBatis注解方式简易模板,spring,mybatis,tomcat

三、访问测试

Spring+SprinMVC+MyBatis注解方式简易模板,spring,mybatis,tomcat

一个简单的基于注解的增删改查就实现了文章来源地址https://www.toymoban.com/news/detail-816576.html

到了这里,关于Spring+SprinMVC+MyBatis注解方式简易模板的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 浅谈 Spring IOC 和 DI 以及 Spring 整合 Mybatis 的十四 个注解

    控制 : 指对对象的创建权 反转: 对象的创建由程序员在类中主动创建变为由Spring自动创建 Spring方式:所有的对象都是由Spring框架提前创建出来,存储到一个容器中,servlet需要Service了,就向Spring要一个 技术的作用 : 通过底层反射原理来 解开对象之间的耦合 注解 @Compone

    2024年02月16日
    浏览(36)
  • SSM框架的学习与应用(Spring + Spring MVC + MyBatis)-Java EE企业级应用开发学习记录(第五天)MyBatis的注解开发

    ​ 昨天我们深入学习了 MyBatis多表之间的关联映射,了解掌握了一对一关联映射,一对多关联映射,嵌套查询方式以及嵌套结果方式,掌握了缓存机制的一级缓存,二级缓存等概念,也使用了代码进行复现理解 。但是都是基于XML配置文件的方式来实现的,现在我们要学习一下

    2024年02月11日
    浏览(59)
  • DAY02_Spring—第三方资源配置管理&Spring容器&Spring注解开发&Spring整合Mybatis和Junit

    说明:以管理DataSource连接池对象为例讲解第三方资源配置管理 问题导入 配置数据库连接参数时,注入驱动类名是用driverClassName还是driver? 1.1 管理Druid连接池 数据库准备 【第一步】添加Druid连接池依赖 注意:除了添加以上两个依赖之外,别忘了添加spring-context依赖。 【第二

    2024年02月13日
    浏览(82)
  • DAY02_Spring第三方资源配置管理&Spring容器&Spring注解开发&Spring整合Mybatis和Junit

    说明:以管理DataSource连接池对象为例讲解第三方资源配置管理 问题导入 配置数据库连接参数时,注入驱动类名是用driverClassName还是driver? 1.1 管理Druid连接池 数据库准备 【第一步】添加Druid连接池依赖 注意:除了添加以上两个依赖之外,别忘了添加spring-context依赖。 【第二

    2024年02月14日
    浏览(57)
  • 基于Spring注解 + MyBatis + Servlet 实现数据库交换的小小Demo

    配置数据库连接信息 db.properties 配置web.xml 配置logback.xml配置文件 配置applicationContext.xml 里面的bean 配置myBatis核心配置文件mybatis-config.xml 创建实体类对象User 创建LoginServlet响应前端的数据 创建UserService 接口 创建UserMapper接口 创建UserServiceImpl 接口实现类 按照这样的方式进行拼接

    2024年02月02日
    浏览(81)
  • MyBatis与Spring集成&常用注解以及AOP和PageHelper分页插件整合

    目录 前言 一、MyBatis与Spring整合的好处以及两者之间的关系 1.好处 2.关系  二、MyBatis和Spring集成 1.导入pom.xml 2.编写配置文件  3.利用mybatis逆向工程生成模型层代码 三、常用注解  四、AOP整合pageHelper分页插件 创建一个切面 测试 MyBatis是一个开源的持久层框架,而Spring是一个

    2024年02月07日
    浏览(57)
  • Spring整合Mybatis方式一 - 常规整合 - 注册映射器

    导包( mybatis-spring 、mysql-connector-java、mybatis、spring-webmvc等) 实体类 DAO层两个文件(接口、xml文件);Service层的接口 第一种:xml 第二种:annotation方式 点击查看代码 MapperFactoryBean注册映射器的最大问题,就是需要一个个注册所有的映射器,而实际上mybatis-spring提供了扫描包

    2024年03月27日
    浏览(42)
  • 深入解析Spring Boot集成MyBatis的多种方式

    🎉欢迎来到架构设计专栏~深入解析Spring Boot集成MyBatis的多种方式 ☆* o(≧▽≦)o *☆嗨~我是IT·陈寒🍹 ✨博客主页:IT·陈寒的博客 🎈该系列文章专栏:架构设计 📜其他专栏:Java学习路线 Java面试技巧 Java实战项目 AIGC人工智能 数据结构学习 🍹文章作者技术和水平有限,如

    2024年02月04日
    浏览(50)
  • Spring xml 方式整合mybatis 第三方框架

    MyBatis提供了mybatis-spring.jar专门用于两大框架的整合。 ①:第一步: 导入MyBatis整合Spring的相关坐标; ②:第二步: 编写Mapper和Mapper.xml ③:第三步: 配置SqlSessionFactoryBean和MapperScannerConfigurer ④:第四步: 编写测试代码

    2024年02月13日
    浏览(60)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包