【Activiti学习之八】Spring整合Activiti

环境 

  JDK 1.8
  MySQL 5.6
  Tomcat 8
  idea
  activiti 5.22

activiti-explorer是官方提供的一个演示项目,可以使用页面管理Activiti流程。activiti-explorer是以war包的形式存的。这里整合Spring+Activiti Modeler。

一、资源文件准备
1、下载activiti-5.22.0.rar
官网下载比较慢,可以从这里下载:https://pan.baidu.com/s/1XVTammPbIrbzU1MK7TBFOA

2、解压activiti-5.22.0.rar


进入wars目录,解压activiti-explorer.war demo

我们需要以下文件:

(1)diagram-viewer、editor-app、modeler.html
(2)stencilset.json(原版的title、description描述都是英文,可以改成中文:传送门

二、搭建maven web工程
这里搭建传统应用:Spring + SpringMVC + Mybatis + Activiti
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.wjy</groupId>
  <artifactId>activiti</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>activiti Maven Webapp</name>
  <url>http://www.example.com</url>

  <properties>
    <spring.version>4.3.5.RELEASE</spring.version>
    <activiti.version>5.22.0</activiti.version>
    <batik.version>1.7</batik.version>
    <java.version>1.8</java.version>
    <jdbc.driver.groupId>mysql</jdbc.driver.groupId>
    <jdbc.driver.artifactId>mysql-connector-java</jdbc.driver.artifactId>
    <jdbc.driver.version>5.1.34</jdbc.driver.version>
  </properties>

  <dependencies>
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-engine</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-spring</artifactId>
      <version>${activiti.version}</version>
      <exclusions>
        <exclusion>
          <artifactId>commons-dbcp</artifactId>
          <groupId>commons-dbcp</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.5</version>
    </dependency>

    <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-bpmn-model</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-bpmn-converter</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-bpmn-layout</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-common-rest</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-crystalball</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-diagram-rest</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-explorer</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-image-generator</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-json-converter</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-modeler</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-simple-workflow</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <!--<dependency>
        <groupId>org.vaadin.addons</groupId>
        <artifactId>dcharts-widget</artifactId>
        <version>0.10.0</version>
    </dependency>-->
    <dependency>
      <groupId>org.activiti</groupId>
      <artifactId>activiti-process-validation</artifactId>
      <version>${activiti.version}</version>
    </dependency>
    <dependency>
      <groupId>com.vaadin</groupId>
      <artifactId>vaadin</artifactId>
      <version>6.8.8</version>
    </dependency>
    <dependency>
      <groupId>org.imgscalr</groupId>
      <artifactId>imgscalr-lib</artifactId>
      <version>4.2</version>
    </dependency>
    <dependency>
      <groupId>org.apache.geronimo.specs</groupId>
      <artifactId>geronimo-servlet_3.0_spec</artifactId>
      <version>1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>

    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.1</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>javax.annotation-api</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>


    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</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-tx</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-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- 使用SpringMVC需配置 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- 关系型数据库整合时需配置 如hibernate jpa等 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- mysql连接 -->
    <dependency>
      <groupId>${jdbc.driver.groupId}</groupId>
      <artifactId>${jdbc.driver.artifactId}</artifactId>
      <version>${jdbc.driver.version}</version>
    </dependency>

    <!-- c3p0数据源 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5-pre10</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.8.9</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.9</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.8.9</version>
    </dependency>
    <!-- aop -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.4</version>
    </dependency>

    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>org.json</artifactId>
      <version>chargebee-1.0</version>
    </dependency>

    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib-ext-spring</artifactId>
      <version>1.0.2</version>
    </dependency>

    <!-- java mail -->
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4</version>
    </dependency>

    <!-- slf4j -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.6.1</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>

    <!-- FastJson将Json转换Bean -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.46</version>
    </dependency>
    <!-- JSON解析 end -->

    <!-- Batik的包主要是用来解析html中的svg的内容 -->
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-transcoder</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-dom</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-bridge</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-css</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-anim</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-codec</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-ext</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-gvt</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-script</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-js</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-parser</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-svg-dom</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-svggen</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-util</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-xml</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-awt-util</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>batik-js</artifactId>
      <version>${batik.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.xmlgraphics</groupId>
      <artifactId>xmlgraphics-commons</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>xml-apis</groupId>
      <artifactId>xml-apis-ext</artifactId>
      <version>1.3.04</version>
    </dependency>
    <dependency>
      <groupId>xml-apis</groupId>
      <artifactId>xml-apis</artifactId>
      <version>1.3.04</version>
    </dependency>

  </dependencies>

  <build>
    <finalName>activiti</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>
View Code

2、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 version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <display-name>activiti</display-name>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/springContext.xml,
            classpath:spring/spring-*.xml
        </param-value>
    </context-param>
    <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/springContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <listener>
        <!-- Spring容器启动监听器 -->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置编码方式过滤器,注意一点:要配置在所有过滤器的前面 -->
    <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>

    <filter>
        <filter-name>EncoidingFilter</filter-name>
        <filter-class>com.wjy.util.EncoidingFilter</filter-class>

        <init-param>
            <param-name>Encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>

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


</web-app>
View Code

3、springContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 自动扫描包,实现支持注解的IOC -->
    <context:component-scan base-package="com.wjy.*">
        <!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
    </context:component-scan>
    <!-- 支持mvc注解驱动 -->
    <mvc:annotation-driven/>

    <!-- 静态资源文件,不会被Spring MVC拦截 -->
    <mvc:default-servlet-handler/>
    <mvc:resources location="/resources/" mapping="/resources/**"/>
    <!--<bean id="springContextHelper" class="com.wjy.util.ApplicationContextHandler"></bean>-->

    <!-- 视图页面配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <!--1 引入属性文件,在配置中占位使用,可以通过${属性名}获得属性文件中的内容 -->
    <context:property-placeholder location="classpath*:jdbc.properties"/>

    <!--2 配置一个Spring提供的数据源 :jdbc数据源,创建一个驱动管理数据源的bean -->
    <bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="jdbcTemplate" name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="jdbcDataSource"/>
    </bean>

    <!--5 声明式事务管理 -->
    <!--定义事物管理器,由spring管理事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="jdbcDataSource"></property>
    </bean>

    <!--支持注解驱动的事务管理,指定事务管理器 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

4、spring-activiti.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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">


    <!-- ==================== Activiti配置 start =================== -->
    <!-- 单例json对象 -->
    <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper"/>

    <bean id="jobExecutor" class="org.activiti.engine.impl.jobexecutor.DefaultJobExecutor">
        <property name="lockTimeInMillis" value="3600000"></property>
    </bean>

    <bean id="uuidGenerator" class="com.wjy.util.UUIDGenerator"/>

    <!-- activiti的processEngine配置 -->
    <bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
        <!--数据源和事务-->
        <property name="dataSource" ref="jdbcDataSource"/>
        <property name="transactionManager" ref="transactionManager"/>

        <!-- 自动创建表 首次执行可以设置true-->
        <!--<property name="databaseSchemaUpdate" value="false"/>-->

        <!-- 是否激活Activiti的任务调度 -->
        <property name="jobExecutorActivate" value="false"/>
        <property name="jobExecutor" ref="jobExecutor"></property>

        <property name="asyncExecutorEnabled" value="false" />
        <property name="asyncExecutorActivate" value="false" />

        <!-- 是否开启工作的数据日志 -->
        <!-- <property name="enableDatabaseEventLogging" value="true" /> -->
        <!--<property name="history" value="full"/>-->
        <property name="processDefinitionCacheLimit" value="10"/>

        <!-- mail -->
        <!-- <property name="mailServerHost" value="localhost"/>
        <property name="mailServerUsername" value="kafeitu"/>
        <property name="mailServerPassword" value="000000"/>
        <property name="mailServerPort" value="2025"/> -->

        <!-- UUID作为主键生成策略  -->
        <property name="idGenerator" ref="uuidGenerator" />

        <!-- 生成流程图的字体 -->
        <property name="activityFontName" value="宋体"/>
        <property name="labelFontName" value="宋体"/>

        <!-- 缓存支持
        <property name="processDefinitionCache">
            <bean class="me.kafeitu.demo.activiti.util.cache.DistributedCache" />
        </property>-->

        <!-- 自动部署 -->
        <!-- <property name="deploymentResources">
            <list>
                <value>classpath*:/deployments/*</value>
            </list>
        </property> -->

        <!-- 自定义表单字段类型 -->
        <!-- <property name="customFormTypes">
            <list>
                <bean class="me.kafeitu.demo.activiti.activiti.form.UsersFormType"/>
            </list>
        </property> -->
        <!--不创建identity表 -->
        <!--<property name="dbIdentityUsed" value="false"/>-->
    </bean>

    <!-- 加载activiti引擎processEngine -->
    <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean" destroy-method="destroy">
        <property name="processEngineConfiguration" ref="processEngineConfiguration"/>
    </bean>

    <!-- activiti的7大服务接口 -->
    <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/>
    <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/>
    <bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/>
    <bean id="formService" factory-bean="processEngine" factory-method="getFormService"/>
    <bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/>
    <bean id="managementService" factory-bean="processEngine" factory-method="getManagementService"/>
    <bean id="identityService" factory-bean="processEngine" factory-method="getIdentityService" />
    <!-- ==================== Activiti配置 end =================== -->
</beans>

6、jdbc.properties

#mysql jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/activitidb?useSSL=false&zeroDateTimeBehavior=round&useUnicode=yes&characterEncoding=UTF8
jdbc.username=root
jdbc.password=123456
View Code

7、log4j.properties

### set log levels ###
log4j.rootLogger = INFO , C , D , E

### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/demo.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/demo_error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
View Code

三、整合activiti-explorer

1、将diagram-viewer、editor-app、modeler.html拷贝到src/main/webapp下
2、将stencilset.json拷贝到/src/main/resources下

代码目录结构:

 

3、修改代码

(1)modeler.html

<div style="display: none" class="navbar navbar-fixed-top navbar-inverse" role="navigation" id="main-header">
        <div class="navbar-header">
            <a href="" ng-click="backToLanding()" class="navbar-brand"
               title="{{'GENERAL.MAIN-TITLE' | translate}}"><span
                    class="sr-only">{{'GENERAL.MAIN-TITLE' | translate}}</span></a>
        </div>
    </div>

这块代码用于展示流程设计器上面显示activit自带的logo,可以通过 style="display: none" 隐藏 ,也可以换成公司自己的logo。

2、修改editor-app/app-cfg.js

var ACTIVITI = ACTIVITI || {};
ACTIVITI.CONFIG = {
        'contextRoot' : '/activiti',
    };

修改上下文,改为应用的上下文即可。

3、修改editor-app/app.js

activitiModeler
  // Initialize routes
  .config(['$selectProvider', '$translateProvider', function ($selectProvider, $translateProvider) {

      // Override caret for bs-select directive
      angular.extend($selectProvider.defaults, {
          caretHtml: '&nbsp;<i class="icon icon-caret-down"></i>'
      });
        
        // Initialize angular-translate
        $translateProvider.useStaticFilesLoader({
            prefix: '/activiti/editor-app/i18n/',
            suffix: '.json'
        });

        $translateProvider.preferredLanguage('zh');

        // remember language
        $translateProvider.useCookieStorage();
        
  }])

上文标出的两个部分,这个是用于查询国际化文件的配置,prefix配置的是查询前缀,这里要加上应用上下文前缀,另外一个地方:$translateProvider.preferredLanguage('zh') 默认是en,改为zh:

查询的是:

4、editor-app/configuration/url-config.js

/*
 * Activiti Modeler component part of the Activiti project
 * Copyright 2005-2014 Alfresco Software, Ltd. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
var KISBPM = KISBPM || {};

KISBPM.URL = {

    getModel: function(modelId) {
        return ACTIVITI.CONFIG.contextRoot + '/model/' + modelId + '/json';
    },

    getStencilSet: function() {
        return ACTIVITI.CONFIG.contextRoot + '/editor/stencilset?version=' + Date.now();
    },

    putModel: function(modelId) {
        return ACTIVITI.CONFIG.contextRoot + '/model/' + modelId + '/save';
    }
};

这个文件是获取流程元数据json、获取流程设计器规范json、保存流程的URL地址设置,要根据你自己写的controller里的requestmapping来定,这里附上我的controller:

package com.wjy.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

@Controller
public class ActivitiModelController {

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

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ObjectMapper objectMapper;

    /** 
    * @Desc: 跳转到新增流程页面
    * @Param:  
    * @return:  
    * @Author: wangjy15
    * @Date: 2019/10/11 
    */ 
    @RequestMapping("/createModel")
    public void createModel(HttpServletRequest request, HttpServletResponse response) {
        try
        {
            String name = request.getParameter("name");
            String key = request.getParameter("key");
            String description = request.getParameter("description");
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));

            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));

            request.setAttribute("modelId", modelData.getId());

            response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    /**
    * @Desc: 获取流程元数据 转换为json返回
    * @Param:
    * @return:
    * @Author: wangjy15
    * @Date: 2019/10/11
    */
    @RequestMapping(value = { "/model/{modelId}/json" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET }, produces = { "application/json" })
    @ResponseBody
    public JSONObject getEditorJson(@PathVariable String modelId) {
        ObjectNode modelNode = null;

        Model model = this.repositoryService.getModel(modelId);
        if (model != null) {
            try {
                if (StringUtils.isNotEmpty(model.getMetaInfo())) {
                    modelNode = (ObjectNode) this.objectMapper.readTree(model.getMetaInfo());
                } else {
                    modelNode = this.objectMapper.createObjectNode();
                    modelNode.put("name", model.getName());
                }
                modelNode.put("modelId", model.getId());
                ObjectNode editorJsonNode = (ObjectNode) this.objectMapper.readTree(new String(this.repositoryService.getModelEditorSource(model.getId()), "utf-8"));
                modelNode.put("model", editorJsonNode);
            } catch (Exception e) {
                throw new ActivitiException("Error creating model JSON", e);
            }
        }
        JSONObject result = JSONObject.parseObject(modelNode.toString());
        return result;
    }

    /**
     * @Desc: 获取流程设计器json规范
     * @Param:
     * @return:
     * @Author: wangjy15
     * @Date: 2019/10/11
     */
    @RequestMapping(value = { "/editor/stencilset" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET }, produces = { "application/json;charset=utf-8" })
    @ResponseBody
    public String getStencilset(HttpServletRequest req, HttpServletResponse rsp) {
        InputStream stencilsetStream = super.getClass().getClassLoader().getResourceAsStream("stencilset.json");
        try {
            String str = IOUtils.toString(stencilsetStream, "UTF-8");
            return str;
        } catch (Exception e) {
            throw new ActivitiException("Error while loading stencil set", e);
        }
    }

    /** 
    * @Desc: 保存流程
    * @Param:  
    * @return:  
    * @Author: wangjy15
    * @Date: 2019/10/11 
    */ 
    @RequestMapping(value = { "/model/{modelId}/save" }, method = { org.springframework.web.bind.annotation.RequestMethod.PUT })
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public void saveModel(@PathVariable String modelId, @RequestBody MultiValueMap<String, String> values) {
        try {
            Model model = this.repositoryService.getModel(modelId);

            ObjectNode modelJson = (ObjectNode) this.objectMapper.readTree(model.getMetaInfo());

            modelJson.put("name", (String) values.getFirst("name"));
            modelJson.put("description", (String) values.getFirst("description"));
            model.setMetaInfo(modelJson.toString());
            model.setName((String) values.getFirst("name"));

            this.repositoryService.saveModel(model);
            //保存json
            logger.debug(values.getFirst("json_xml"));
            this.repositoryService.addModelEditorSource(model.getId(),values.getFirst("json_xml").getBytes("utf-8"));

            //保存svg
            logger.debug(values.getFirst("svg_xml"));
            InputStream svgStream = new ByteArrayInputStream(values.getFirst("svg_xml").getBytes("utf-8"));
            TranscoderInput input = new TranscoderInput(svgStream);

            PNGTranscoder transcoder = new PNGTranscoder();

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            TranscoderOutput output = new TranscoderOutput(outStream);

            transcoder.transcode(input, output);
            byte[] result = outStream.toByteArray();
            this.repositoryService.addModelEditorSourceExtra(model.getId(), result);
            outStream.close();
        }
        catch (Exception e)
        {
            throw new ActivitiException("Error saving model", e);
        }
    }
}

 

效果:

 

 

本文所搭应用activiti代码:传送门

参考:
activiti-explorer项目部署
Activiti介绍与官方demo使用(activiti-explorer)
Spring学习之整合Activiti(一)
Spring学习之整合Activiti(二)
Spring学习之整合Activiti(三)之Id生成
工作流Activiti异常积累

Spring boot整合activiti modeler 5.22

使用idea 配置运行 activiti-explorer 5.22.0版 maven工程 

posted @ 2019-10-10 11:06  cac2020  阅读(1738)  评论(0编辑  收藏  举报