Myeclipse:Java1.7+Tomcat8.5+maven+servlet3.0简易示例
整个项目预览图:
1. 新建maven程序:
2. 点下一步:
点完成,新建项目完成。
3. 进入build path
将两个错误的删除。
4. 添加maven要求的必须的四个目录(file->new->source Folder)
5. 进入build path 设定4个文件夹的输出Output folder,双击修改
分别修改输出路径为
src/main/resources 对应 target/classes
src/main/java 对应 target/classes
src/test/resources 对应 target/test-classes
src/test/java 对应 target/test-classes
6. 修改后的文件
7. 改变Libraries和Dynamic Web Projec
点击项目,右键进入properties,双击Myeclipse,选择property faces,点击ok
8. 至此,程序就不报错了。之后配置pom.xml,引入servlet3.0依赖
<projectxmlns="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.0http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>test2</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>test2 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>
<!--要求Maven下载Servlet3.0的jar包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<build>
<finalName>test2</finalName>
</build>
</project>
9. 这时候,系统自动将servlet3.0依赖包下载到了项目中。配置servlet3.0的web.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
10. 创建index.jsp
<%@page language="java" contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtml PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Hello</title>
</head>
<body>
Helloworld!
<ahref="./hello">Hello</a>
</body>
</html>
11. 再于src/main/java新建一个hello.java,这是一个普通类,不用servlet创建,此时已经不需要再web.xml中配置路径,用注解代替了。如下
package com.test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@WebServlet(name="hello",urlPatterns={"/hello"})
public class hello extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
PrintStream out = new PrintStream(response.getOutputStream());
response.setContentType("text/html;charSet=utf-8");
out.print("hello world");
}
}
12.把工程发布到Tomcat中运行,运行结果如下:
点击hello超链接进入:
至此,一个完整的servlet3.0的maven程序搭建成功,可以尝试高级功能了。
本内容由安康学院"雨季"原创。