Servlet 是基于 Java 技术的 web 组件,容器托管的,用于生成动态内容。客户端通过 Servlet 容器实现的请求/应答模型。

java.servlet.Servlet 接口的源码:

  1. public interface Servlet {
  2. public void init(ServletConfig config) throws ServletException;
  3. public ServletConfig getServletConfig();
  4. public void service(ServletRequest req, ServletResponse res)
  5. throws ServletException, IOException;
  6. public String getServletInfo();
  7. public void destroy();
  8. }

Servlet 基本使用

1、导入 Maven 依赖:Servlet 有两个版本,一个是3.0版本之前,为 servlet-api;一个是3.0版本之后,为 javax.servlet-api,使用时根据需求进行导入

  1. <!-- Servlet3.0之前的版本为servlet-api -->
  2. <dependency>
  3. <groupId>javax.servlet</groupId>
  4. <artifactId>servlet-api</artifactId>
  5. <version>2.5</version>
  6. <scope>provided</scope>
  7. </dependency>
  8. <!-- Servlet3.0之后的版本为javax.servlet-api -->
  9. <dependency>
  10. <groupId>javax.servlet</groupId>
  11. <artifactId>javax.servlet-api</artifactId>
  12. <version>4.0.1</version>
  13. <scope>provided</scope>
  14. </dependency>

2、编写一个自定义类,实现 Servlet 接口:

  1. public class MyServlet implements Servlet {
  2. @Override
  3. public void init(ServletConfig servletConfig) throws ServletException {
  4. System.out.println("Servlet init!");
  5. }
  6. @Override
  7. public ServletConfig getServletConfig() {
  8. return null;
  9. }
  10. @Override
  11. public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
  12. servletResponse.getWriter().write("Hello World!");
  13. }
  14. @Override
  15. public String getServletInfo() {
  16. return null;
  17. }
  18. @Override
  19. public void destroy() {
  20. System.out.println("servlet destroy!");
  21. }
  22. }

3、在 web.xml 中配置这个 Servlet,idea可以自动生成 web.xml:

  • 在项目文件夹上右击,选择 Add Framework Support

    1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/750131/1606138583704-2b46d879-5d92-424b-9e9c-ae127d313af6.png#align=left&display=inline&height=157&margin=%5Bobject%20Object%5D&name=image.png&originHeight=313&originWidth=702&size=30247&status=done&style=none&width=351)
  • 然后勾选 Web Application,idea会自动生成 web.xml 文件

    1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/750131/1606138722112-e3324d0e-46e5-453e-8f5c-273b00eabed8.png#align=left&display=inline&height=160&margin=%5Bobject%20Object%5D&name=image.png&originHeight=363&originWidth=802&size=33551&status=done&style=none&width=354)
  • 在生成的 web.xml 中配置自定义的 Servlet:

    1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/750131/1606140030296-988c64f4-1ce8-4294-b387-d4ec64f8c31c.png#align=left&display=inline&height=216&margin=%5Bobject%20Object%5D&name=image.png&originHeight=433&originWidth=712&size=56459&status=done&style=none&width=356)
  • 启动 tomcat,在浏览器中访问:localhost:8080/myServlet,能够看到返回值 Hello World!