文档章节

Java Web开发入门 - 第4章 Maven单元作业

抢小孩糖吃
 抢小孩糖吃
发布于 2016/08/26 23:46
字数 2352
阅读 688
收藏 0

#问题1 ##问题1描述:maven插件帮助文档 1(3分)如何查看一个maven插件的帮助文档,并举一个例子(可以将你查看到的帮助文档内容贴出来,可以只贴一部分)
##回答: ##插件配置

  • 插件配置元素
  • configuration配置 - 不同插件的配置项查询,查询模板如下
mvn help:describe -Dplugin=<plugin_name> -Dgoal=<goal> -Ddetail

查询插件目标:

 mvn help:describe -Dplugin=tomcat7

输出如下:

zhanpeng@GE70:~/Workspace/maven/restaurant/Restaurant$ mvn help:describe -Dplugin=tomcat7
Name: Apache Tomcat Maven Plugin :: Tomcat 7.x
Description: The Tomcat Maven Plugin provides goals to manipulate WAR
  projects within the Tomcat 7.x servlet container.
Group Id: org.apache.tomcat.maven
Artifact Id: tomcat7-maven-plugin
Version: 2.2
Goal Prefix: tomcat7

This plugin has 14 goals:

tomcat7:deploy
  Description: Deploy a WAR to Tomcat.

tomcat7:deploy-only
  Description: Deploy a WAR to Tomcat without forking the package lifecycle.

tomcat7:exec-war
  Description: Create a self executable jar file containing all necessary
    Apache Tomcat classes. This allows for using just java -jar mywebapp.jar to
    run your webapp without needing to install a Tomcat instance. More details
    here.

tomcat7:exec-war-only
  Description: Same as exec-war goal without forking the package lifecycle.

tomcat7:help
  Description: Display help information on tomcat7-maven-plugin.
    Call mvn tomcat7:help -Ddetail=true -Dgoal=<goal-name> to display parameter
    details.

tomcat7:redeploy
  Description: Redeploy a WAR in Tomcat. (Alias for the deploy goal with its
    update parameter set to true.)

tomcat7:redeploy-only
  Description: Redeploy a WAR in Tomcat without forking the package
    lifecycle. (Alias for the deploy-only goal with its update parameter set to
    true.)

tomcat7:run
  Description: Runs the current project as a dynamic web application using an
    embedded Tomcat server.

tomcat7:run-war
  Description: Runs the current project as a packaged web application using
    an embedded Tomcat server.

tomcat7:run-war-only
  Description: Same as run-war goal without forking the package cycle.

tomcat7:shutdown
  Description: Shuts down all possibly started embedded Tomcat servers. This
    will be automatically done through a shutdown hook or you may call this
    Mojo to shut them down explictly.
    
    By default the shutdown goal is not bound to any phase. For integration
    tests you might want to bind it to post-integration-test.

tomcat7:standalone-war
  Description: This Mojo will create an executable war file with embedded
    Tomcat that is also capable of being deployed elsewhere.

tomcat7:standalone-war-only
  Description: This Mojo will create an executable war file with embedded
    Tomcat that is also capable of being deployed elsewhere.

tomcat7:undeploy
  Description: Undeploy a WAR from Tomcat.

For more information, run 'mvn help:describe [...] -Ddetail'

查询目标对应配置:

mvn help:describe -Dplugin=tomcat7 -Dgoal=run -Ddetail=true

所查询到的内容如下:

zhanpeng@GE70:~/Workspace/maven/restaurant/Restaurant$ mvn help:describe -Dplugin=tomcat7 -Dgoal=run -Ddetail=true
tomcat7:run
  Description: Runs the current project as a dynamic web application using an
    embedded Tomcat server.
  Implementation: org.apache.tomcat.maven.plugin.tomcat7.run.RunMojo
  Language: java
  Before this mojo executes, it will call:
    Phase: 'process-classes'

  Available parameters:

    addContextWarDependencies (Default: false)
      User property: maven.tomcat.addContextWarDependencies
      Will create a tomcat context for each dependencies of war type with
      'scope' set to 'tomcat'. In other words, dependencies with:
         <type>war</type>
         <scope>tomcat</scope>
      To preserve backward compatibility it's false by default.
      Deprecated. use webapps instead

    additionalClasspathDirs
      Additional optional directories to add to the embedded tomcat classpath.

    additionalConfigFilesDir (Default: ${basedir}/src/main/tomcatconf)
      User property: maven.tomcat.additionalConfigFilesDir
      The directory contains additional configuration Files that copied in the
      Tomcat conf Directory.

    address
      User property: maven.tomcat.address
      this IP address will be used on all ports

    addWarDependenciesInClassloader (Default: true)
      User property: maven.tomcat.addWarDependenciesInClassloader
      will add /WEB-INF/lib/*.jar and /WEB-INF/classes from war dependencies in
      the webappclassloader

    ajpPort (Default: 0)
      User property: maven.tomcat.ajp.port
      The AJP port to run the Tomcat server on. By default it's 0 this means
      won't be started. The ajp connector will be started only for value > 0.
      Will be exposed as System props and session.executionProperties with key
      tomcat.maven.ajp.port

    ajpProtocol (Default: org.apache.coyote.ajp.AjpProtocol)
      User property: maven.tomcat.ajp.protocol
      The AJP protocol to run the Tomcat server on. By default it's ajp. NOTE
      The ajp connector will be started only if ajpPort > 0. possible values
      are:
      - org.apache.coyote.ajp.AjpProtocol - new blocking Java connector that
        supports an executor
      - org.apache.coyote.ajp.AjpAprProtocol - the APR/native connector.

    aliases
      configure aliases see Host Name aliases

    backgroundProcessorDelay (Default: -1)
      User property: maven.tomcat.backgroundProcessorDelay
      represents the delay in seconds between each classPathScanning change
      invocation

    classLoaderClass
      Class loader class to set.

    clientAuth (Default: false)
      User property: maven.tomcat.https.clientAuth
      enable client authentication for https (if configured) see
      http://tomcat.apache.org/tomcat-7.0-doc/config/http.html#SSL_Support_-_BIO_and_NIO

    configurationDir (Default: ${project.build.directory}/tomcat)
      The directory to create the Tomcat server configuration under.

    contextFile
      User property: maven.tomcat.contextFile
      The path of the Tomcat context XML file.
      
      Since release 2.0, the file is filtered as a maven resource so you can
      use interpolation tokens ${ }

    contextReloadable (Default: false)
      User property: maven.tomcat.contextReloadable
      Force context scanning if you don't use a context file with reloadable =
      'true'. The other way to use contextReloadable is to add attribute
      reloadable = 'true' in your context file.

    delegate (Default: true)
      User property: tomcat.delegate
      Set the 'follow standard delegation model' flag used to configure our
      ClassLoader.

    fork (Default: false)
      User property: maven.tomcat.fork
      Set this to true to allow Maven to continue to execute after invoking the
      run goal.

    hostName (Default: localhost)
      User property: maven.tomcat.hostName
      configure host name

    httpsPort (Default: 0)
      User property: maven.tomcat.httpsPort
      The https port to run the Tomcat server on. By default it's 0 this means
      won't be started. The https connector will be started only for value > 0.
      Will be exposed as System props and session.executionProperties with key
      tomcat.maven.https.port

    ignorePackaging (Default: false)
      User property: tomcat.ignorePackaging
      If set to true ignore if packaging of project is not 'war'.

    jarScanAllDirectories (Default: true)
      User property: maven.tomcat.jarScan.allDirectories
      In case a module in your reactors has some web-fragments they will be
      read. If you don't need that for performance reasons, you can deactivate
      it.

    keystoreFile
      Override the default keystoreFile for the HTTPS connector (if enabled)

    keystorePass
      Override the default keystorePass for the HTTPS connector (if enabled)

    keystoreType (Default: JKS)
      Override the type of keystore file to be used for the server certificate.
      If not specified, the default value is 'JKS'.

    path (Default: /${project.artifactId})
      Required: true
      User property: maven.tomcat.path
      The webapp context path to use for the web application being run. This
      must always start with a forward-slash ('/').

    pluginArtifacts (Default: ${plugin.artifacts})
      Required: true
      (no description available)

    port (Default: 8080)
      User property: maven.tomcat.port
      The port to run the Tomcat server on. Will be exposed as System props and
      session.executionProperties with key tomcat.maven.http.port

    propertiesPortFilePath
      User property: maven.tomcat.propertiesPortFilePath
      Will dump port in a properties file (see ports for property names). If
      empty no file generated

    protocol (Default: HTTP/1.1)
      User property: maven.tomcat.protocol
      The protocol to run the Tomcat server on. By default it's HTTP/1.1. See
      possible values HTTP Connector protocol attribute

    serverXml
      User property: maven.tomcat.serverXml
      server.xml to use Note if you use this you must configure in this file
      your webapp paths.

    skip (Default: false)
      User property: maven.tomcat.skip
      Skip execution

    staticContextDocbase
      User property: maven.tomcat.staticContextDocbase
      The static context docroot base fully qualified path if null static
      context won't be added

    staticContextPath (Default: /)
      User property: maven.tomcat.staticContextPath
      The static context

    systemProperties
      List of System properties to pass to the Tomcat Server.

    tomcatLoggingFile
      User property: maven.tomcat.tomcatLogging.file
      The path of the Tomcat logging configuration.

    tomcatUsers
      User property: maven.tomcat.tomcatUsers.file
      The path of the Tomcat users XML file.

    tomcatWebXml
      User property: maven.tomcat.webXml
      overriding the providing web.xml to run tomcat This override the global
      Tomcat web.xml located in $CATALINA_HOME/conf/

    trustManagerClassName
      (no description available)

    trustMaxCertLength
      (no description available)

    truststoreAlgorithm
      (no description available)

    truststoreFile
      (no description available)

    truststorePass
      (no description available)

    truststoreProvider
      (no description available)

    truststoreType
      (no description available)

    uriEncoding (Default: ISO-8859-1)
      User property: maven.tomcat.uriEncoding
      The character encoding to use for decoding URIs.

    useBodyEncodingForURI (Default: false)
      User property: maven.tomcat.useBodyEncodingForURI
      (no description available)

    useNaming (Default: true)
      User property: maven.tomcat.useNaming
      Enables or disables naming support for the embedded Tomcat server.
      
      Note: This setting is ignored if you provide a server.xml for your
      Tomcat. Instead please configure naming in the server.xml.

    useSeparateTomcatClassLoader (Default: false)
      User property: tomcat.useSeparateTomcatClassLoader
      if true a new classLoader separated from maven core will be created to
      start tomcat.

    useTestClasspath (Default: false)
      User property: maven.tomcat.useTestClasspath
      will use the test classpath rather than the compile one and will add test
      dependencies too

    warSourceDirectory (Default: ${basedir}/src/main/webapp)
      User property: tomcat.warSourceDirectory
      The web resources directory for the web application being run.

    webapps
      Collection of webapp artifacts to be deployed. Elements are <webapp> and
      contain usual GAVC plus contextPath and/or contextFile elements.

2(4分)关于tomcat7插件,在本章课程中仅仅演示了run这个目标。在实际应用中还会经常使用到deploy,undeploy这两个目标。

请查找资料,说明对于tomcat7这个插件来说,run与deploy这两个目标的区别与联系 ##回答: 我们可以在Apache Tomcat官网差找到tomcat的maven插件。 Apache Tomcat - Maven Plugin
###run目标: 可以在嵌入式的Tomcat运行war包。run的目标是给计算快速开发应用,不需要独立安装Tomcat。 ###deploy: 部署WAR项目:
deploy目标为把war包部署到Tomcat。

3(6分)对 Maven管理简单Web项目 一节中的项目Restaurant进行功能扩充,对每一次请求,都要再打印一次日志,用来记录用户的面条里面加的是什么,具体日志格式不限。要求使用log4j来实现日志管理,使用Maven来管理对log4j的依赖。本题目提交的答案为:修改后的NoodlesServelt.java 以及对pom.xml 文件的修改。(如果太长,在不影响答题效果的情况下,可以部分截断) ##回答: 首先下载《Maven管理简单项目源代码》。
去mvnrepository网站查看log4j的最高版本。通过查询我们发现,log4j具有1.x版本和2.x版本。编者建议使用log4j 2。Apache Log4j 2官网
通过log4j 2官网查询到maven配置如下:

<dependencies>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.6.2</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.6.2</version>
  </dependency>
</dependencies>

项目配置的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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.netease.restaurant</groupId>
    <artifactId>Restaurant</artifactId>
    <packaging>war</packaging>
    <version>1.0.0-SNAPSHOT</version>
    <name>Restaurant Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- Apache Log4j 2 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.6.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.6.2</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>Restaurant</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <uriEncoding>UTF-8</uriEncoding>
                    <finalName>Restaurant</finalName>
                    <server>tomcat</server>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

官方文档中给了代码示例如下:

import com.foo.Bar;
 
// Import log4j classes.
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
 
public class MyApp {
 
    // Define a static logger variable so that it references the
    // Logger instance named "MyApp".
    private static final Logger logger = LogManager.getLogger(MyApp.class);
 
    public static void main(final String... args) {
 
        // Set up a simple configuration that logs on the console.
 
        logger.trace("Entering application.");
        Bar bar = new Bar();
        if (!bar.doIt()) {
            logger.error("Didn't do it.");
        }
        logger.trace("Exiting application.");
    }
}

注意:编者碰到错误引用,LogManager导致LogManager.getLogger无法调用。重新查看import。修改就可以正确运行。
当运行后发现打印错误信息,需要我们处理配置文件:

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

根据错误内容描述,与题目要求命令行输出。logging打印错误时在console进行输出。则源代码如下:

package com.netease;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NoodlesServlet extends HttpServlet {

    private static final Logger logger = LogManager.getLogger(NoodlesServlet.class);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter writer = response.getWriter();
        String vegetable = request.getParameter("vegetable");
        if (vegetable == null) {

            // log4j 2 print what thing put in noodle
            logger.error(vegetable);

            vegetable = "Tomato";
        }
        else
        {
            logger.error(vegetable);
        }

        writer.println("<html><body>");
        writer.println("<h1> Noodles with " + vegetable + "</h1>"); 
        writer.println("</body></html>");
    }
}

打印内容:

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
23:43:54.094 [http-bio-8080-exec-6] ERROR com.netease.NoodlesServlet - Apple
23:43:54.903 [http-bio-8080-exec-7] ERROR com.netease.NoodlesServlet - Apple
23:43:55.103 [http-bio-8080-exec-8] ERROR com.netease.NoodlesServlet - Apple
23:43:55.280 [http-bio-8080-exec-9] ERROR com.netease.NoodlesServlet - Apple
23:43:55.474 [http-bio-8080-exec-10] ERROR com.netease.NoodlesServlet - Apple

© 著作权归作者所有

共有 人打赏支持
抢小孩糖吃

抢小孩糖吃

粉丝 70
博文 244
码字总数 235322
作品 0
东城
程序员
私信 提问
【Java学习路线】新手该如何一步步的学习 Java

新手该如何一步步的学习 Java? 如果真的想学Java,最好要循序渐进,有章有法的学习它! 今天小慕就不说一些学习方法和技巧了,直接来谈每个阶段要学习的内容。 首先,给大家分享一张以 企业...

Eddie_yang
2018/11/15
131
0
8个超实用的Java测试工具和框架

Java入门 如果你才刚开始接触Java世界,那么要做的第一件事情是,安装JDK——Java Development Kit(Java开发工具包),它自带有Java Runtime Environment(JRE)和JVM(Java运行时环境)。它...

拉偶有所依
2015/06/24
0
0
Java程序员必读书单,家族又添新成员

点击关注异步图书,置顶公众号 每天与你分享IT好书 技术干货 职场知识 参与文末话题讨论,每日赠送异步图书。 ——异步小编 有些革命出其不意地吸引了全世界的眼球。Twitter、Linux操作系统和...

异步社区
2018/05/09
0
0
[CentOS 7专用] Spring MVC/Maven 部署、入门与示例(纯菜鸟专用,一气呵成)

[CentOS 7专用] Spring MVC/Maven 部署、入门与示例(纯菜鸟专用,一气呵成) 前言 针对Spring MVC和Maven的入门教程,网上有较多参考资料。这里重点分享一下在Linux系统上,进行安装、部署和...

暗夜在火星
2018/11/02
0
0
JAVA区块链项目实战视频课程

课程介绍 全国首套,基于java的区块链实战教程。目的是让更多的java编程者了解区块链,掌握区块链开发。 1、区块链理论:以node.js例子区块链原理有深刻理解; 2、区块链java实战:深刻理解区...

小红牛
2018/09/14
0
0

没有更多内容

加载失败,请刷新页面

加载更多

OSChina 周六乱弹 —— 看见这花臂了么?赶紧叫大佬!

Osc乱弹歌单(2019)请戳(这里) 【今日歌曲】 @宇辰OSC :分享周华健的单曲《有没有一首歌会让你想起我》 《有没有一首歌会让你想起我》- 周华健 手机党少年们想听歌,请使劲儿戳(这里) ...

小小编辑
59分钟前
46
3
Confluence 6 升级中的一些常见问题

升级的时候遇到了问题了吗? 如果你想尝试重新进行升级的话,你需要首先重新恢复老的备份。不要尝试再次对 Confluence 进行升级或者在升级失败后重新启动老的 Confluence。 在升级过程中的一...

honeymoose
今天
2
0
C++随笔(四)Nuget打包

首先把自己编译好的包全部准备到一个文件夹 像这样 接下来新建一个文本文档,后缀名叫.nuspec 填写内容 <?xml version="1.0"?><package xmlns="http://schemas.microsoft.com/packaging/201......

Pulsar-V
今天
3
0
再谈使用开源软件搭建数据分析平台

三年前,我写了这篇博客使用开源软件快速搭建数据分析平台, 当时收到了许多的反馈,有50个点赞和300+的收藏。到现在我还能收到一些关于dataplay2的问题。在过去的三年,开源社区和新技术的发...

naughty
今天
16
0
Python3的日期和时间

python 中处理日期时间数据通常使用datetime和time库 因为这两个库中的一些功能有些重复,所以,首先我们来比较一下这两个库的区别,这可以帮助我们在适当的情况下时候合适的库。 在Python文...

编程老陆
今天
2
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部