一:流程分解
1.eclipse中创建maven项目
2.在pom.xml文件中增加jre和tomcat的相关jar包
3.设置maven的命令,用maven来执行tomcat
4.浏览器访问
二:演示
1.eclipse中创建maven项目
2.在pom.xml文件中增加jre和tomcat的相关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.guojian</groupId>
<artifactId>webproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
<dependencies>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Embedded Apache Tomcat required for testing war -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.设置maven的命令,用maven来执行tomcat
3.1、在src/maim/java下新建一个包servlet和该包下新建一个类HelloWorldServlet。
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author maxsu
*/
@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
resp.getWriter().write("Hello World! Maven Web Project Example.");
}
}
3.2、右键项目名–>Run As–>Maven build..–>clean install
正常时:
有可能报错:Dmaven.multiModuleProjectDirectory system property is not set.
这个需要maven环境变量配置M2_Home和配置JRE时需要引入这个环境变量。
-Dmaven.multiModuleProjectDirectory=$M2_HOME
3.3 运行在tomcat上:右键项目名–>Run As–>Maven build..–>tomcat7:run
正常时显示:
4.浏览器访问
http://localhost:8080/hello