Servlet 是基于 Java 技术的 web 组件,容器托管的,用于生成动态内容。客户端通过 Servlet 容器实现的请求/应答模型。
java.servlet.Servlet 接口的源码:
public interface Servlet {
public void init(ServletConfig config) throws ServletException;
public ServletConfig getServletConfig();
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
public String getServletInfo();
public void destroy();
}
Servlet 基本使用
1、导入 Maven 依赖:Servlet 有两个版本,一个是3.0版本之前,为 servlet-api;一个是3.0版本之后,为 javax.servlet-api,使用时根据需求进行导入
<!-- Servlet3.0之前的版本为servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- Servlet3.0之后的版本为javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
2、编写一个自定义类,实现 Servlet 接口:
public class MyServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("Servlet init!");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
servletResponse.getWriter().write("Hello World!");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("servlet destroy!");
}
}
3、在 web.xml 中配置这个 Servlet,idea可以自动生成 web.xml:
在项目文件夹上右击,选择 Add Framework Support
![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 文件
![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:
![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!