一、软件版本
Eclipse Java EE IDE for Web Developers. Version: Neon Release (4.6.0)
Maven 3.3.9
Servlet 2.5
tomcat9
jdk1.8
本文将定Eclipse已配置好jdk和tomcat。
二、创建步骤
1、新建一个maven web项目
1.1 打开Eclipse,Ctrl + N 弹窗新建向导, 如下图
1.2 在搜索框中输入 maven project,
1.3 选择 Next ,选择好工作区间
1.4 选择 Next ,这里选择webapp结尾的骨架来创建web项目
1.5 输入好信息后,点击finish
1.7 至此,一个初始的maven web项目就建好了,目录结构如下:
2、项目属性的基本设置
2.1更改项目属性为UTF-8。
2.2更改项目依赖的jdk为本地jdk。
2.3更改项目的其他属性
3、更改项目的部署路径
4、编写程序
这里编写一个简单servlet。首先在pom.xml中引入servlet依赖。
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kang</groupId>
<artifactId>WebTest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>WebTest Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>WebTest</finalName>
</build>
</project>
然后在src/main/java目录下建立一个servlet。
MyTest.java
package com.kang; import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class MyTest
*/
public class MyTest extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public MyTest() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }
最后编写jsp页面。
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>
Hello World!
<a href="http://localhost:8080/WebTest/MyTest">request.getContextPath()</a>
</body>
</html>
5、运行到tomcat上