首页 > 编程语言 >JavaWeb开发基础Servlet API

JavaWeb开发基础Servlet API

时间:2024-07-27 22:08:40浏览次数:8  
标签:JavaWeb Servlet void javax API res servlet public

Servlet版本

Oracle将Java EE(Java SE还自己保留)交给开源组织,Eclipse基金会接手。但Oracle不允许开源组织使用Java名号,所以Jakarta EE名称于2018.02.26应运而生。

正是因为组织变化,Servlet被割裂为了2个版本,javax.servletjakarta.servlet

javax.servlet已经停止维护,但它仍然是一个非常有用和重要的技术,特别是在许多现有项目中,学习和使用它将为你提供坚实的Web开发基础。

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

如果希望使用Jakarta EE 9或更高版本的Servlet API,则需要切换到javax.servlet

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
    <scope>provided</scope>
</dependency>

本文将基于javax.servlet来介绍Servlet,从Usages来看,它仍然是使用最广泛的。

Servlet API

Servlet API主要有2个包,javax.servlet包含了servlet和web container使用的接口和类。javax.servlet.http包含了http相关的接口和类。

javax.servlet接口列表:

  1. Servlet
  2. ServletRequest
  3. ServletResponse
  4. RequestDispatcher
  5. ServletConfig
  6. ServletContext
  7. SingleThreadModel
  8. Filter
  9. FilterConfig
  10. FilterChain
  11. ServletRequestListener
  12. ServletRequestAttributeListener
  13. ServletContextListener
  14. ServletContextAttributeListener

javax.servlet类列表:

  1. GenericServlet
  2. ServletInputStream
  3. ServletOutputStream
  4. ServletRequestWrapper
  5. ServletResponseWrapper
  6. ServletRequestEvent
  7. ServletContextEvent
  8. ServletRequestAttributeEvent
  9. ServletContextAttributeEvent
  10. ServletException
  11. UnavailableException

javax.servlet.http接口列表:

  1. HttpServletRequest
  2. HttpServletResponse
  3. HttpSession
  4. HttpSessionListener
  5. HttpSessionAttributeListener
  6. HttpSessionBindingListener
  7. HttpSessionActivationListener
  8. HttpSessionContext (deprecated now)

javax.servlet.http类列表:

  1. HttpServlet
  2. Cookie
  3. HttpServletRequestWrapper
  4. HttpServletResponseWrapper
  5. HttpSessionEvent
  6. HttpSessionBindingEvent
  7. HttpUtils (deprecated now)

Servlet接口

Servlet Interface定义了所有servlet必须具有的行为。主要方法如下:

  1. public void init(ServletConfig config) 初始化,只会被web container调用1次

  2. public void service(ServletRequest request, ServletResponse response) 接收请求,返回响应,每次请求都会调用1次

  3. public void destroy() 销毁,只会被web container调用1次

  4. public ServletConfig getServletConfig() Servlet配置

  5. public String getServletInfo() Servlet信息

以下是代码示例:

import java.io.*;
import javax.servlet.*;

public class First implements Servlet {
    ServletConfig config = null;

    /**
     * 初始化
     * @param config
     */
    public void init(ServletConfig config) {
        this.config = config;
        System.out.println("servlet is initialized");
    }

    /**
     * 服务
     * @param req
     * @param res
     * @throws IOException
     * @throws ServletException
     */
    public void service(ServletRequest req, ServletResponse res)
            throws IOException, ServletException {

        res.setContentType("text/html");

        PrintWriter out = res.getWriter();
        out.print("<html><body>");
        out.print("<b>hello simple servlet</b>");
        out.print("</body></html>");
    }

    /**
     * 销毁
     */
    public void destroy() {
        System.out.println("servlet is destroyed");
    }

    /**
     * 配置
     * @return
     */
    public ServletConfig getServletConfig() {
        return config;
    }

    /**
     * 信息
     * @return
     */
    public String getServletInfo() {
        return "copyright 2007-1010";
    }
}

GenericServlet类

GenericServlet是个抽象类,实现了Servlet, ServletConfig, Serializable接口,能处理任何请求,支持任何协议。主要方法如下:

  1. public void init(ServletConfig config) 初始化
  2. public abstract void service(ServletRequest request, ServletResponse response) 接收请求,返回响应,每次请求都会调用1次
  3. public void destroy() 销毁,只会被web container调用1次
  4. public ServletConfig getServletConfig() Servlet配置
  5. public String getServletInfo() Servlet信息
  6. public void init() 无参初始化
  7. public ServletContext getServletContext() Servlet上下文
  8. public String getInitParameter(String name) 根据参数name返回value
  9. public Enumeration getInitParameterNames() web.xml所有参数
  10. public String getServletName() Servlet名称
  11. public void log(String msg) 记录Servlet日志
  12. public void log(String msg,Throwable t) 记录Servlet日志和异常堆栈

以下是代码示例:

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class First extends GenericServlet {
    public void service(ServletRequest req, ServletResponse res)
            throws IOException, ServletException {

        res.setContentType("text/html");

        PrintWriter out = res.getWriter();
        out.print("<html><body>");
        out.print("<b>hello generic servlet</b>");
        out.print("</body></html>");
    }
}  

HttpServlet类

HttpServlet继承了GenericServlet抽象类。主要方法如下:

  1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type.(这里结合英文解释比较清楚,转换类型后,调用第2个service)

  2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type.(这里结合英文解释比较清楚,根据不同method,调用doXXX()方法)

  3. protected void doGet(HttpServletRequest req, HttpServletResponse res) 处理GET请求,web container调用

  4. protected void doPost(HttpServletRequest req, HttpServletResponse res) 处理POST请求,web container调用

  5. protected void doHead(HttpServletRequest req, HttpServletResponse res) 处理HEAD请求,web container调用

  6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) 处理OPTIONS请求,web container调用

  7. protected void doPut(HttpServletRequest req, HttpServletResponse res) 处理PUT请求,web container调用

  8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) 处理TRACE请求,web container调用

  9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) 处理DELETE请求,web container调用

  10. protected long getLastModified(HttpServletRequest req) 上次修改时间

如果想深入学习Servlet API,可以在Maven pom.xml引入servlet包依赖,External Libraries查看源码。

参考资料:

https://www.javatpoint.com/servlet-api

https://www.javatpoint.com/Servlet-interface

https://www.javatpoint.com/GenericServlet-class

https://www.javatpoint.com/HttpServlet-class

ChatGPT

标签:JavaWeb,Servlet,void,javax,API,res,servlet,public
From: https://www.cnblogs.com/df888/p/18301949

相关文章

  • Python调用ChatTTS API接口
    Python调用ChatTTSAPI接口:#*********************************************#author:wgscd#date:2024-7-27#installlist:#pipinstallfastapi#pipinstallrequests#pipinstalluvicorn[standard]#在命令行中运行以下命令来启动服务器:#uvicornmain:app--reload......
  • 自写ApiTools工具,功能参考Postman和ApiPost
    近日在使用ApiPost的时候,发现新版本8和7不兼容,也就是说8不支持离线操作,而7可以。我想说,我就是因为不想登录使用才从Postman换到ApiPost的。众所周知,postman时国外软件,登录经常性抽风,离线支持也不太好。所以使用apipost,开始用apipost7一直很好用。可是apipost大升级,不支持离线操......
  • 字符串API
    API:应用程序编程接口,为预先定义的函数(方法)。一、常用的字符串APIlength()chartAt(int) //索引处字符toCharArray() //转换为char类型equals(String)  equalsIgnoreCase(String) //忽略字母大小小比较内容是否一样contains(String) //是否包含内容indexOf(String)......
  • 探索Memcached的宇宙:APIs及其工作原理深度解析
    ......
  • Servlet 超详细快速入门(详解 看这一篇就够了)
    1.Servlet介绍1.1 什么是Servlet  Servlet是ServerApplet的简称,是用Java编写的是运行在Web服务器上的程序,它是作为来自Web浏览器或其他HTTP客户端的请求和HTTP服务器上的数据库或应用程序之间的中间层。使用Servlet,可以收集来自网页表单的用户输入,呈现来自......
  • 在 FastAPI 中更改来自 MySQL 的数据类型输入
    我的这一行有“serialize_response”错误:@app.get("/get-sensors/",response_model=List[Data])和这个:return{"status":"success","list":data}我该如何解决这个问题!我想获取字典类型的数据为了解决在FastAPI中更改来自MySQL的数据类型输入时遇到的......
  • 【微信小程序开发】API使用、自定义组件、页面实现图解超详细
    文章目录常用API消息交互消息加载转发给朋友模态对话框获取用户信息调起客户端扫码界面发起支付获取位置自定义组件创建自定义组件使用自定义组件组件生命周期组件所在页面的生命周期页面实现淘宝订单简化页面饮品订单简化页面本篇总结更多相关内容可查看常用......
  • 无法在 Fast api 中使用 SQLAlchemy 删除子表
    下面我有三个表,它们之间有多对多的关系,问题是我无法删除数据库中的用户表:“表imagesmetadata上的约束imagesmetadata_user_id_fkey取决于表用户表令牌上的约束tokens_user_id_fkey取决于表usercannot删除表用户,因为其他对象依赖于它”删除令牌和图像元数据表后删除......
  • 如何使用aioprometheus和FastAPI向外部服务添加指标?
    我正在尝试在使用aioprometheus构建的应用程序中使用FastAPI向外部服务添加指标。这是我想要实现的目标的简化示例。假设我有一个这样的包装器App类:fromaioprometheusimportRegistry,Counter,HistogramfromfastapiimportFastAPIclassApp:......
  • apifox日常使用
    一、前后置操作1.1提取变量登录接口提取返回数据里的token,保存为全局变量1.2接口间相互传递数据详情接口使用登录接口返回提取的token二、Moc数据定义入参定义返参本地Mock......