1、创建web项目
2、勾选Generate web.xml
3、创建Class文件并实现Servlet接口
当搜索Servlet接口时,如果未发现接口则Add library→选择tomcat版本至完成。
代码如下:
package test.servlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class TestServlet implements Servlet {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
System.out.println("servlet初始化");
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
System.out.println("service");
}
public TestServlet(){
System.out.println("TestServlet");
}
}
4、编辑web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>servlet-demo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置和映射servlet -->
<servlet>
<!-- Servlet注册的名字 -->
<servlet-name>TestServlet</servlet-name>
<!-- Servlet的全类名 -->
<servlet-class>test.servlet.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- 需要和某一个servlet节点的servlet-name子节点的名称一致 -->
<servlet-name>TestServlet</servlet-name>
<!-- 映射具体的访问路径:/代表当前web应用的根目录 -->
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>