【笔记】Servlet快速入门

前言

Servlet快速入门

创建项目

  • 创建Web项目,引入Servlet依赖

pom.xml

1
2
3
4
5
6
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>

创建一个类

  • 创建一个类,实现servlet接口,当接收到请求时,会自动执行service()方法

@WebServlet(""):定义访问路径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;

@WebServlet("/test")
public class MyServlet implements Servlet {

public void init(ServletConfig servletConfig) throws ServletException {

}

public ServletConfig getServletConfig() {
return null;
}

public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("test");
}

public String getServletInfo() {
return null;
}

public void destroy() {

}
}

完成

参考文献

哔哩哔哩——黑马程序员