Maven 介绍

步骤 1 : 什么是Maven

Maven 是专门用于构建和管理Java相关项目的工具。

Maven是意第绪语,依地语(犹太人使用的国际语),表示专家的意思。

所以用Maven管理Java 项目,你就是专家了 -_-!

步骤 2 : Maven 主要用处一:相同的项目结构

使用Maven管理的Java 项目都有着相同的项目结构

  1. 有一个pom.xml 用于维护当前项目都用了哪些jar包
  2. 所有的java代码都放在 src/main/java 下面
  3. 所有的测试代码都放在src/test/java 下面

步骤 3 : Maven 主要用处二:统一维护jar包

比如说有3个Java 项目,这些项目都不是maven风格。那么这3个项目,就会各自维护一套jar包。 而其中有些jar包是相同的。

而maven风格的项目,首先把所有的jar包都放在"仓库“ 里,然后哪个项目需要用到这个jar包,只需要给出jar包的名称和版本号就行了。 这样jar包就实现了共享

如图所示,在pom.xml里,表示用到了mysql 的jar包,版本号是5.1.30。

那么仓库在哪里? 怎么建设呢? 在后续教程会讲到: 仓库

Maven 下载与配置

步骤 1 : 下载

下载区(点击进入)可以下载 apache-maven-3.5.0-bin.zip, 版本是3.5.0,当前是(2017.7.21)最新版本

官方最新版下载地址:http://maven.apache.org/download.cgi

步骤 2 : 配置环境变量

右键我的电脑-属性-高级系统设置-环境变量-系统变量-Path

步骤 3 : 检验版本

使用win+r, 然后输入cmd 打开命令行,输入如下命令
mvn -v

倘若出现如图所示的截图,即表示配置成功了

Maven 仓库

步骤 1 : 仓库概念

所谓的仓库就是用于存放项目需要的jar包的。
maven采用一个仓库,多个项目的方式,让多个项目共享一个仓库里的相同jar包。

步骤 2 : 仓库默认位置

打开
D:\software\apache-maven-3.5.0\conf\settings.xml

可以看到,在52行指定了仓库的位置是${user.home}/.m2/repository。
对应我的机器就是
C:\Users\X7TI.m2\repository

<?xml version="1.0" encoding="UTF-8"?> <!--Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements.  See the NOTICE filedistributed with this work for additional informationregarding copyright ownership.  The ASF licenses this fileto you under the Apache License, Version 2.0 (the"License"); you may not use this file except in compliancewith the License.  You may obtain a copy of the License at     http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,software distributed under the License is distributed on an"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYKIND, either express or implied.  See the License for thespecific language governing permissions and limitationsunder the License.--> <!-- | This is the configuration file for Maven. It can be specified at two levels: | |  1. User Level. This settings.xml file provides configuration for a single user, |                 and is normally provided in ${user.home}/.m2/settings.xml. | |                 NOTE: This location can be overridden with the CLI option: | |                 -s /path/to/user/settings.xml | |  2. Global Level. This settings.xml file provides configuration for all Maven |                 users on a machine (assuming they're all using the same Maven |                 installation). It's normally provided in |                 ${maven.conf}/settings.xml. | |                 NOTE: This location can be overridden with the CLI option: | |                 -gs /path/to/global/settings.xml | | The sections in this sample file are intended to give you a running start at | getting the most out of your Maven installation. Where appropriate, the default | values (values used when the setting is not specified) are provided. | |--><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">  <!-- localRepository   | The path to the local repository maven will use to store artifacts.   |   | Default: ${user.home}/.m2/repository  <localRepository>/path/to/local/repo</localRepository>  -->

。。。略

步骤 3 : 默认下载路径

maven 会默认从maven官方提供的服务器下载jar包。
而官方服务器在国外,因为大家都知道的原因,网速很慢,而且容易卡断。 为了便于快速下载相关jar包,可以使用国内maven 阿里云的下载地址:使用阿里云下载路径

步骤 4 : 使用阿里云下载路径

打开
D:\software\apache-maven-3.5.0\conf\settings.xml

修改在mirrors下新加一个阿里云的镜像地址:

<mirror><id>alimaven</id><mirrorOf>central</mirrorOf><name>aliyun maven</name><url>http://maven.aliyun.com/nexus/content/repositories/central/</url></mirror>

也可以直接复制粘贴即可,修改位置是160-165行

<?xml version="1.0" encoding="UTF-8"?> <!--Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements.  See the NOTICE filedistributed with this work for additional informationregarding copyright ownership.  The ASF licenses this fileto you under the Apache License, Version 2.0 (the"License"); you may not use this file except in compliancewith the License.  You may obtain a copy of the License at     http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,software distributed under the License is distributed on an"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYKIND, either express or implied.  See the License for thespecific language governing permissions and limitationsunder the License.--> <!-- | This is the configuration file for Maven. It can be specified at two levels: | |  1. User Level. This settings.xml file provides configuration for a single user, |                 and is normally provided in ${user.home}/.m2/settings.xml. | |                 NOTE: This location can be overridden with the CLI option: | |                 -s /path/to/user/settings.xml | |  2. Global Level. This settings.xml file provides configuration for all Maven |                 users on a machine (assuming they're all using the same Maven |                 installation). It's normally provided in |                 ${maven.conf}/settings.xml. | |                 NOTE: This location can be overridden with the CLI option: | |                 -gs /path/to/global/settings.xml | | The sections in this sample file are intended to give you a running start at | getting the most out of your Maven installation. Where appropriate, the default | values (values used when the setting is not specified) are provided. | |--><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">  <!-- localRepository   | The path to the local repository maven will use to store artifacts.   |   | Default: ${user.home}/.m2/repository     -->  <localRepository>d:/maven/repository</localRepository>   <!-- interactiveMode   | This will determine whether maven prompts you when it needs input. If set to false,   | maven will use a sensible default value, perhaps based on some other setting, for   | the parameter in question.   |   | Default: true  <interactiveMode>true</interactiveMode>  -->   <!-- offline   | Determines whether maven should attempt to connect to the network when executing a build.   | This will have an effect on artifact downloads, artifact deployment, and others.   |   | Default: false  <offline>false</offline>  -->   <!-- pluginGroups   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.   |-->  <pluginGroups><!-- pluginGroup     | Specifies a further group identifier to use for plugin lookup.<pluginGroup>com.your.plugins</pluginGroup>-->  </pluginGroups>   <!-- proxies   | This is a list of proxies which can be used on this machine to connect to the network.   | Unless otherwise specified (by system property or command-line switch), the first proxy   | specification in this list marked as active will be used.   |-->  <proxies><!-- proxy     | Specification for one proxy, to be used in connecting to the network. |<proxy>  <id>optional</id>  <active>true</active>  <protocol>http</protocol>  <username>proxyuser</username>  <password>proxypass</password>  <host>proxy.host.net</host>  <port>80</port>  <nonProxyHosts>local.net|some.host.com</nonProxyHosts></proxy>-->  </proxies>   <!-- servers   | This is a list of authentication profiles, keyed by the server-id used within the system.   | Authentication profiles can be used whenever maven must make a connection to a remote server.   |-->  <servers><!-- server     | Specifies the authentication information to use when connecting to a particular server, identified by     | a unique name within the system (referred to by the 'id' attribute below). | | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are     |       used together. |<server>  <id>deploymentRepo</id>  <username>repouser</username>  <password>repopwd</password></server>--> <!-- Another sample, using keys to authenticate.<server>  <id>siteServer</id>  <privateKey>/path/to/private/key</privateKey>  <passphrase>optional; leave empty if not used.</passphrase></server>-->  </servers>   <!-- mirrors   | This is a list of mirrors to be used in downloading artifacts from remote repositories.   |   | It works like this: a POM may declare a repository to use in resolving certain artifacts.   | However, this repository may have problems with heavy traffic at times, so people have mirrored   | it to several places.   |   | That repository definition will have a unique id, so we can create a mirror reference for that   | repository, to be used as an alternate download site. The mirror site will be the preferred   | server for that repository.   |-->  <mirrors><!-- mirror     | Specifies a repository mirror site to use instead of a given repository. The repository that     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors. |<mirror>  <id>mirrorId</id>  <mirrorOf>repositoryId</mirrorOf>  <name>Human Readable Name for this Mirror.</name>  <url>http://my.repository.com/repo/path</url></mirror> --><mirror><id>alimaven</id><mirrorOf>central</mirrorOf><name>aliyun maven</name><url>http://maven.aliyun.com/nexus/content/repositories/central/</url></mirror>    </mirrors>   <!-- profiles   | This is a list of profiles which can be activated in a variety of ways, and which can modify   | the build process. Profiles provided in the settings.xml are intended to provide local machine-   | specific paths and repository locations which allow the build to work in the local environment.   |   | For example, if you have an integration testing plugin - like cactus - that needs to know where   | your Tomcat instance is installed, you can provide a variable here such that the variable is   | dereferenced during the build process to configure the cactus plugin.   |   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles   | section of this document (settings.xml) - will be discussed later. Another way essentially   | relies on the detection of a system property, either matching a particular value for the property,   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.   | Finally, the list of active profiles can be specified directly from the command line.   |   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact   |       repositories, plugin repositories, and free-form properties to be used as configuration   |       variables for plugins in the POM.   |   |-->  <profiles><!-- profile     | Specifies a set of introductions to the build process, to be activated using one or more of the     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/> | or the command line, profiles have to have an ID that is unique. | | An encouraged best practice for profile identification is to use a consistent naming convention     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. | This will make it more intuitive to understand what the set of introduced profiles is attempting     | to accomplish, particularly when you only have a list of profile id's for debug. | | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.<profile>  <id>jdk-1.4</id>       <activation><jdk>1.4</jdk>  </activation>       <repositories><repository>  <id>jdk14</id>  <name>Repository for JDK 1.4 builds</name>  <url>http://www.myhost.com/maven/jdk14</url>  <layout>default</layout>  <snapshotPolicy>always</snapshotPolicy></repository>  </repositories></profile>--> <!-- | Here is another profile, activated by the system property 'target-env' with a value of 'dev', | which provides a specific path to the Tomcat instance. To use this, your plugin configuration     | might hypothetically look like: | | ... | <plugin> |   <groupId>org.myco.myplugins</groupId> |   <artifactId>myplugin</artifactId> | |   <configuration> |     <tomcatLocation>${tomcatPath}</tomcatLocation> |   </configuration> | </plugin> | ... | | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to     |       anything, you could just leave off the <value/> inside the activation-property. |<profile>  <id>env-dev</id>       <activation><property>  <name>target-env</name>  <value>dev</value></property>  </activation>       <properties><tomcatPath>/path/to/tomcat/instance</tomcatPath>  </properties></profile>-->  </profiles>   <!-- activeProfiles   | List of profiles that are active for all builds.   |  <activeProfiles><activeProfile>alwaysActiveProfile</activeProfile><activeProfile>anotherAlwaysActiveProfile</activeProfile>  </activeProfiles>  --></settings>

步骤 5 : 修改仓库位置
仓库默认位置 是 C:\Users\X7TI.m2\repository,放在C盘有一点不好,重装系统就都没有了。所以通常我会把仓库的位置修改为:
d:/maven/repository

配置文件的第55行,复制粘贴即可。

<?xml version="1.0" encoding="UTF-8"?> <!--Licensed to the Apache Software Foundation (ASF) under oneor more contributor license agreements.  See the NOTICE filedistributed with this work for additional informationregarding copyright ownership.  The ASF licenses this fileto you under the Apache License, Version 2.0 (the"License"); you may not use this file except in compliancewith the License.  You may obtain a copy of the License at     http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,software distributed under the License is distributed on an"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANYKIND, either express or implied.  See the License for thespecific language governing permissions and limitationsunder the License.--> <!-- | This is the configuration file for Maven. It can be specified at two levels: | |  1. User Level. This settings.xml file provides configuration for a single user, |                 and is normally provided in ${user.home}/.m2/settings.xml. | |                 NOTE: This location can be overridden with the CLI option: | |                 -s /path/to/user/settings.xml | |  2. Global Level. This settings.xml file provides configuration for all Maven |                 users on a machine (assuming they're all using the same Maven |                 installation). It's normally provided in |                 ${maven.conf}/settings.xml. | |                 NOTE: This location can be overridden with the CLI option: | |                 -gs /path/to/global/settings.xml | | The sections in this sample file are intended to give you a running start at | getting the most out of your Maven installation. Where appropriate, the default | values (values used when the setting is not specified) are provided. | |--><settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">  <!-- localRepository   | The path to the local repository maven will use to store artifacts.   |   | Default: ${user.home}/.m2/repository     -->  <localRepository>d:/maven/repository</localRepository>   <!-- interactiveMode   | This will determine whether maven prompts you when it needs input. If set to false,   | maven will use a sensible default value, perhaps based on some other setting, for   | the parameter in question.   |   | Default: true  <interactiveMode>true</interactiveMode>  -->   <!-- offline   | Determines whether maven should attempt to connect to the network when executing a build.   | This will have an effect on artifact downloads, artifact deployment, and others.   |   | Default: false  <offline>false</offline>  -->   <!-- pluginGroups   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.   |-->  <pluginGroups><!-- pluginGroup     | Specifies a further group identifier to use for plugin lookup.<pluginGroup>com.your.plugins</pluginGroup>-->  </pluginGroups>   <!-- proxies   | This is a list of proxies which can be used on this machine to connect to the network.   | Unless otherwise specified (by system property or command-line switch), the first proxy   | specification in this list marked as active will be used.   |-->  <proxies><!-- proxy     | Specification for one proxy, to be used in connecting to the network. |<proxy>  <id>optional</id>  <active>true</active>  <protocol>http</protocol>  <username>proxyuser</username>  <password>proxypass</password>  <host>proxy.host.net</host>  <port>80</port>  <nonProxyHosts>local.net|some.host.com</nonProxyHosts></proxy>-->  </proxies>   <!-- servers   | This is a list of authentication profiles, keyed by the server-id used within the system.   | Authentication profiles can be used whenever maven must make a connection to a remote server.   |-->  <servers><!-- server     | Specifies the authentication information to use when connecting to a particular server, identified by     | a unique name within the system (referred to by the 'id' attribute below). | | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are     |       used together. |<server>  <id>deploymentRepo</id>  <username>repouser</username>  <password>repopwd</password></server>--> <!-- Another sample, using keys to authenticate.<server>  <id>siteServer</id>  <privateKey>/path/to/private/key</privateKey>  <passphrase>optional; leave empty if not used.</passphrase></server>-->  </servers>   <!-- mirrors   | This is a list of mirrors to be used in downloading artifacts from remote repositories.   |   | It works like this: a POM may declare a repository to use in resolving certain artifacts.   | However, this repository may have problems with heavy traffic at times, so people have mirrored   | it to several places.   |   | That repository definition will have a unique id, so we can create a mirror reference for that   | repository, to be used as an alternate download site. The mirror site will be the preferred   | server for that repository.   |-->  <mirrors><!-- mirror     | Specifies a repository mirror site to use instead of a given repository. The repository that     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors. |<mirror>  <id>mirrorId</id>  <mirrorOf>repositoryId</mirrorOf>  <name>Human Readable Name for this Mirror.</name>  <url>http://my.repository.com/repo/path</url></mirror> --><mirror><id>alimaven</id><mirrorOf>central</mirrorOf><name>aliyun maven</name><url>http://maven.aliyun.com/nexus/content/repositories/central/</url></mirror>    </mirrors>   <!-- profiles   | This is a list of profiles which can be activated in a variety of ways, and which can modify   | the build process. Profiles provided in the settings.xml are intended to provide local machine-   | specific paths and repository locations which allow the build to work in the local environment.   |   | For example, if you have an integration testing plugin - like cactus - that needs to know where   | your Tomcat instance is installed, you can provide a variable here such that the variable is   | dereferenced during the build process to configure the cactus plugin.   |   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles   | section of this document (settings.xml) - will be discussed later. Another way essentially   | relies on the detection of a system property, either matching a particular value for the property,   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.   | Finally, the list of active profiles can be specified directly from the command line.   |   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact   |       repositories, plugin repositories, and free-form properties to be used as configuration   |       variables for plugins in the POM.   |   |-->  <profiles><!-- profile     | Specifies a set of introductions to the build process, to be activated using one or more of the     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/> | or the command line, profiles have to have an ID that is unique. | | An encouraged best practice for profile identification is to use a consistent naming convention     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. | This will make it more intuitive to understand what the set of introduced profiles is attempting     | to accomplish, particularly when you only have a list of profile id's for debug. | | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.<profile>  <id>jdk-1.4</id>       <activation><jdk>1.4</jdk>  </activation>       <repositories><repository>  <id>jdk14</id>  <name>Repository for JDK 1.4 builds</name>  <url>http://www.myhost.com/maven/jdk14</url>  <layout>default</layout>  <snapshotPolicy>always</snapshotPolicy></repository>  </repositories></profile>--> <!-- | Here is another profile, activated by the system property 'target-env' with a value of 'dev', | which provides a specific path to the Tomcat instance. To use this, your plugin configuration     | might hypothetically look like: | | ... | <plugin> |   <groupId>org.myco.myplugins</groupId> |   <artifactId>myplugin</artifactId> | |   <configuration> |     <tomcatLocation>${tomcatPath}</tomcatLocation> |   </configuration> | </plugin> | ... | | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to     |       anything, you could just leave off the <value/> inside the activation-property. |<profile>  <id>env-dev</id>       <activation><property>  <name>target-env</name>  <value>dev</value></property>  </activation>       <properties><tomcatPath>/path/to/tomcat/instance</tomcatPath>  </properties></profile>-->  </profiles>   <!-- activeProfiles   | List of profiles that are active for all builds.   |  <activeProfiles><activeProfile>alwaysActiveProfile</activeProfile><activeProfile>anotherAlwaysActiveProfile</activeProfile>  </activeProfiles>  --></settings>

步骤 6 : 使用现成的仓库

在下载区(点击进入)有我目前使用的maven仓库,虽不能说齐全,但是相当一部分常用的已经有了。 可以直接下载并解压在
d:/maven/repository

这样就不需要自己下载了。

Maven 创建Maven项目

步骤 1 : 关于Maven风格的Java项目

Maven作为一种工具,可以创建标准化的Maven风格Java项目。 但是在实际工作中,很少有机会直接通过Maven 命令行来做到这一点。 通常都是在Eclipse或者IDEA中,通过集成Maven的方式来创建Java 项目。

本知识点会演示这种做法,目的是为了方便理解在IDE中对Maven的运用

步骤 2 : 切换到项目目录

按下win+r,然后输入cmd,接着输入
cd e:\project

步骤 3 : 创建maven项目

首先确保e:\project目录下没有j2se文件夹,否则会报错
然后执行命令:

mvn archetype:generate -DgroupId=com.how2java -DartifactId=j2se -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

archetype:generate 表示创建个项目
-DgroupId 项目包名: com.how2java
-DartifactId 项目名称: j2se
-DarchetypeArtifactId 项目类型: maven-archetype-quickstart
-DinteractiveMode:false 表示前面参数都给了,就不用一个一个地输入了

运行成功会看到绿色的BUILD SUCCESS

步骤 4 : 项目结构

如图所示,会创建一个标准结构的maven 项目,不仅如此还送了一个App.java。里面输出了一个Hello World!

package com.how2java; /** * Hello world! * */public class App{public static void main( String[] args ){System.out.println( "Hello World!" );}}

步骤 5 : 运行package命令

然后运行package命令
mvn package

注: 运行这个命令之前要先把当前路径切换到 j2se来
cd j2se

最后会看到一个绿色的BUILD SUCCESS

package做了很多事情,编译,测试,打包,最后生成了一个j2se-1.0-SNAPSHOT.jar包,里面放了APP这个类

步骤 6 : 执行Jar

java -cp target/j2se-1.0-SNAPSHOT.jar com.how2java.App

如图所示,会创建一个标准结构的maven 项目,不仅如此还送了一个App.java。里面输出了一个Hello World!

Maven Eclipse 设置

步骤 1 : 集成MAVEN

Eclipse EE版本是已经集成好MAVEN的了,无需额外手动集成。
没有的同学可以在这里下载:下载 Eclipse

步骤 2 : 设置MAVEN路径

菜单->Window->Preferences->Maven->Installations-> 指定 d:\software\apache-maven-3.5.0

注: 把原来的那个低版本maven删除掉,如果有的话

步骤 3 : 设置仓库路径

菜单->Window->Preferences->Maven->User Settings->
Global Settings 和 User Settings都使用:
D:\software\apache-maven-3.5.0\conf\settings.xml

点击一下Reindex,确保 local Repository为:
d:/maven/repository

Maven Eclipse Maven 项目

步骤 1 : 删除j2se目录

按照前面的学习流程,已经存在一个j2se目录,为避免干扰因素,先把这个目录删除掉

步骤 2 : 新建Maven 项目

菜单->File->New->Other->Maven->Maven Project

步骤 3 : 这个界面点下一步

步骤 4 : 这个界面使用默认的选项,点下一步

这里选择默认的maven-archetype-quickstart, 和命令行创建maven项目中的项目类型一致的

步骤 5 : 这一步填写如图所示的信息

Group Id: 填写包名
Artifact Id: 填写j2se
然后点击Finish

步骤 6 : 运行App

Maven 添加包

步骤 1 : Maven项目用到第三方jar

当一个Maven项目需要用到第三方jar的时候,就需要添加对应的jar包。
本例演示如何添加一个jdbc的jar包

步骤 2 : 修改App

修改App.class,故意写一段需要依赖jar包才可以成功执行的代码: 初始化mysql驱动

package com.how2java.j2se; /** * Hello world! * */public class App{public static void main( String[] args ) throws ClassNotFoundException{Class.forName("com.mysql.jdbc.Driver");System.out.println("初始化驱动成功");System.out.println( "Hello World!" );}}

步骤 3 : 给maven项目添加jar

双击pom.xml,出现pom专有的编辑页面。
点击OverView右边的Dependencies可以看到里面有一个默认存在的junit
然后点击Add,弹出选择窗口
在中间 Enter GroupId, artifactId or sha1 prefix or pattern(*)… 这个地方输入mysql,下面就会出来被搜索到的mysql-connector-java
选中它,并点击ok

注: Scope要选择compile,表示编译期间要用到。
注: 如果输入了mysql下面没有自动显示搜索结果怎么办?点击 重建本地仓库

步骤 4 : 保存再执行

点击保存,一定要记得保存,保存才能使得pom.xml中的jar包依赖起作用,接着再运行APP

步骤 5 : 重建本地仓库

倘若在给maven项目添加jar中无法搜索到mysql jar包,那么可以按照如下行为操作一遍
菜单->Window->Show View->Other->Maven->Maven Repositories->Local Repository->Rebuild Index

Maven 创建Web项目

步骤 1 : 关于Maven风格的Web项目

与创建Maven项目类似的,还可以创建web 项目
同样的,这种事情,几乎不会用命令行来做,都是用IDE来做的,比如Eclipse Web 项目

所以本知识点也就演示一下,实际工作一般不这么干

步骤 2 : 创建命令

  1. 首先切换目录
  2. 切换盘符
  3. 执行命令(确保e:\project下没有j2ee目录)
    mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-webapp -DgroupId=com.how2java -DartifactId=j2ee -DinteractiveMode=false

这个命令和创建maven java项目中的命令一样,不过类型是从
maven-archetype-quickstart 改成了 maven-archetype-webapp
项目名称从 j2se改成了j2ee而已

步骤 3 : 目录结构

与maven创建的java项目结构类似,不过没有java目录,需要自己手动创建。 所以命令行方式的maven web项目很少用到

Maven Eclipse Web 项目

步骤 1 : 删除j2ee目录

删除创建Web项目步骤创建的j2ee目录

步骤 2 : 新建Maven 项目

菜单->File->New->Other->Maven->Maven Project

步骤 3 : 这个界面点下一步

步骤 4 : 这个界面使用webapp,点下一步

默认选中的是maven-archetype-quickstart, 请修改为: maven-archetype-webapp

步骤 5 : 这一步填写如图所示的信息

步骤 6 : 此时得到的maven web 项目的问题

此时能得到的maven web 项目,不过有两个问题

  1. 没有java源代码目录
  2. index.jsp报错

步骤 7 : 创建java 源代码目录

在上一步的截图中可以发现,没有地方存放java源文件,这个时候就需要按照如下步骤做:
右键项目->属性->Java Build Path->Libraries->Edit->Workspace default
JRE(jdk8)->Finish

步骤 8 : java源文件目录创建好了

如图所示,java源文件目录创建好了

步骤 9 : 通过pom.xml添加servlet jar包

这个时候,还存在index.jsp会 报错的问题。 这个问题的解决办法是添加servlet.jar包。
做法参考:给maven项目添加jar

步骤 10 : 添加好之后,index.jsp也不报错了

步骤 11 : 通过eclipse内置tomcat启动

maven web-app 项目就像动态web项目那样,是支持通过eclipse 内置tomcat启动的

右键点击项目j2ee,点击Run As -> Run on Server ,成功之后就会看到如图所示的Hello World!

如果对于Eclipse内置Tomcat配置方式不熟悉,请参考教程:通过Eclipse启动Tomcat-Run On Server


Maven 创建 SSM 项目

步骤 1 : 基于前面的知识点

本知识点在SSM 的PageHelper的基础上进行,所以要先到SSM 的PageHelper去下载可运行的项目,并解压。

注: 不要下载到当前知识点的可运行项目了哦,当前的是已经完成了目前的步骤流程后完成的项目

步骤 2 : 创建maven web项目

File->New->Other->Maven->Maven Project

步骤 3 : 设置项目目录

默认即可

步骤 4 : 选择Archetype

选择 maven-archetype-webapp

步骤 5 : 设置GroupId和Artifact Id

设置GroupId和Artifact Id,分别是com.how2java和ssm。
后续配置也是用的这个,所以照着做,别自作聪明改其他的,不然后面走不通

步骤 6 : 项目截图

此时项目就创建好了,不过还会报错,接着做后续的一系列操作

步骤 7 : 创建java 源代码目录

在上一步的截图中可以发现,没有地方存放java源文件,这个时候就需要按照如下步骤做:
右键项目->属性->Java Build Path->Libraries->Edit->Workspace default
JRE(jdk8)->Finish

步骤 8 : java源文件目录创建好了

步骤 9 : pom.xml

接着复制粘贴pom.xml为下面的代码。 粘贴之后,jsp本来的报错就消失了,不过出来一个新的问题,要求通过Maven更新项目。

右键项目->Maven->Update Project,会弹出一个对话框,点击Ok,这个问题就消失了。

<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.how2java</groupId>  <artifactId>ssm</artifactId>  <version>0.0.1-SNAPSHOT</version>  <packaging>war</packaging>   <properties><spring.version>4.1.3.RELEASE</spring.version><pagehelper.version>5.1.2-beta</pagehelper.version><mysql.version>5.1.6</mysql.version><mybatis.spring.version>1.2.3</mybatis.spring.version><mybatis.version>3.1.1</mybatis.version><junit.version>4.12</junit.version><jstl.version>1.2</jstl.version><jsqlparser.version>1.0</jsqlparser.version><jackson.version>1.2.7</jackson.version><servlet-api.version>3.1.0</servlet-api.version><druid.version>1.0.18</druid.version><log4j.version>1.2.16</log4j.version><commons-logging.version>1.2</commons-logging.version><commons-fileupload.version>1.2.1</commons-fileupload.version><commons-io.version>1.3.2</commons-io.version><commons-lang.version>2.6</commons-lang.version><aopalliance.version>1.0</aopalliance.version><mybatis-generator.version>1.3.5</mybatis-generator.version>  </properties>   <dependencies> <dependency>  <groupId>junit</groupId>  <artifactId>junit</artifactId>  <version>${junit.version}</version></dependency> <dependency>  <groupId>org.mybatis</groupId>  <artifactId>mybatis</artifactId>  <version>${mybatis.version}</version></dependency> <dependency>  <groupId>org.mybatis</groupId>  <artifactId>mybatis-spring</artifactId>  <version>${mybatis.spring.version}</version></dependency> <dependency>  <groupId>mysql</groupId>  <artifactId>mysql-connector-java</artifactId>  <version>${mysql.version}</version></dependency> <dependency>  <groupId>com.alibaba</groupId>  <artifactId>druid</artifactId>  <version>${druid.version}</version></dependency> <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-context</artifactId>  <version>${spring.version}</version></dependency> <dependency>  <groupId>org.springframework</groupId>  <artifactId>spring-test</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-webmvc</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-aspects</artifactId>  <version>${spring.version}</version></dependency><!-- JSP相关 --><dependency>  <groupId>jstl</groupId>  <artifactId>jstl</artifactId>  <version>${jstl.version}</version></dependency> <dependency>  <groupId>javax.servlet</groupId>  <artifactId>javax.servlet-api</artifactId>  <version>${servlet-api.version}</version>  <scope>provided</scope></dependency> <!-- pageHelper --><dependency>  <groupId>com.github.pagehelper</groupId>  <artifactId>pagehelper</artifactId>  <version>${pagehelper.version}</version></dependency> <!--jsqlparser--><dependency>  <groupId>com.github.jsqlparser</groupId>  <artifactId>jsqlparser</artifactId>  <version>${jsqlparser.version}</version></dependency><dependency>  <groupId>log4j</groupId>  <artifactId>log4j</artifactId>  <version>${log4j.version}</version></dependency> <dependency>  <groupId>commons-logging</groupId>  <artifactId>commons-logging</artifactId>  <version>${commons-logging.version}</version></dependency> <dependency>  <groupId>commons-fileupload</groupId>  <artifactId>commons-fileupload</artifactId>  <version>${commons-fileupload.version}</version></dependency> <dependency>  <groupId>commons-io</groupId>  <artifactId>commons-io</artifactId>  <version>${commons-io.version}</version></dependency> <dependency>  <groupId>commons-lang</groupId>  <artifactId>commons-lang</artifactId>  <version>${commons-lang.version}</version></dependency> <dependency>  <groupId>aopalliance</groupId>  <artifactId>aopalliance</artifactId>  <version>${aopalliance.version}</version></dependency> <dependency>  <groupId>org.mybatis.generator</groupId>  <artifactId>mybatis-generator-core</artifactId>  <version>${mybatis-generator.version}</version></dependency>   </dependencies>   <build><finalName>${project.artifactId}</finalName><plugins>  <!-- 资源文件拷贝插件 -->  <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><version>2.7</version><configuration>  <encoding>UTF-8</encoding></configuration>  </plugin>  <!-- java编译插件 -->  <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration>  <source>1.8</source>  <target>1.8</target>  <encoding>UTF-8</encoding></configuration>  </plugin></plugins><pluginManagement>  <plugins><!-- 配置Tomcat插件 --><plugin>  <groupId>org.apache.tomcat.maven</groupId>  <artifactId>tomcat7-maven-plugin</artifactId>  <version>2.2</version></plugin>  </plugins></pluginManagement> <resources>  <resource><directory>src/main/resources</directory><includes>  <include>**/*.properties</include>          <include>**/*.xml</include>  <include>**/*.tld</include>        </includes>        <filtering>false</filtering>      </resource>      <resource>        <directory>src/main/java</directory>        <includes>          <include>**/*.properties</include>  <include>**/*.xml</include>        </includes>        <filtering>false</filtering>      </resource>    </resources>   </build> </project>

步骤 10 : 接着复制项目文件

首先从在基于前面的知识点里下载的项目里解压出来,然后按照如下顺序复制粘贴。 不要一股脑全粘贴进去,会出现无法解决的错误哦

步骤 11 : web.xml

首先覆盖web.xml
把下载下来的xxx/ssm/WebContent/WEB-INF/web.xml
复制到当前的 ssm/src/main/webapp/web.xml这里

步骤 12 : jsp 目录

接着复制jsp目录。
千万不要复制lib目录

步骤 13 : 配置文件

把三个配置文件复制到 ssm/src/main/resources下面

步骤 14 : java源代码

把java源代码复制到src/main/java下

步骤 15 : 关于Category.xml

按照maven ssm项目风格来说,这个文件本应该放在Resource目录的mapper文件夹下,但是这么做还要修改配置信息,为了避免问题复杂化,而且考虑到即使放在当前位置也是可以正常工作的,所以就暂时不修改它的位置了。

步骤 16 : 启动Tomcat

右键点击项目,点击Run As -> Run on Server 启动Tomcat

如果对于Eclipse内置Tomcat配置方式不熟悉,请参考教程:通过Eclipse启动Tomcat-Run On Server

步骤 17 : 访问测试地址

访问如下测试地址:

http://localhost:8080/ssm/listCategory


步骤 18 : 可运行项目
在下载区(点击进入)有本知识点对应的可运行项目下载 ,实在自己搞不出来,就下载解压出来比较一下。

注:不要和基于前面的知识点里的下载搞混了哦


©著作权归作者所有:来自51CTO博客作者wx5c4afeea27343的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. 如何在 阿里云 申请 ssl 免费证书
  2. 史上最详细的Intellij IDEA开发教程
  3. Springboot 如何做前后端分离?
  4. 如何设置 Centos7 为固定ip地址(详细教程)
  5. 变量系列教材 (八)- 什么是Java的表达式
  6. 控制流程系列教材 (一)- Java的If 条件语句
  7. HelloWorld系列教材 (五)- 在Eclipse中运行第一个 java 程序
  8. 面向对象系列教材 (一)- Java中的类和对象
  9. HelloWorld系列教材 (四)- 使用ecipse创建第一个 java project

随机推荐

  1. 成员函数可以重载吗?
  2. C语言中的三目运算符是什么
  3. c语言是面向什么的语言
  4. C语言中字符串连接函数是什么
  5. C语言中二叉树中序遍历怎么执行?
  6. 一个c语言程序总是从什么开始执行
  7. c++中static关键字的作用是什么?
  8. c语言真假是1和0吗?
  9. 学习asp.net core集成MongoDB的完整步骤
  10. c语言三种基本程序结构是什么?