Java Web開發入門 - 第4章 Maven單元做業

#問題1 ##問題1描述:maven插件幫助文檔 1(3分)如何查看一個maven插件的幫助文檔,並舉一個例子(能夠將你查看到的幫助文檔內容貼出來,能夠只貼一部分)
##回答: ##插件配置html

  • 插件配置元素
  • configuration配置 - 不一樣插件的配置項查詢,查詢模板以下
mvn help:describe -Dplugin=<plugin_name> -Dgoal=<goal> -Ddetail

查詢插件目標:java

mvn help:describe -Dplugin=tomcat7

輸出以下:react

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'

查詢目標對應配置:web

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

所查詢到的內容以下:apache

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這兩個目標。api

請查找資料,說明對於tomcat7這個插件來講,run與deploy這兩個目標的區別與聯繫 ##回答: 咱們能夠在Apache Tomcat官網差找到tomcat的maven插件。 Apache Tomcat - Maven Plugin
###run目標: 能夠在嵌入式的Tomcat運行war包。run的目標是給計算快速開發應用,不須要獨立安裝Tomcat。 ###deploy: 部署WAR項目:
deploy目標爲把war包部署到Tomcat。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配置以下:session

<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代碼以下:app

<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>

官方文檔中給了代碼示例以下:webapp

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
相關文章
相關標籤/搜索