简体   繁体   English

我是否正确理解了servlet的工作原理?

[英]Am I understanding the working of servlets correctly?

在此输入图像描述

So, yeah, I summed up all what I understood and drew a simple diagram. 所以,是的,我总结了所有我理解的东西,并绘制了一个简单的图表。

If I am not wrong, the servlet is the CGI (Common Gateway Interface) because the servelet is THE ONLY way you can get access to the resources on the server. 如果我没有错,那么servlet就是CGI(通用网关接口),因为servlet是唯一可以访问服务器上资源的方式。 So, in short, it is the COMMON GATEWAY. 简而言之,它就是COMMON GATEWAY。

The CONTAINER, like Apache Tomcat, is responsible for capturing the request sent by the user and sending it to the servlet. 与Apache Tomcat一样,CONTAINER负责捕获用户发送的请求并将其发送到servlet。

What the user perceives is a dynamic webpage called web app. 用户感知的是一个名为Web应用程序的动态网页。

This is what I learnt so far. 这是我到目前为止所学到的。

Have I learnt it correctly ? 我是否正确学习了它?

You are almost right. 你几乎是对的。 Here are typical workflows you can follow when working with plain servlets: 以下是使用普通servlet时可以遵循的典型工作流程:

Servlet renders page Servlet呈现页面

  1. Servlet container find servlet that matches request URL Servlet容器查找与请求URL匹配的servlet

  2. doGet() or doPost() is called depending on HTTP method requested 根据请求的HTTP方法调用doGet()doPost()

  3. Servlet does some processing Servlet做了一些处理

  4. Response (HTML, XML, JSON, image...) is generated directly in the servlet and sent to the client using getOutputStream() or getWriter() 响应(HTML,XML,JSON,image ...)直接在servlet中生成,并使用getOutputStream()getWriter()发送到客户端

     PrintWriter out = response.getWriter(); out.println("Hello World"); 

JSP handles request JSP处理请求

  1. Servlet container finds JSP matching request. Servlet容器查找JSP匹配请求。 You must understand that underneath each JSP is translated to some internal servlet 您必须了解每个JSP下面都会转换为某个内部servlet

  2. This JSP is interpreted. 解释此JSP。 Raw text is sent directly, Java code in scriptlets is executed 原始文本直接发送,执行scriptlet中的Java代码

  3. JSP ends, request is done JSP结束,请求完成

Servlet forwards to JSP Servlet转发到JSP

  1. Same as 1-3 in first scenario 与第一种情况中的1-3相同

  2. Servlet chooses JSP file and forwards to that JSP Servlet选择JSP文件并转发到该JSP

  3. JSP file is then evaluated, it has access to some context (request attributes, session) that was passed by servlet 然后评估JSP文件,它可以访问servlet传递的一些上下文(请求属性,会话)

     RequestDispatcher dispatcher = getServletContext() .getRequestDispatcher("foo.jsp"); dispatcher.forward(request, response); 

The last scenario is considered the best one as it does not mix business logic (servlet) and presentation (JSP). 最后一个场景被认为是最好的场景,因为它不混合业务逻辑(servlet)和表示(JSP)。

A Servlet processes a request and generates a response. Servlet处理请求并生成响应。

A JSP gets compiled into a servlet, so JSPs are a subset of servlets. JSP被编译成servlet,因此JSP是servlet的子集。

It is not a Servlet who looks for the correct JSP, this is the container's job. 寻找正确的JSP不是Servlet,这是容器的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM