Fork me on GitHub

JavaEE Day08 Maven

Day08 maven


什么是maven

  1. 项目构建,项目依赖管理,项目信息管理工具,
  2. 改变编码方式。

构建

编译、单元测试、打包、部署等过程称为构建。

编程风格

  1. maven必须有特定项目结构
  2. 约定优于配置

依赖管理

环境(jdk,tomcat)

项目的构建方式

  1. Ecplise:项目构建
    手工操作较多,ide的配置有差异;
  2. Ant:项目构建
  3. maven:项目构建和管理
    1. 基于pom(项目对象模型),xml配置
      项目构建方式,项目依赖信息
    2. 对项目目录结构严格要求(约定优于配置)
    3. 依赖管理:提供中央仓库(公开的服务器),所有的组件通过“坐标”来实现定位。pom.xml中配置组件坐标
  4. grade:项目构建和管理
    groovy语言

下载和安装maven

  1. 下载: maven官网 建议使用3.5.2版本

  2. 目录结构:

    bin:二进制可执行文件
    boot:启动maven依赖的jar包
    conf:配置文件
    lib:依赖jar包
    
  3. 环境变量配置

    1. M2_HOME = maven安装目录:
      (M2_HOME = D:\OneDrive\learning\JavaEE\maven\apache-maven-3.5.2)
    2. PATH新增M2_HOME路径:
      (PATH = %M2_HOME%\bin;)
  4. pom.xml依赖jar包配置的网页查找
    maven pom依赖jar包配置

  5. conf/setting配置

    <?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:\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
         | 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>nexus-aliyun</id>
            <mirrorOf>*</mirrorOf>
            <name>Nexus aliyun</name>
            <url>http://maven.aliyun.com/nexus/content/groups/public</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>
        -->
        <!-- 默认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>    
        <!--
         | 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>
    
    

手工开发maven项目

maven项目介绍

  1. maven项目的目录结构

    .
    ├── pom.xml # aven项目核心配置文件
    ├── src
    │   ├── main
    │   │   ├── java  # 存放项目java文件
    │   │   └── resources # 存放项目资源文件,如spring,hibemate配置文件
    │   └── test
    │       ├── java # 存放所有测试。java文件,如junit测试类
    │       └── resources # 测试资源文件
    └── target # 目标文件输入位置如.class,.jar,.war文件
    
  2. 常见命令:

    1. mvn compile: 编译(main/java文件)
    2. mvn test: 执行测试
    3. mvn clean: 清理(target 内容清空)
    4. mvn package:打包(jar,war),默认情况是jar包
    5. mvn install: 安装(部署到仓库(本地仓库))
    6. 组合命令: mvn clean compile
  3. 需要注意的是,在test目录下创建测试项目时,不需要导入main/java下的包,因为在maven中认为test/java和main/java是同一个目录;所以只要包名相同,就不需要继续导包了。

手工maven项目Hello

目录结构

.
└── HelloWorld
    ├── pom.xml
    └── src
        ├── main
        │   ├── java
        │   │   └── com
        │   │       └── lee
        │   │           └── hello
        │   │               └── HelloWorld.java
        │   └── resources
        └── test
            └── java
                └── com
                    └── lee
                        └── hello
                            └── TestHelloWorld.java

HelloWorld.java

package com.lee.hello;

public class HelloWorld{
	public void sayHi(String name){
		System.out.println("Hello:"+name);
	}

}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	sxi:schemaLication="http://maven.apache.org/POM/4.0.0
	http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<!--坐标:在服务器唯一确定组件 gav
		groupId:组或者组织公司等编号
		artifactId:模块功能编号
		version: 版本号
			x.x.x:
				SNAPSHOT:快照
				BETA:
				GA
				RELEASE:
	-->
	<groupId>com.lee</groupId>
	<artifactId>helloworld</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<!-- 依赖jar配置 -->
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
	</dependencies>
</project>%

TestHelloWorld.java

此处就不需要导入main下的HelloWorld这个类;

package com.lee.hello;

public class TestHelloWorld{

	public void test(){
		HelloWorld hw = new HelloWorld();
		hw.sayHi("za");
	}

}

测试

在src目录下 启动命令行

mvn compile # 编译
mvn test # 测试

eclipse集成maven

-w537
-w493
-w493

创建maven project

maven项目的创建方式

  1. 骨架方式
    1. 就是基本结构已经搭建起来了,不需要我们手工创建
  2. 简单项目

项目类型

  1. web项目 - 不建议使用骨架方式;
  2. java项目

使用骨架方式创建java项目

  1. 新建maven project
    -w487
    注意:选择简单项目就会跳过骨架的选择
  2. 选择maven骨架
    1. java项目使用quickstart结尾的
    2. web项目使用webapp结尾的
    3. 此处选择quickstart结尾的
  3. 设置当前项目的坐标
    -w487

第一次使用需要等待加载完成;加载完成如下:
-w204
如果没有 resources目录,则需要手动创建
main和test目录下都要有resources目录;

创建java类

package com.lee.hello;

public class HelloWorld {

    public void sayHi(String name){
        System.out.println("hello:"+name);
    }
}

创建测试类

package com.lee.hello;

import org.junit.Test;

public class HelloworldTest {
	@Test
	public void test(){
		HelloWorld hw = new HelloWorld();
		hw.sayHi("zs");
	}
}

修改pom.xml,配置依赖包

package com.lee.hello;

import org.junit.Test;

public class HelloworldTest {
	@Test
	public void test(){
		HelloWorld hw = new HelloWorld();
		hw.sayHi("zs");
	}
}

# chenzhuanglan @ chenzhuanglandeMacBook-Pro in ~/OneDrive/learning/WorkSpace/hello [0:34:06]
$ cat 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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

	<!-- 当前项目坐标 -->
    <groupId>com.lee</groupId>
    <artifactId>hello</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <!-- packaging 此处可以改成war -->
    <packaging>jar</packaging>


    <name>hello</name>
    <url>http://maven.apache.org</url>

    <!-- 属性:配置常量 -->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.1.6-release</spring.version>
    </properties>

    <!-- 依赖
        scope:作用域
            compile:默认,编译运行都生效
            test:测试时生效。junit
            provided:编译时生效运行时不生效。servlet-api.jar
            runtime:运行时生效,编译时不生效,mysql-connector.jar
    -->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <!--       <version>${spring.version}</version> -->
            <version>4.12</version>
            <!-- 作用域 -->
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

测试,打包,安装

都是右击项目名,然后选择run asmaven build…
-w625
在红色部分直接填写maven的命令选项即可;也可以使用组合命令,但是要使用空格分隔;输入完成后直接回车即可;eclipse会自动执行maven命令;

骨架方式创建mybatis项目

使用eclipse创建maven project

前三步 与上一个项目一样,只需修改ArtifactId为本项目的包名即可;
我的包名为mybatis04maven

编辑配置文件

将jdbc.properties、log4j.properties、mybatis.xml放置到src/main/resources/目录下

jdbc.properties

db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///bd1808?useSSL=true
db.username=root
db.password=root

log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<properties resource="jdbc.properties"></properties>
	<typeAliases>
		<package name="com.lee.mybatis04maven.pojo"/>
	</typeAliases>
	<environments default="dev">

		<environment id="dev">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="${db.driver}"/>
				<property name="url" value="${db.url}"/>
				<property name="username" value="${db.username}"/>
				<property name="password" value="${db.password}"/>
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<package name="com.lee.mybatis04maven.mapper"/>
	</mappers>
</configuration>%

配置pom.xml文件

  1. 修改junit的版本
  2. 增加jdbc驱动类,mybatis类,log4j类
  3. 通过maven pom依赖jar包配置查找
<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.lee</groupId>
  <artifactId>mybatis04maven</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>mybatis04maven</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!-- 1.驱动包 -->
    <dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
    	<version>5.1.38</version>
	</dependency>
    <!-- 2.mybatis核心包 -->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.4.4</version>
	</dependency>
    <!-- 3. log4j包 -->
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
	<dependency>
	    <groupId>log4j</groupId>
	    <artifactId>log4j</artifactId>
	    <version>1.2.17</version>
	</dependency>

  </dependencies>
</project>

创建实体类和mapper接口

实体类

package com.lee.mybatis04maven.pojo;

public class UserInfo {
	private int uid;
	private String username;
	private String password;


	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "UserInfo [uid=" + uid + ", username=" + username + ", password=" + password + "]";
	}


}

mapper接口

package com.lee.mybatis04maven.mapper;

import java.util.List;

import com.lee.mybatis04maven.pojo.UserInfo;

public interface UserMapper {

	List<UserInfo> queryAll();
}

配置mapper映射文件

在main/resources目录新建配置文件,但是mapper映射文件,需要与main/java下的mapper接口同包即可;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lee.mybatis04maven.mapper.UserMapper">
    <select id="queryAll" resultType="userinfo" >
        select * from userinfo
    </select>
</mapper>%

新建测试类

test/java下创建测试类

package com.lee.mybatis04maven.test;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import com.lee.mybatis04maven.mapper.UserMapper;

public class TestMybatis {

	@Test
	public void test() throws IOException{
		Reader reader = Resources.getResourceAsReader("mybatis.xml");
		SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
		SqlSession session = ssf.openSession(true);
		UserMapper mapper = session.getMapper(UserMapper.class);
		System.out.println(mapper.queryAll());
		session.close();
	}
}

测试运行即可

右击项目名,然后选择run asmaven test即可

注意事项:

test目录和main目录在相同包下 可以看成是一个包;
main目录和resources目录 在相同包下 也可以看成是一个包;

简单项目方式创建web项目

创建maven project

-w487
需要选择创建简单项目。
依次填写groupId、artifactId、version(本项目在本地仓库的坐标),打包方式选择war,这样才会是web项目,但是创建出来以后有报错信息,这是因为在src下的main目录下的webapp目录里没有相应的web配置,需要通过eclipse来生成,右击项目名称选择java ee tools选择第二个生成,此时就不会报错了.

但是在创建jsp文件时,又会出现报错,这是因为此时缺少了servlet-api.jar这个包,需要从pom.xml文件导入该包即可;

目录结构

.
├── javaweb.iml
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── servlet
│   │   │       └── HelloServlet.java
│   │   ├── resources
│   │   └── webapp
│   │       ├── WEB-INF
│   │       │   └── web.xml
│   │       └── index.jsp
│   └── test
│       ├── java
│       └── resources
└── target

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="hello">点击</a>
</body>
</html>

pom.xml

此处如果加了tomcat的puglin的配置,那么就可以直接在eclipse中运行,在maven build... 中使用命令tomcat7:run,即可运行服务器;

<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.lee</groupId>
  <artifactId>javaweb</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
  	<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>3.1.0</version>
	    <scope>provided</scope>
	</dependency>

  </dependencies>
  <build>
  	<finalName>javaweb</finalName>
  	<plugins>
			<plugin>
				<!-- 配置插件 -->
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<!-- tomcat配置 -->
				<configuration>
					<port>8080</port>
					<path>/</path>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>%

HelloServlet.java

package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "HelloServlet", value = "/hello")
public class HelloServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	response.getWriter().println("success");
    }
}

运行测试即可

可以直接 打包 使用maven build...,使用package命令即可,然后在target中找到javaweb.war文件,移至tomcat的webapp目录下即可,启动tomcat测试;

或者
若pom.xml加了tomcat的puglin的配置,那么就可以直接在eclipse中运行,在maven build... 中使用命令tomcat7:run,即可运行服务器测试;

需要注意的是如果运行报错了,修改完代码后 最好clean下,在编译或者测试;

idea的maven集成

-w572

需要配置默认配置,否则每次创建和加载maven项目时配置都需要从新配置
-w918

-w1163

创建maven项目

-w806

填写当前项目的坐标

-w807

配置maven

  1. maven的目录
  2. maven的配置文件
  3. 本地的maven仓库

-w807

创建项目

-w796

maven删除本地仓库中所有的.lastUpdated

mac

find /Users/chenzhuanglan/MavenRepository -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;

windows

cd %userprofile%\.m2\repository
for /r %i in (*.lastUpdated) do del %i

maven高级管理

子模块导入父pom中的依赖

默认情况下 子模块 强制加载 父pom中的依赖

但是为了能够很好的控制子模块导入的包;需要在父pom文件中的依赖外面在套一层标签;例如

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
      </dependency>
    <!-- 计算结果落地到HBase -->
      <dependency>
        <groupId>org.apache.hbase</groupId>
        <artifactId>hbase-client</artifactId>
        <version>${hbase.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

这样子模块中就不会默认导入所有父pom文件中的所有依赖;

此时,如果子模块想要导入 父pom文件中的依赖,则需要手动导入,但是不需要指定version信息,例如

<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-client</artifactId>
</dependency>

去除maven中的某个jar包

表示去除 spark-streaming-kafka-0-10_2.11 库中的 kafka-clients的依赖

 <dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-streaming-kafka-0-10_2.11</artifactId>
    <version>${spark.version}</version>
    <exclusions>
      <exclusion>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
      </exclusion>
    </exclusions>
  </dependency>

maven 编译的注意事项

Maven打包不打test,Maven中-DskipTests和-Dmaven.test.skip=true的区别

在使用mvn package进行编译、打包时,Maven会执行src/test/java中的JUnit测试用例,

有时为了跳过测试,会使用参数-DskipTests-Dmaven.test.skip=true

这两个参数的主要区别是:

-DskipTests:不执行测试用例,但编译测试用例类生成相应的class文件至target/test-classes下。

-Dmaven.test.skip=true:不执行测试用例,也不编译测试用例类。

maven设置代理

编辑 ~/.m2/setting.xml 文件。如果该目录下没有该文件,复制 $M2_HOME/conf/setting.xml 。

找到 节点。去掉相应的注释,设置代理信息。

原来Maven也像IE一样,可以设置代理的。

步骤如下:

  ·编辑 ~/.m2/setting.xml 文件。如果该目录下没有该文件,复制 $M2_HOME/conf/setting.xml 。

  ·找到 节点。去掉相应的注释,设置代理信息。

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

id:代理的名称(随便设,XYZ也行)

active:表示该代理是否激活

protocol:代理协议,这个不用改

username:当代理需要认证时的用户名

password:当代理需要认证时的密码

host:代理的IP地址

port:代理的端口号

nonProxyHost:指定不需要使用代理的主机,可不设置。如果有多个,用 | 分隔

maven仓库地址

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

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

<mirror>
	<id>jboss-public-repository-group</id>
	<mirrorOf>central</mirrorOf>
	<name>JBoss Public Repository Group</name>
	<url>http://repository.jboss.org/nexus/content/groups/public</url>
</mirror>
posted @ 2018-11-17 11:42  耳_东  阅读(197)  评论(0)    收藏  举报