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>