web.xml文件配置如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
所需javaee-jar包:
导入tomcat7.0以上版本的lib下的jar文件即可。
程序如下:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="FirstServlet",urlPatterns={"/FirstServlet","/MyServlet"}) // 注解,即体现出servlet3.0的优势
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter();
out.println("hello World");
out.close();
}
}
配置tomcat中的server.xml文件,加入如下代码(指定项目的访问路径):
<Context path="/servlet3.0" docBase="D:\Workspaces\servlet3.0\WebRoot" reloadable="true"/>
// 项目名称为servlet3.0