我读了很多文章来理解Java servlet,但我没有成功。

你能简单介绍一下Java servlet吗(用简单的语言)?什么是servlet?它的优点是什么?

我不能理解服务器端编程语言(PHP, ASP)和servlet之间的区别。


当前回答

servlet只是一个响应特定类型网络请求的类——最常见的是HTTP请求。基本上,servlet通常用于实现web应用程序——但也有各种框架在servlet之上运行(例如Struts),以提供比servlet提供的“这是一个HTTP请求,写入此HTTP响应”级别更高级别的抽象。

servlet运行在处理网络端(例如解析HTTP请求,连接处理等)的servlet容器中。Tomcat是最著名的开源servlet容器之一。

其他回答

正如本文所描述的,Servlet是一种扩展Java服务器并访问其功能的标准化方式。

每个Servlet都可以被视为一个小型服务器(因此得名),它可以访问用Java代码建模的请求和响应,以及其他上下文数据,比如Session。

有了这些,servlet的Java代码就可以与它所需要的任何东西交互以呈现响应,包括交给JSP页面来生成HTML视图。

servlet只是一个响应特定类型网络请求的类——最常见的是HTTP请求。基本上,servlet通常用于实现web应用程序——但也有各种框架在servlet之上运行(例如Struts),以提供比servlet提供的“这是一个HTTP请求,写入此HTTP响应”级别更高级别的抽象。

servlet运行在处理网络端(例如解析HTTP请求,连接处理等)的servlet容器中。Tomcat是最著名的开源servlet容器之一。

A servlet at its very core is a java class; which can handle HTTP requests. Typically the internal nitty-gritty of reading a HTTP request and response over the wire is taken care of by the containers like Tomcat. This is done so that as a server side developer you can focus on what to do with the HTTP request and responses and not bother about dealing with code that deals with networking etc. The container will take care of things like wrapping the whole thing in a HTTP response object and send it over to the client (say a browser).

Now the next logical question to ask is who decides what is a container supposed to do? And the answer is; In Java world at least It is guided (note I did not use the word controlled) by specifications. For example Servlet specifications (See resource 2) dictates what a servlet must be able to do. So if you can write an implementation for the specification, congratulations you just created a container (Technically containers like Tomcat also implement other specifications and do tricky stuff like custom class loaders etc but you get the idea).

假设您有一个容器,您的servlet现在是java类,其生命周期将由容器维护,但它们对传入HTTP请求的反应将由您决定。你可以通过在init()、doGet()、doPost()等预定义方法中编写你想要做的事情来做到这一点。看看资源3。

这里有一个有趣的练习。像资源3中那样创建一个简单的servlet,在它的构造函数方法(是的,你可以有一个servlet的构造函数)、init()、doGet()、doPost()方法中编写一些System.out.println()语句,并在tomcat中运行servlet。查看控制台日志和tomcat日志。

资源

看看这里的HTTP servlet (Tomcat示例)。 Servlet规范。 简单的Servlet示例。 开始在线阅读这本书/PDF 它还提供了整本书的下载。也许这会有帮助。 如果你刚刚开始使用servlet,那么阅读相关材料和servlet API是一个不错的主意。这是一个较慢的学习过程,但对弄清基本知识更有帮助。

servlet是当网站用户从服务器请求URL时运行某些功能的Java类。这些函数可以完成将数据保存到数据库、执行逻辑和返回加载页面所需的信息(如JSON数据)等任务。

大多数Java程序使用main()方法在程序运行时执行代码。Java servlet包含doGet()和doPost()方法,它们的作用与main()方法类似。当用户向映射到该servlet的URL发出GET或POST请求时,将执行这些函数。因此,用户可以为GET请求加载页面,或者存储来自POST请求的数据。

当用户发送GET或POST请求时,服务器读取目录中每个servlet类顶部的@WebServlet,以决定调用哪个servlet类。例如,假设你有一个ChatBox类,顶部是这样的:

@WebServlet("/chat")
public class ChatBox extends HttpServlet {

当用户请求/chat URL时,ChatBox类将被执行。

我认为servlet基本上是一个java类,充当HTTP请求和HTTP响应之间的中间路径。Servlet也用来使你的网页动态。例如,如果你想重定向到服务器上的另一个网页,那么你必须使用servlet。另一个重要的事情是servlet既可以在本地主机上运行,也可以在web浏览器上运行。