Tomcat热部署:Maven项目一键部署到Tomcat服务器 - 支持多环境

参考:Eclipse中的Maven项目一键部署到Tomcat服务器 - 支持多环境部署

命令

debug模式设置关联源码

eclipse --> 项目右键 --> Debug As --> Debug Configurations --> Source --> Add --> Java Project --> 选中当前项目

再以Debug As -->Maven build中的tomcat:run命令运行,如此断点debug后,可以关联到源码

debug模式运行tomcat插件

clean compile tomcat:run -Pdevelopment

打包及部署

打包研发环境

clean package -Pdevelopment

部署研发环境

clean package cargo:redeploy -Pdevelopment

打包测试环境

clean package -Ptest

部署测试环境

clean package cargo:redeploy -Ptest

Tomcat配置

需要在Tomcat配置目录conf下的tomcat-users.xml配置tomcat用户的角色和权限,下面的配置为我们tomcat-username这个用户配置了管理权限,可以向tomcat部署应用

<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users>
    <role rolename="manager-script"/>
    <role rolename="manager-jmx"/>
    <role rolename="manager-status"/>
    <role rolename="manager"/>
    <role rolename="manager-gui"/>
    <user username="tomcat" password="tomcat" roles="manager,manager-gui,manager-script,manager-jmx,manager-status"/>
</tomcat-users>

配置说明:
manager-gui:允许访问html接口(即URL路径为/manager/html/)
manager-script:允许访问纯文本接口(即URL路径为/manager/text/
)
manager-jmx:允许访问JMX代理接口(即URL路径为/manager/jmxproxy/)
manager-status:允许访问Tomcat只读状态页面(即URL路径为/manager/status/
)

从Tomcat Manager内部配置文件中可以得知,manager-gui、manager-script、manager-jmx均具备manager-status的权限,也就是说,manager-gui、manager-script、manager-jmx三种角色权限无需再额外添加manager-status权限,即可直接访问路径"/manager/status/*"。

项目配置

源码

https://github.com/chencye/demo

测试

点击【loback】按钮,将显示当前部署的env.name配置

http://localhost:8080/hotpublish

代码

src/main/resources

src/main/resources目录
: dev
    : conf-sys-dev.properties
    : logback.xml
    : spring-mvc.xml
    : spring.xml
: test
    : conf-sys-test.properties
    : logback.xml
    : spring-mvc.xml
    : spring.xml

配置文件内容
说明:这里的文件名字与文件中的配置项只是为了对不同环境一目了然而已,可根据实际情况命名

dev/conf-sys-dev.properties

env.name=dev

dev/logback.xml

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

<!-- scan: 当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。 -->
<!-- scanPeriod: 设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug: 当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="false" debug="false">

    <!-- 设置变量: 定义变量后,可以使“${}”来使用变量 -->
    <property name="LOG_HOME" value="D:/temp/logs/dev" />
    <property name="appName" value="logbackdemo" />

    <!-- 设置上下文名称 -->
    <!-- 每个logger都关联到logger上下文,默认上下文名称为“default”。但可以使用<contextName>设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。 -->
    <contextName>${appName}</contextName>

    <!-- <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /> -->

    <!-- appender:负责写日志的组件 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="rollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${LOG_HOME}/${appName}.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>${LOG_HOME}/${appName}-%d{yyyy-MM-dd}-%i.log.zip</FileNamePattern>
            <maxHistory>365</maxHistory>
            <TimeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <MaxFileSize>10MB</MaxFileSize>
            </TimeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 用来设置某一个包或者具体的某一个类的日志打印级别、以及指定<appender>。<loger>仅有一个name属性,一个可选的level和一个可选的addtivity属性。 -->
    <!-- name: 用来指定受此loger约束的某一个包或者具体的某一个类。 -->
    <!-- level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。如果未设置此属性,那么当前loger将会继承上级的级别。 -->
    <!-- addtivity:是否向上级loger传递打印信息。默认是true。 -->
    <logger name="com.chencye" level="INFO">
        <!-- 可以包含零个或多个<appender-ref>元素,标识这个appender将会添加到这个logger -->
        <appender-ref ref="rollingFile" />
    </logger>

    <logger name="org.springframework" level="warn" />
    <logger name="ch.qos.logback" level="warn" />

    <root level="info">
        <appender-ref ref="console" />
    </root>

</configuration>

dev/spring-mvc.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: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/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">

    <mvc:annotation-driven />

    <!-- 若要在controller中直接使用Value注解拿到值,需要spring-mvc.xml配置文件中再次加载配置文件(两个容器之因) -->
    <context:property-placeholder location="classpath*:conf-*.properties" />

    <context:component-scan base-package="com.chencye" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>

    <mvc:view-controller path="/" view-name="index" />

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

dev/spring.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
         http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath*:conf-*.properties" />

    <context:component-scan base-package="com.chencye">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    </context:component-scan>

</beans>

test/conf-sys-test.properties

env.name=test

test/logback.xml

除了如下代码,其它与dev/logback.xml相同

<property name="LOG_HOME" value="D:/temp/logs/test" />

test/spring-mvc.xml

与dev/spring-mvc.xml相同

test/spring.xml

与dev/spring.xml相同

src/main/java

LogbackController.java

package com.chencye.demo.hotpublish.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LogbackController {

    private final static Logger log = LoggerFactory.getLogger(LogbackController.class);

    @Value("${env.name}")
    private String envName;

    @RequestMapping("logback")
    public ModelAndView testLogback() {

        for (int i = 0; i < 1; i++) {
            log.debug("[debug] testLogback. current environment is {}", envName);
            log.info("[info] testLogback. current environment is {}", envName);
            log.warn("[warn] testLogback. current environment is {}", envName);
            log.error("[error] testLogback. current environment is {}", envName);
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("envName", envName);
        mv.setViewName("index");
        return mv;
    }
}

index.jsp

src/main/webapp/WEB-INF/views/index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test logback</title>
</head>
<body>
    <span>${envName}</span>
    <input type="button" value="test" onclick="location.href='logback'" />
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring.xml</param-value>
    </context-param>

    <!-- Spring IoC -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 防止中文乱码 -->
    <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>

    <!-- Spring MVC -->
    <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>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

pom.xml

<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.chencye.demo</groupId>
    <artifactId>hotpublish</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <repositories>
        <repository>
            <id>oschina</id>
            <name>oschina</name>
            <url>http://maven.oschina.net/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>oschina</id>
            <name>oschina</name>
            <url>http://maven.oschina.net/content/groups/public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <project.build.encoding>UTF-8</project.build.encoding>
        <java.version>1.7</java.version>
        <spring.version>3.2.13.RELEASE</spring.version>
    </properties>

    <dependencies>
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.7</version>
        </dependency>
        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</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-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- 测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!-- 配置文件 -->
    <profiles>
        <!-- 研发环境 -->
        <profile>
            <id>development</id>
            <properties>
                <profiles.active>dev</profiles.active>
                <!-- Tomcat7的部署url是manager/text Tomcat6没有/text -->
                <deploy.url>http://localhost:8080/manager/text</deploy.url>
            </properties>
        </profile>
        <!-- 测试环境 -->
        <profile>
            <id>test</id>
            <properties>
                <profiles.active>test</profiles.active>
                <deploy.url>http://localhost:8080/manager/text</deploy.url>
            </properties>
        </profile>
    </profiles>

    <build>
        <finalName>${project.artifactId}</finalName>
        <!-- 打包配置文件管理 -->
        <resources>

            <!-- 代码生成器配置文件过滤 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <excludes>
                    <exclude>**/generatorConfig.xml</exclude>
                </excludes>
                <filtering>true</filtering>
            </resource>

            <!-- 所有环境配置文件过滤 -->
            <resource>
                <directory>src/main/resources</directory>
                <excludes>
                    <exclude>test/*</exclude>
                    <exclude>dev/*</exclude>
                </excludes>
            </resource>

            <!-- 指定环境配置文件导入 -->
            <resource>
                <directory>src/main/resources/${profiles.active}</directory>
            </resource>
        </resources>

        <plugins>
            <!-- mvn compile -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>

            <!-- 跳过单元测试,若skip设置为false,则需要进行单元测试 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>

            <!-- mvn package -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
            </plugin>

            <!-- mvn tomcat:run -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <url>http://localhost:8080/manager/text</url>
                    <httpPort>8080</httpPort>
                    <uriEncoding>${project.build.encoding}</uriEncoding>
                    <useBodyEncodingForURI>true</useBodyEncodingForURI>
                </configuration>
            </plugin>

            <!-- mvn cargo:redeploy -->
            <plugin>
                <groupId>org.codehaus.cargo</groupId>
                <artifactId>cargo-maven2-plugin</artifactId>
                <version>1.1.3</version>
                <configuration>
                    <wait>true</wait>
                    <container>
                        <containerId>tomcat7x</containerId>
                        <type>remote</type>
                    </container>
                    <configuration>
                        <type>runtime</type>
                        <properties>
                            <cargo.remote.uri>${deploy.url}</cargo.remote.uri>
                            <cargo.remote.username>tomcat</cargo.remote.username>
                            <cargo.remote.password>tomcat</cargo.remote.password>
                        </properties>
                    </configuration>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
上一篇:IIS支持解析json


下一篇:基于iscroll.js实现下拉刷新和上拉加载特效