6-Maven

目录

1.什么是Maven?

PS:关于 jar 包

2.配置并使用Maven

2.1.Maven依赖管理流程

2.2.Maven国内源配置

①确认右边的两个勾已经都选中。

②查看自己电脑上settings.xml文件是否存在,进而进行相关配置

③配置所有新项目配置文件

PS:在本地仓库查看对应的jar包

PS:在当前项目中查看引入的jar包

PS:在当前项目中添加/删除jar包

2.3.Maven依赖导入失败解决方案——删本地jar包,重新下载jar包

3.创建第一个Maven项目

3.1.项目目录说明

3.2.pom.xml文件说明

PS:添加Maven外部引用的jar包:

3.3.使用 JDBC 实现查询功能

4.Maven打包(生命周期)


1.什么是Maven?

Maven 是⼀个项⽬构建⼯具,创建的项⽬只要遵循 Maven 规范(称为Maven项⽬),即可使⽤ Maven 来进⾏:①管理 jar 包、②编译项目(定位错误进行修改)、③打包项目(发布web项目到其他服务器)等功能。

学习 Servlet 之前要学 Maven, 是因为 Servlet 是框架,要使⽤ Maven 引入外部 jar 包、打包项⽬和发布项目。

PS:关于 jar 包

项目构成:

  • 自己的代码。
  • 别人的代码。

引进别人的代码,不是一个单独的功能,而是一系列功能的集合——使用 jar 包(多个 java 代码的压缩包,默认把Java整个生态里常用的包全放在一个国外的仓库里):

  • 之前JDBC讲过一种方式:通过Idea找到本地jar包,直接去用。存在的问题:大家使用的版本可能不同,协同代码会有问题。
  • 为了大家使用的版本内容一致,则使用官方的jar包(默认是国外的数据源,若不配置Maven,访问会非常慢,若遇到网络不好去情况,超过HTTP最长响应时间,会显示中断,下载出错)。
  • jar包里通常会放.class文件(无注释;会做源代码的保护:修改不了、功能能用,但看不到源码),不会放.java文件。

2.配置并使用Maven

Maven ⽆需安装,因为 Idea 已经⾃带了,打开 Idea 搜索“Maven”就能找到 Maven,如下图所示:

2.1.Maven依赖管理流程

Maven 项⽬中可以引⼊依赖包(引⼊外部框架的 jar 包),引⼊后,加载依赖包的⽅式为在 Maven 仓库中搜索。 Maven仓库可以理解为存放依赖包的仓库,分为本地仓库和远程仓库两种。

本地仓库地址在 Idea 中可以找到:

2.2.Maven国内源配置

Maven 默认情况下使⽤的国外源,所以下载 jar 会很慢,且经常出差,所以⼀定要配置本机的 Maven 源为国内源,它的配置⽅法如下:

①确认右边的两个勾已经都选中。

②查看自己电脑上settings.xml文件是否存在,进而进行相关配置

Win(图标)+ R 快捷打开cmd窗口:

若没有此目录,先建立此目录(路径中不要出现中文!)

a. 如果不存在,复制下面配置了国内源的 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>
  -->

  <!-- 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>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>        
    </mirror>
    <!-- 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>
     -->
  </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>

b. 如果存在,检查 settings.xml 是否配置了国内源。

没有配置国内源,需要添加Maven配置信息,将以下代码复制保存到镜像集合中,即将当前的国外源改为了国内的阿里源。目前使用国内源较多的有2种:阿里的(推荐);网易的。

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

注:不要直接去下载配置好的settings.xml文件,然后覆盖掉原来电脑上已存在的settings.xml文件,会出错!

③配置所有新项目配置文件

重复上述步骤再执行一次。

PS:在本地仓库查看对应的jar包

jar包存在,直接去项目中使用。

PS:在当前项目中查看引入的jar包

PS:在当前项目中添加/删除jar包

删除:

 

 添加即是在pom.xml中添加对应依赖即可。都要点reload按钮!

2.3.Maven依赖导入失败解决方案——删本地jar包,重新下载jar包

步骤一:先多检查⼏遍第⼀步是否配置好国内maven源。

步骤二:如果配置没问题,则删除本地存储 jar 包的⽬录下的所有文件,避免之前有下载不全的jar包。

步骤三:切换到 Idea 中,重新下载 jar 包。

待下载完成,如果还是下载失败那就是本地⽹速问题,更换网络,重复上述步骤直到下载成功! 

3.创建第一个Maven项目

第一次右下角的滚动条加载时间会比较长,右边maven面板会报红,没关系,多下载几次就行。

3.1.项目目录说明

3.2.pom.xml文件说明

xml(可扩展标记语言,EXtensible Markup Language):出现比java还要早,最早出现时有2种用途:

  1. 描述当前项目的配置文件。
  2. 作为信息传递的载体。(现在使用json来代替)

PS:添加Maven外部引用的jar包:

Maven中央仓库这个网站可以供java开发者注册登录,将自己公司或自己写的jar包发布上去,供大家共同使用。Maven中央仓库就相当于是手机的应用中心,大家都可以去里面下载需要的jar包。

Maven中央仓库地址https://mvnrepository.com/①去Maven中央仓库找到对应的依赖信息。

 

引用依赖信息是不分国内/国外的,至于具体下载jar包是去国内/国外,是和项目的settings设置有关。

②将依赖信息复制粘贴到pom.xml中。

③一定要点击重新导入按钮。

3.3.使用 JDBC 实现查询功能

import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class App {
    //普通项目仍然需要main方法;web项目就不需要main方法了。
    public static void main(String[] args) throws SQLException {
        //1.得到DataSource
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setURL("jdbc:mysql://127.0.0.1:3306/java33?character=utf8&useSSL=false"); //useSSL是否使用加密的方式进行传输:有的电脑需要设置为true,有的电脑需要设置为false。可以都试一下,哪个行设置哪个即可。
        dataSource.setUser("root");
        dataSource.setPassword("12345678");

        //2.得到Connection
        Connection connection = (Connection) dataSource.getConnection();

        //3.拼接sql,并执行
        String sql = "select * from student where id=?";
        PreparedStatement statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setInt(1,2);//参数的坐标是从1开始,设置的值为2

        //4.执行查询
        ResultSet resultSet = statement.executeQuery();//查询,返回的是一个结果集:ResultSet
        //int result = statement.executeUpdate();//增加,删除,修改,返回受影响的行数:int类型
        if(resultSet.next()) {
            //有数据
            System.out.println("用户名:" + resultSet.getString("username"));
            System.out.println("email:" + resultSet.getString("mail"));
        }

        //5.关闭资源,从小往大关闭
        resultSet.close();
        statement.close();
        connection.close();
    }
}

 

4.Maven打包(生命周期)

当项目运行起来后,项目目录会增加 target 文件夹。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值