配置文件生成器-秒杀SSM的xml整合

news/2024/6/17 19:06:07 标签: xml
xmlns="http://www.w3.org/2000/svg" style="display: none;">

xml_0">配置文件生成器-秒杀SSM的xml整合

在这里插入图片描述

思路: 通过简单的配置,直接生成对应配置文件。

maven坐标

xml">  <dependencies>
    <!--    配置文件生成    -->
    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.31</version>
    </dependency>
    <!--数据库驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.27</version>
    </dependency>

    <!--数据库连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.1</version>
    </dependency>
    <!--    jspapi-->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>
    <!--      jstl标签库  -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!--Mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>
    <!--mybatis、spring整合-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>

    <!--Springmvc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.12.RELEASE</version>
    </dependency>

    <!--    mvc、实体类序列化成json。默认jackson    -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.5</version>
    </dependency>
    <!--    lombok插件    -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.30</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.9.RELEASE</version>
    </dependency>
  </dependencies>
  <build>
    <!--  必选:生成ssm配置文件时,务必把以下内容注释  。项目运行过程mybatis如果报错,再打开、否则保留注释即可。 -->
    <!--        <resources>-->
    <!--            &lt;!&ndash;  静态资源过滤问题解决&ndash;&gt;-->
    <!--            <resource>-->
    <!--                <directory>src/main/java</directory>-->
    <!--                <includes>-->
    <!--                    <include>**/*.properties</include>-->
    <!--                    <include>**/*.xml</include>-->
    <!--                </includes>-->
    <!--                <filtering>false</filtering>-->
    <!--            </resource>-->
    <!--            <resource>-->
    <!--                <directory>src/main/resources</directory>-->
    <!--                <includes>-->
    <!--                    <include>**/*.properties</include>-->
    <!--                    <include>**/*.xml</include>-->
    <!--                </includes>-->
    <!--                <filtering>false</filtering>-->
    <!--            </resource>-->
    <!--        </resources>-->
  </build>

一、生成器ftl模板文件

模板文件,全部放在resource目录下的template文件夹中 。

  • mybatis-config-template.ftl 模板文件。
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>

    <!-- 设置别名 -->
    <typeAliases>
        <package name="${packageName}"/>
    </typeAliases>

    <!-- 其他的MyBatis配置 -->

</configuration>
  • springmvc-config-template.xml.ftl 模板文件
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">

    <!-- 配置Controller包扫描 -->
    <context:component-scan base-package="${basePackage}"/>
    
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="${viewResolverPrefix}"/>
        <property name="suffix" value="${viewResolverSuffix}"/>
    </bean>

    <!-- 开启SpringMVC的注解 -->
    <mvc:annotation-driven/>

</beans>
  • spring-mybatis-config-template.ftl 模板文件
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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 扫描dao和service包 -->
    <context:component-scan base-package="${basePackage}"/>

    <!-- 数据源配置,根据实际数据库连接信息修改 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${dbDriverClassName}"/>
        <property name="url" value="${dbUrl}"/>
        <property name="username" value="${dbUsername}"/>
        <property name="password" value="${dbPassword}"/>
    </bean>

    <!-- MyBatis的SqlSessionFactory配置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="${mapperLocations}"/>
    </bean>

    <!-- MyBatis的MapperScannerConfigurer配置 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="${daoBasePackage}"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <!-- 事务管理器配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

  • web-config-template.ftl 模板文件
xml"><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <!-- Spring的核心监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Spring的核心配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>${springMyBatisConfigPath}</param-value>
    </context-param>

    <!-- Spring MVC的DispatcherServlet -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>${springMvcConfigPath}</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 其他的Web配置 -->
    <!-- 添加UTF-8编码的全局过滤器 -->
    <filter>
        <filter-name>encodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

二、生成器代码

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SSMWebXmlGenerator {
    // SSM 全局参数
    private static final String BASE_PACKAGE = "com.itheima";
    private static final String OUTPUT_DIR = "src/main/resources/ssm";  // 配置文件生成目录

    // MyBatis 配置参数
    private static final String MYBATIS_OUTPUT_PATH = OUTPUT_DIR + "/mybatis-config.xml";  // 设置mybaits配置文件名字
    private static final String POJO_PACKAGE = BASE_PACKAGE + ".pojo"; // typeAliases  设置别名参数

    // Spring MVC 配置参数
    private static final String SPRING_MVC_OUTPUT_PATH = OUTPUT_DIR + "/springmvc-config.xml";  //springmvc配置文件名字
    private static final String CONTROLLER_PACKAGE = BASE_PACKAGE + ".controller";   // 配置controller包位置,以便可以扫描到里面的bean
    private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/jsp/";  //视图解析器前缀
    private static final String VIEW_RESOLVER_SUFFIX = ".jsp";//视图解析器后缀

    // Spring 配置参数
    private static final String SPRING_OUTPUT_PATH = OUTPUT_DIR + "/spring-mybatis-config.xml";  //spring配置文件名字
    private static final String DAO_PACKAGE = BASE_PACKAGE + ".dao";  // dao层的全包名
    private static final String SERVICE_PACKAGE = BASE_PACKAGE + ".service";  //service层的全包名
    private static final String DB_DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver"; //mysql驱动,默认8.*
    private static final String DB_URL = "jdbc:mysql://localhost:3306/cnmsb";  //url
    private static final String DB_USERNAME = "root"; //账号
    private static final String DB_PASSWORD = "root"; // 密码
    private static final String MYBATIS_MAPPER_LOCATIONS = "classpath*:mapper/*.xml"; //配置mybatis中xml的位置

    // web.xml 配置参数
    private static final String WEB_XML_OUTPUT_PATH = "src/main/webapp/WEB-INF/web.xml";   //生成路径
    private static final String SPRING_MYBATIS_CONFIG_PATH = "classpath:ssm/spring-mybatis-config.xml";  //spring配置文件名
    private static final String SPRING_MVC_CONFIG_PATH = "classpath:ssm/springmvc-config.xml"; //springmvc文件名

    public static void main(String[] args) throws IOException, TemplateException {
        try {
            generateMyBatisConfig();
            generateSpringMVCConfig();
            generateSpringConfig();
            generateWebXml();
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            System.err.println("生成配置文件时出错:" + e.getMessage());
            System.out.println("请注意,生成配置文件时、请删除或注释pom文件中,build标签。会影响生成!!!");
        }
    }

    private static void generateMyBatisConfig() throws IOException, TemplateException {
        // 配置 FreeMarker
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
        configuration.setDefaultEncoding("UTF-8");
        // 加载 MyBatis 配置模板文件
        Template template = configuration.getTemplate("template/mybatis-config-template.ftl");

        Map<String, String> dataModel = new HashMap<>();
        // 设置 MyBatis 包名参数
        dataModel.put("packageName", POJO_PACKAGE);

        generateFile(MYBATIS_OUTPUT_PATH, template, dataModel);
    }

    private static void generateSpringMVCConfig() throws IOException, TemplateException {
        // 配置 FreeMarker
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
        configuration.setDefaultEncoding("UTF-8");
        // 加载 Spring MVC 配置模板文件
        Template template = configuration.getTemplate("template/springmvc-config-template.xml.ftl");

        Map<String, String> dataModel = new HashMap<>();
        // 设置 Spring MVC 包名参数和视图解析器参数
        dataModel.put("basePackage", CONTROLLER_PACKAGE);
        dataModel.put("viewResolverPrefix", VIEW_RESOLVER_PREFIX);
        dataModel.put("viewResolverSuffix", VIEW_RESOLVER_SUFFIX);

        generateFile(SPRING_MVC_OUTPUT_PATH, template, dataModel);
    }

    private static void generateSpringConfig() throws IOException, TemplateException {
        // 配置 FreeMarker
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
        configuration.setDefaultEncoding("UTF-8");
        // 加载 Spring 配置模板文件
        Template template = configuration.getTemplate("template/spring-mybatis-config-template.ftl");

        Map<String, String> dataModel = new HashMap<>();
        // 设置 Spring 包名参数和数据库连接参数
        dataModel.put("basePackage", DAO_PACKAGE + "," + SERVICE_PACKAGE);
        dataModel.put("dbDriverClassName", DB_DRIVER_CLASS_NAME);
        dataModel.put("dbUrl", DB_URL);
        dataModel.put("dbUsername", DB_USERNAME);
        dataModel.put("dbPassword", DB_PASSWORD);
        dataModel.put("mapperLocations", MYBATIS_MAPPER_LOCATIONS);
        dataModel.put("daoBasePackage", DAO_PACKAGE);

        generateFile(SPRING_OUTPUT_PATH, template, dataModel);
    }

    private static void generateWebXml() throws IOException, TemplateException {
        // 配置 FreeMarker
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
        configuration.setDefaultEncoding("UTF-8");
        // 加载 web.xml 配置模板文件
        Template template = configuration.getTemplate("template/web-config-template.ftl");

        Map<String, String> dataModel = new HashMap<>();
        // 设置 web.xml 配置参数,引用之前生成的配置文件路径
        dataModel.put("springMyBatisConfigPath", SPRING_MYBATIS_CONFIG_PATH);
        dataModel.put("springMvcConfigPath", SPRING_MVC_CONFIG_PATH);

        generateFile(WEB_XML_OUTPUT_PATH, template, dataModel);
    }

    private static Configuration createConfiguration() {
        // 创建 FreeMarker 配置
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
        configuration.setDefaultEncoding("UTF-8");
        return configuration;
    }

    private static void generateFile(String outputPath, Template template, Map<String, String> dataModel)
            throws IOException, TemplateException {
        // 检查父目录是否存在,如果不存在则创建
        File parentDir = new File(outputPath).getParentFile();
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 写入文件
        FileWriter writer = new FileWriter(new File(outputPath));
        template.process(dataModel, writer);
        writer.close();

        System.out.println("配置文件生成成功:" + outputPath);
    }
}

 class MyBatisConfigModel {
    private String package_name;

    // Getter 和 Setter 方法

    // 构造函数
    public MyBatisConfigModel(String packageName) {
        this.package_name = packageName;
    }
}

 class SpringMVCConfigModel {
    private String basePackage;
    private String viewResolverPrefix;
    private String viewResolverSuffix;

    // Getter 和 Setter 方法

    // 构造函数
    public SpringMVCConfigModel(String basePackage, String viewResolverPrefix, String viewResolverSuffix) {
        this.basePackage = basePackage;
        this.viewResolverPrefix = viewResolverPrefix;
        this.viewResolverSuffix = viewResolverSuffix;
    }
}

 class SpringMyBatisConfigModel {
    private String basePackage;
    private String dbDriverClassName;
    private String dbUrl;
    private String dbUsername;
    private String dbPassword;
    private String mapperLocations;
    private String daoBasePackage;

    // Getter 和 Setter 方法

    // 构造函数
    public SpringMyBatisConfigModel(String basePackage, String dbDriverClassName, String dbUrl, String dbUsername, String dbPassword, String mapperLocations, String daoBasePackage) {
        this.basePackage = basePackage;
        this.dbDriverClassName = dbDriverClassName;
        this.dbUrl = dbUrl;
        this.dbUsername = dbUsername;
        this.dbPassword = dbPassword;
        this.mapperLocations = mapperLocations;
        this.daoBasePackage = daoBasePackage;
    }
}


http://www.niftyadmin.cn/n/5069012.html

相关文章

golang gin——controller 模型绑定与参数校验

controller 模型绑定与参数校验 gin框架提供了多种方法可以将请求体的内容绑定到对应struct上&#xff0c;并且提供了一些预置的参数校验 绑定方法 根据数据源和类型的不同&#xff0c;gin提供了不同的绑定方法 Bind, shouldBind: 从form表单中去绑定对象BindJSON, shouldB…

Python数据攻略-数据连续变量常用10种处理方法

今天将探讨一个非常重要的主题:如何处理连续变量。在数据分析、机器学习和科学研究中,连续变量是一种常见的数据类型。但连续变量通常需要经过一定的处理,才能更好地用于模型训练或分析。 文章的目的是展示如何使用Python进行这些处理,使数据更适合分析或机器学习模型。这…

动态内存函数笔试题

题目四&#xff1a; 修改后 #include<string.h> void test() {char* str (char*)malloc(100);strcpy(str, "hello");if (str ! NULL){strcpy(str, "world");printf(str);}free(str);str NULL; } int main() {test();return 0; } 源代码 #inclu…

对深度学习的批评

对深度学习的主要批评是许多方法缺乏理论支撑。 大多数深度结构仅仅是梯度下降的某些变式。 尽管梯度下降法已经被充分地研究&#xff0c;但理论涉及的其他算法&#xff0c;例如对比分歧算法&#xff0c;并没有获得充分的研究&#xff0c;其收敛性等问题仍不明确。 深度学习…

洛谷题解 | P9712 「QFOI R1」贴贴

目录 题目描述输入格式输出格式样例 #1样例输入 #1样例输出 #1 样例 #2样例输入 #2样例输出 #2 样例 #3样例输入 #3样例输出 #3 提示题目思路AC代码 题目描述 小 R 是一个可爱的女孩子&#xff0c;她希望通过给洛谷题目写题解的方式跟出题人贴贴。 她发现&#xff0c;如果从题…

第八章 排序 五、快速排序

目录 一、算法思想 二、例子 三、代码实现 四、验证 五、算法效率分析 1、时间复杂度 ​编辑 2、空间复杂度 3、小结 4、优化思路 5、稳定性 六、总结 一、算法思想 首先&#xff0c;选取一个数作为序列的基准数&#xff0c;分别定义序列的第一个数和最后一个数为l…

php实战案例记录(16)php://input输入流

php://input是PHP中的一个特殊的输入流&#xff0c;它允许访问请求的原始数据。它主要用于处理非表单的POST请求&#xff0c;例如当请求的内容类型为application/json或application/xml时。使用php://input可以获取到POST请求中的原始数据&#xff0c;无论数据是什么格式。使用…

JMeter性能分析实战一:日常登录接口

负载测试 日常需求&#xff1a;负载测试&#xff01; 对于桥的负载测试&#xff1a;我给你20t的一排车辆&#xff0c;看你能不能撑得住20t&#xff01; 对于系统的负载测试&#xff1a; 逐步增加负载&#xff0c;便于问题的发现和定位&#xff0c;不要操之过急。逐步增加负载…