python实现javaWeb自动建包

强颜欢笑 提交于 2020-03-03 06:24:09

建立工程,导包,配置Tomcat,全部自动化完成。
还在一个个复制配置文件?No。

from os import mkdir
from os import makedirs
from os import listdir
from os.path import join
from os.path import basename

def copyFile(src,dest):
    with open(src,'rb') as f1,open(dest,'wb') as f2:
        content = f1.read()
        f2.write(content)

def writeFile(path,content):# 写入指定文件的方法
    f = open(path,'w',encoding='utf-8')
    f.write(content)
    f.close()

proName = input('输入新工程名:')   # 新工程名
basePath = r''     # 工程所在的路径
libSrc = r'' # 40个jar包所在的路径
jQuerySrc = r'' # jquery文件路径,为了防止出错,这里用了1.12.4的版本
contextPath = input('输入web根路径:') # web根路径
tomcatName = 'Tomcat 8.5.42' # tomcat名称,用于部署设置
jdkVersion = '12.0.2' # 项目中的jdk版本名

# 文件夹路径
proPath = join(basePath,proName)
ideaPath = join(proPath,'.idea')
srcPath = join(proPath,'src')
shyPath = join(srcPath,'com/shy')
controllerPath = join(shyPath,'controller')
mapperPath = join(shyPath,'mapper')
mapperxmlPath = join(shyPath,'mapperxml')
pojoPath = join(shyPath,'pojo')
servicePath = join(shyPath,'service')
webPath = join(proPath,'web')
jsPath = join(webPath,'js')
cssPath = join(webPath,'css')
imagesPath = join(webPath,'images')
uploadPath = join(webPath,'upload')
webInfPath = join(webPath,'WEB-INF')
libPath = join(webInfPath,'lib')
artifactsPath = join(ideaPath,'artifacts')
librariesPath = join(ideaPath,'libraries')
# 文件内容和模板
indexContent = '''<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>测试</h1>
</body>
</html>'''
webContent = '''<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
         version="4.0">
<!--    配置Spring监听-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
<!--    配置全局编码-->
    <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>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
<!--    配置springmvc的核心控制器-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--        指定XML位置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>'''
imlContent = '''<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="FacetManager">
    <facet type="web" name="Web">
      <configuration>
        <descriptors>
          <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/web/WEB-INF/web.xml" />
        </descriptors>
        <webroots>
          <root url="file://$MODULE_DIR$/web" relative="/" />
        </webroots>
      </configuration>
    </facet>
  </component>
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR$">
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    </content>
    <orderEntry type="inheritedJdk" />
    <orderEntry type="sourceFolder" forTests="false" />
    <orderEntry type="library" name="springlib" level="project" />
  </component>
</module>'''
miscTemplate = '''<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectRootManager" version="2" languageLevel="JDK_12" default="true" project-jdk-name="${jdkVersion}" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>'''
modulesTemplate = '''<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/###.iml" filepath="$PROJECT_DIR$/###.iml" />
    </modules>
  </component>
</project>'''
warTemplate = '''<component name="ArtifactManager">
  <artifact type="exploded-war" name="###:war exploded">
    <output-path>$PROJECT_DIR$/out/artifacts/###_war_exploded</output-path>
    <root id="root">
      <element id="javaee-facet-resources" facet="###/web/Web" />
      <element id="directory" name="WEB-INF">
        <element id="directory" name="classes">
          <element id="module-output" name="###" />
        </element>
      </element>
    </root>
  </artifact>
</component>'''
applicationContent = '''<?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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        <context:component-scan base-package="com.shy"/>

<!--    读取数据库配置文件-->
    <bean id="dbproperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:db.properties"/>
    </bean>

<!--    数据源的配置,采用的是dbcp连接池的方式-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
    </bean>

<!--    将核心工厂对象交给spring管理-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatisConfig.xml"/>
        <property name="mapperLocations" value="classpath:com/shy/mapperxml/*.xml"/>
    </bean>

<!--    将sqlSesion交给spring管理-->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

<!--    配置接口的扫描包-->
    <bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.shy.mapper"/>
    </bean>

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

    <!--声明事务管理器-->
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>'''
dbContent = '''driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///kh80?useUnicode=true&characterEncoding=utf8
user=root
password=root'''
log4jContent = '''### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=info, stdout'''
mybatisContent = '''<?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="logImpl" value="STDOUT_LOGGING"/>
        <setting name="cacheEnabled" value="true"/>
    </settings>
    
    <typeAliases>
        <package name="com.shy.pojo"/>
    </typeAliases>

    <plugins>
        <!--        com.github.pagehelper为PageHelper类所在包名-->
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql"/>
            <!--            该参数默认为false-->
            <!--            设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用-->
            <!--            和startPage中的pageNum效果一样-->
            <property name="offsetAsPageNum" value="true"/>
            <!--            该参数默认为false-->
            <!--            设置为true时,使用RowBounds分页会进行count查询-->
            <property name="rowBoundsWithCount" value="true"/>
            <!--            设置为true时,如果pageSize=0或者RowBounds.limit = 0 就会查询出全部的效果-->
            <!--            (相当于没有执行分页查询,但是返回结果任然是Page类型)-->
            <property name="pageSizeZero" value="true"/>
            <!--            3.3.0版本可用 - 分页参数合理化,默认false禁用-->
            <!--            启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页-->
            <!--            禁用合理化时,如果pageNum<1或者pageNum>pages会返回空数据-->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>

</configuration>'''
springmvcContent = '''<?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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--    启动springmvc的注解驱动-->
    <mvc:annotation-driven/>
<!--    springmvc扫描包-->
    <context:component-scan base-package="com.shy.controller"/>
    <!--    配置视图解析器-->
<!--    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!--        <property name="suffix" value=".html"/>-->
<!--    </bean>-->
<!--    配置文件上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>
</beans>'''
springlibContent = '''<component name="libraryTable">
  <library name="springlib">
    <CLASSES>
      <root url="file://$PROJECT_DIR$/web/WEB-INF/lib" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
    <jarDirectory url="file://$PROJECT_DIR$/web/WEB-INF/lib" recursive="false" />
  </library>
</component>'''
workspaceTemplate = '''<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectFrameBounds" extendedState="7">
    <option name="x" value="617" />
    <option name="y" value="3" />
    <option name="width" value="1096" />
    <option name="height" value="1056" />
  </component>
  <component name="PropertiesComponent">
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="aspect.path.notification.shown" value="true" />
    <property name="last_opened_file_path" value="$PROJECT_DIR$" />
  </component>
  <component name="RunManager">
    <configuration name="${proName}" type="#com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory" factoryName="Local" APPLICATION_SERVER_NAME="${tomcatName}" ALTERNATIVE_JRE_ENABLED="false">
      <option name="OPEN_IN_BROWSER_URL" value="http://localhost:8080${contextPath}/index.html" />
      <option name="UPDATE_ON_FRAME_DEACTIVATION" value="true" />
      <option name="UPDATE_CLASSES_ON_FRAME_DEACTIVATION" value="true" />
      <deployment>
        <artifact name="${proName}:war exploded">
          <settings>
            <option name="CONTEXT_PATH" value="${contextPath}" />
          </settings>
        </artifact>
      </deployment>
      <server-settings>
        <option name="BASE_DIRECTORY_NAME" value="'Unnamed_${proName}" />
      </server-settings>
      <predefined_log_file enabled="true" id="Tomcat" />
      <predefined_log_file enabled="true" id="Tomcat Catalina" />
      <predefined_log_file id="Tomcat Manager" />
      <predefined_log_file id="Tomcat Host Manager" />
      <predefined_log_file id="Tomcat Localhost Access" />
      <RunnerSettings RunnerId="Debug">
        <option name="DEBUG_PORT" value="57106" />
      </RunnerSettings>
      <ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Cover">
        <option name="USE_ENV_VARIABLES" value="true" />
        <STARTUP>
          <option name="USE_DEFAULT" value="true" />
          <option name="SCRIPT" value="" />
          <option name="VM_PARAMETERS" value="" />
          <option name="PROGRAM_PARAMETERS" value="" />
        </STARTUP>
        <SHUTDOWN>
          <option name="USE_DEFAULT" value="true" />
          <option name="SCRIPT" value="" />
          <option name="VM_PARAMETERS" value="" />
          <option name="PROGRAM_PARAMETERS" value="" />
        </SHUTDOWN>
      </ConfigurationWrapper>
      <ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Debug">
        <option name="USE_ENV_VARIABLES" value="true" />
        <STARTUP>
          <option name="USE_DEFAULT" value="true" />
          <option name="SCRIPT" value="" />
          <option name="VM_PARAMETERS" value="" />
          <option name="PROGRAM_PARAMETERS" value="" />
        </STARTUP>
        <SHUTDOWN>
          <option name="USE_DEFAULT" value="true" />
          <option name="SCRIPT" value="" />
          <option name="VM_PARAMETERS" value="" />
          <option name="PROGRAM_PARAMETERS" value="" />
        </SHUTDOWN>
      </ConfigurationWrapper>
      <ConfigurationWrapper VM_VAR="JAVA_OPTS" RunnerId="Run">
        <option name="USE_ENV_VARIABLES" value="true" />
        <STARTUP>
          <option name="USE_DEFAULT" value="true" />
          <option name="SCRIPT" value="" />
          <option name="VM_PARAMETERS" value="" />
          <option name="PROGRAM_PARAMETERS" value="" />
        </STARTUP>
        <SHUTDOWN>
          <option name="USE_DEFAULT" value="true" />
          <option name="SCRIPT" value="" />
          <option name="VM_PARAMETERS" value="" />
          <option name="PROGRAM_PARAMETERS" value="" />
        </SHUTDOWN>
      </ConfigurationWrapper>
      <method v="2">
        <option name="Make" enabled="true" />
        <option name="BuildArtifacts" enabled="true">
          <artifact name="${proName}:war exploded" />
        </option>
      </method>
    </configuration>
  </component>
</project>'''
# 根据项目名替换模板生成新的内容
modulesContent = modulesTemplate.replace('###',proName)
warContent = warTemplate.replace('###',proName)
miscContent = miscTemplate.replace('${jdkVersion}',jdkVersion)
workspaceTemplate = workspaceTemplate.replace('${tomcatName}',tomcatName)
workspaceTemplate = workspaceTemplate.replace('${proName}',proName)
workspaceTemplate = workspaceTemplate.replace('${contextPath}',contextPath)
# 建立文件夹
mkdir(proPath)
mkdir(ideaPath)
mkdir(srcPath)
makedirs(shyPath)
mkdir(controllerPath)
mkdir(mapperPath)
mkdir(mapperxmlPath)
mkdir(pojoPath)
mkdir(servicePath)
mkdir(webPath)
mkdir(jsPath)
mkdir(cssPath)
mkdir(imagesPath)
mkdir(uploadPath)
mkdir(webInfPath)
mkdir(artifactsPath)
mkdir(librariesPath)
mkdir(libPath)
# 写入项目文件和配置文件
writeFile(join(webPath,'index.html'),indexContent)
writeFile(join(webInfPath,'web.xml'),webContent)
writeFile(join(proPath,proName+'.iml'),imlContent)
writeFile(join(ideaPath,'misc.xml'),miscContent)
writeFile(join(ideaPath,'modules.xml'),modulesContent)
writeFile(join(ideaPath,'workspace.xml'),workspaceTemplate)
writeFile(join(artifactsPath,proName+'_war_exploded.xml'),warContent)
writeFile(join(srcPath,'applicationContext.xml'),applicationContent)
writeFile(join(srcPath,'db.properties'),dbContent)
writeFile(join(srcPath,'log4j.properties'),log4jContent)
writeFile(join(srcPath,'mybatisConfig.xml'),mybatisContent)
writeFile(join(srcPath,'springmvc.xml'),springmvcContent)
writeFile(join(librariesPath,'springlib.xml'),springlibContent)
# 复制jQuery
copyFile(jQuerySrc,join(jsPath,basename(jQuerySrc)))
# 复制所有jar包
for i in listdir(libSrc):
    copyFile(join(libSrc,i),join(libPath,i))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!