一、Servlet 体系
Servlet
GenericServlet ===> 实现 Servlet 接口的抽象类
HttpServlet ===> 继承 GenericServlet 抽象类的子抽象类
二、GenericServlet
GenericServlet 实现了 Servlet 接口,而且将除了 service 方法外的其他方法都进行了空实现,即我们的自定义 Servlet 如果继承该抽象类,仅需实现 service 方法即可
package web.servlet;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet(urlPatterns = {"/first"})
public class FirstServlet extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("this is my first servlet!");
}
}
三、HttpServlet (推荐)
默认实现了判断 get 和 post 的逻辑,如果是 get,则执行 doGet();如果是 post,则执行 doPost();因此我们继承该类时需要复写 doPost() 方法
package web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/first"})
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet......");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost......");
}
}
四、urlPatterns 命名规则
- /xxx
- /xxx/xxx
- 结合通配符( /* ,*.[后缀])
package web.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/first", "/first/one", "*.info", "/*"})
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet......");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost......");
}
}