实验一Maven的使用

maven的使用


Maven是什么 ?

Apache Maven是一个软件项目管理和综合工具。基于项目对象模型(POM)的概念,Maven可以从一个中心资料片管理项目构建,报告和文件。Maven提供了开发人员构建一个完整的生命周期框架。开发团队可以自动完成项目的基础工具建设,Maven使用标准的目录结构和默认构建生命周期。在多个开发团队环境时,Maven可以设置按标准在非常短的时间里完成配置工作。由于大部分项目的设置都很简单,并且可重复使用,Maven让开发人员的工作更轻松,同时创建报表,检查,构建和测试自动化设置。

Maven目标

Maven主要目标是提供给开发人员:

  • 项目是可重复使用,易维护,更容易理解的一个综合模型。
  • 插件或交互的工具,这种声明性的模式。
    Maven项目的结构和内容在一个XML文件中声明,pom.xml 项目对象模型(POM),这是整个Maven系统的基本单元。有关详细信息,请参阅Maven POM的部分。
Maven安装和配置(Windows)
Maven 下载

下载地址:http://maven.apache.org/download.cgi
在这里插入图片描述

不同平台下载对应的包:

系统包名
Windowsapache-maven-3.6.3-bin.zip
Linuxapache-maven-3.6.3-bin.tar.gz
Macapache-maven-3.6.3-bin.tar.gz

下载包后解压到对应目录:

系统存储位置 (可根据自己情况配置)
WindowsD:\Tools\apache-maven-3.6.3
Linux/usr/local/apache-maven-3.6.3
Mac/usr/local/apache-maven-3.6.3
设置 Maven 环境变量

添加环境变量 MAVEN_HOME:
右键 “计算机”,选择 “属性”,之后点击 “高级系统设置”,点击"环境变量",来设置环境变量,有以下系统变量需要配置:
新建系统变量 MAVEN_HOME,变量值:D:\Tools\apache-maven-3.6.3
在这里插入图片描述

编辑系统变量 Path,添加变量值:%MAVEN_HOME%\bin
在这里插入图片描述

验证

执行 mvn –v 在命令提示符下,如下图输出结果:
在这里插入图片描述

如果你看到类似消息,说明 Apache Maven 在 Windows 上已安装成功。

修改配置文件

通常我们需要修改解压目录下conf/settings.xml文件,这样可以更好的适合我们的使用。

  • 此处注意:所有的修改一定要在注释标签外面,不然修改无效。Maven很多标签都是给的例子,都是注释掉的。

最后附上整个Settings.xml文件配置示例。
在这里插入图片描述

本地仓库位置修改

在标签内添加自己的本地位置路径

  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
  <localRepository>D:\Tools\maven-repository</localRepository>
修改maven默认的JDK版本

查看自己的JDK版本:
在这里插入图片描述

在标签下添加一个标签,修改maven默认的JDK版本。

  <profile>
    <id>JDK-1.8</id>
    <activation>
        <activeByDefault>true</activeByDefault>
        <jdk>1.8</jdk>
    </activation>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
    </properties>
</profile>
添加国内镜像源

添加<mirrors>标签下<mirror>,添加国内镜像源,这样下载jar包速度很快。默认的中央仓库有时候甚至连接不通。一般使用阿里云镜像库即可。Maven会默认从这几个开始下载,没有的话就会去中央仓库了。

<!-- 阿里云仓库 -->
      <mirror>
        <id>alimaven</id>
        <mirrorOf>central</mirrorOf>
        <name>aliyun maven</name>
        <url>http://maven.aliyun.com/nexus/content/repositories/central/</url>
      </mirror>
      <!-- 中央仓库1 -->
      <mirror>
        <id>repo1</id>
        <mirrorOf>central</mirrorOf>
        <name>Human Readable Name for this Mirror.</name>
        <url>http://repo1.maven.org/maven2/</url>
      </mirror>
      <!-- 中央仓库2 -->
      <mirror>
        <id>repo2</id>
        <mirrorOf>central</mirrorOf>
        <name>Human Readable Name for this Mirror.</name>
        <url>http://repo2.maven.org/maven2/</url>
      </mirror>
在Eclipse下配置Maven

Eclipse自身集成了一个版本的Maven。但是通常我们使用自己已经配置好的Maven。

  1. 将Eclipse使用的Maven修改为自己的。点击add后选择自己Maven的安装目录即可。添加好之后记得勾选。依次点击Window ->Preferences->Maven->Installations:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  2. 点击 Maven节点下的UserSettings,将所有的settings修改为自己Maven目录下的conf/settings.xml.点击Update Settings按钮,下面的Local Respository会自动识别出来。
    在这里插入图片描述

至此Maven配置结束!


附:完整的Settings.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with 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 ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under 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>
    -->
    <localRepository>D:\Tools\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>
      <!-- 中央仓库1 -->
      <mirror>
        <id>repo1</id>
        <mirrorOf>central</mirrorOf>
        <name>Human Readable Name for this Mirror.</name>
        <url>http://repo1.maven.org/maven2/</url>
      </mirror>
      <!-- 中央仓库2 -->
      <mirror>
        <id>repo2</id>
        <mirrorOf>central</mirrorOf>
        <name>Human Readable Name for this Mirror.</name>
        <url>http://repo2.maven.org/maven2/</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>
    -->
        <profile>
            <id>jdk-1.8</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>


在Eclipse中新建一个maven项目

(1)在创建向导中多了maven的相关选项:
在这里插入图片描述

(2) 选择默认的工程位置,下一步
在这里插入图片描述

(3)创建工程,填写相关的groupId artifactId version等信息
在这里插入图片描述

点击完成就创建好了一个简单的maven工程。maven的工程一般都是如下的结构:
在这里插入图片描述

pom.xml:用于定义或者添加jar包的依赖

src-main:用于存放java源文件

src-test:用于存放测试用例。

target:来生成对应的class文件或发布的jar包。

(4)刚刚创建的项目会报错错误,首先配置tomcat和jdk,点击项目右键>>Build Path>>Configure Build Path。
在这里插入图片描述

右键点击项目的Deployment Descriptor:testmaven,选择Generate Deployment Descriptor Stub
在这里插入图片描述

这样转成了web项目,生成了webapp下的WEN-INF文件夹

在这里插入图片描述

(5)继续点击Project Facets。取消 Dynamic Web Module 选项并将 Java 也就是 JDK 版本 调到 1.8。

点击 Apply 后,再勾选 Dynamic Web Module 并将其版本跳到 3.1。结果如下图所示:
在这里插入图片描述

如果还有错,右键点击项目的Deployment Descriptor:testmaven,选择Generate Deployment Descriptor Stub

(9)最后:如果我们想把根目录设置为 webapp 的话,仍然是右键项目名,点击 Propertites --> Deployment Assembly。如图所示:
在这里插入图片描述
选择这个 /WebContent,然后点击 Remove,再点击 Add
在这里插入图片描述
选中 Folder 后点击 Next,然后如图所示:选中 webapp 后 Finish,再 Apply and Close。
在这里插入图片描述
在这里插入图片描述

在webapp下新建一个jsp文件,
在这里插入图片描述
在这里插入图片描述

看见上面的jsp页面正常显示,说明web工程配置成功

在maven项目添加Spring环境
添加Spring Framework 依赖

打开项目中的pom.xml文件,并点击Dependencies标签,点击add添加新的依赖
在这里插入图片描述
如果知道依赖的group id和artifact id,可以直接填写,如果不清楚,可以输入关键字进行查询,或是到https://mvnrepository.com/网站查询所依赖的报的GroupId、 Artifact Id、Version。
通过关键字查询,修改版本号符合自己需要的jar包,
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

或者通过https://mvnrepository.com/网站查询所依赖的报的GroupId、 Artifact Id、Version。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

保存后即可在线更新jar包。

最终添加完Spring的jar包
在这里插入图片描述

添加ApplicationContext.XML

使用Spring帮助文档获取配置文件applicationContext.xml信息,可以下载Spring Framework的帮助文档,在
spring_framework-5.0.2.RELEASE\docs\spring-framework-reference\index.html
在这里插入图片描述
或者使用在线Spring Framework的帮助文档

https://spring.io/projects/spring-framework#learn

由于Spring上没有列出5.0.2版本的文档,我们使用5.0.16作参考,
在这里插入图片描述

点击Core:

在这里插入图片描述

选择1.2.1节,右面的位applicationContext.xml的内容,复制后,在项目src->main->resources文件夹下新建applicationContext.xml,粘贴内容:
在这里插入图片描述

在src/main/java下创建dao和test包,导入ch1中的TestDao.java和TestDaoImpl.java,test包导入Test.java,

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

配置applicationContext.xml的bean:
在这里插入图片描述

右键运行Test.java,Run As… 选 Java Application,出现如下运行结果,即完成Spring项目的配置
在这里插入图片描述

选择1.2.1节,右面的位applicationContext.xml的内容,复制后,在项目src->main->resources文件夹下新建applicationContext.xml,粘贴内容:

在src/main/java下创建dao和test包,导入ch1中的TestDao.java和TestDaoImpl.java,test包导入Test.java,
在这里插入图片描述

配置applicationContext.xml的bean:

在这里插入图片描述

右键运行Test.java,Run As… 选 Java Application,出现如下运行结果,即完成Spring项目的配置

在这里插入图片描述

当涉及到使用Maven和JDBC技术在项目开发中时,可以设计以下实验实验目标:通过Maven构建一个基于JDBC的简单Java应用程序,实现连接数据库、执行SQL查询和更新操作。 实验步骤: 1. 环境准备: - 安装Java JDK和Maven,并设置环境变量。 - 在本地或远程数据库服务器上创建一个测试数据库,并创建一些测试表和数据。 2. 创建Maven项目: - 在命令行或IDE中使用Maven命令创建一个新的Maven项目。 - 在项目的pom.xml文件中配置所需的依赖项,包括JDBC驱动程序。 3. 编写Java代码: - 创建一个Java类,用于连接数据库并执行SQL操作。 - 在类中使用JDBC API来建立数据库连接,执行SQL查询和更新操作。 - 编写适当的异常处理代码,确保程序能够正确处理可能出现的错误情况。 4. 配置数据库连接信息: - 在项目中创建一个配置文件,用于存储数据库连接信息,如数据库URL、用户名和密码等。 - 在Java代码中读取这些配置信息,并使用它们来建立数据库连接。 5. 编译和运行程序: - 使用Maven构建项目,并生成可执行的JAR文件。 - 在命令行中运行JAR文件,观察程序是否能够成功连接数据库并执行SQL操作。 - 检查程序的输出结果和数据库中的数据是否一致。 6. 实验扩展(可选): - 尝试执行不同类型的SQL查询和更新操作,如插入、更新、删除等。 - 使用PreparedStatement来执行参数化的SQL查询和更新操作,以防止SQL注入攻击。 - 实现异常处理和错误恢复机制,确保程序在出现错误时能够正确处理和回滚数据库操作。 通过这个实验,你将能够学习和理解如何使用Maven和JDBC技术在项目开发中连接数据库并执行SQL操作。这将为你提供一个基础,以后在实际项目中使用这些技术时能够更加熟练和自信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值