且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我需要 Servlet 的映射或注释,而 JSP 不需要?

更新时间:2022-06-10 09:09:12

为什么我需要 Servlet 的映射或注解,而 JSP 不需要?

Why I need mapping or annotation for Servlet, but not for JSP?

正如@SotiriosDelimanolis 在上面的评论中指出的那样,实际情况并非如此.JSP 最终会变成一个 servlet,其行为与您自己定义的任何其他 servlet 一样.并且在定义 servlet 时,您还需要添加 URL 映射,以便将 URL 路径解析为可以响应对该 URL 的请求的 servlet.

As pointed out in the comment above from @SotiriosDelimanolis, that's not what actually happens. A JSP is eventually turned into a servlet and behaves like any other servlet you define on your own. And when you define a servlet you also need to add a URL mapping so that an URL path is resolved to a servlet that can respond to a request made for that URL.

唯一的区别是对于 JSP 文件,这种映射是由 servlet 容器隐式完成的.对于您定义的 servlet,您显然需要定义自己的映射,因为服务器无法知道您想在您自己的应用程序中对 servlet 做什么.

The only difference is that for JSP files this mapping is done implicitly by the servlet container. For the servlets you define, you obviously need to define your own mapping because the server can't know what you want to do with the servlet in your own application.

规范 表示以下内容(强调我的):

The specifications says the following (emphasis mine):

Web 组件可以是 servlet 或 JSP 页面.web.xml 部署描述符中的 servlet 元素用于描述这两种类型的 Web 组件.JSP 页面组件通过使用隐式 .jsp 扩展映射在部署描述符中隐式定义,或通过使用 jsp-group 元素显式定义.

A web component is either a servlet or a JSP page. The servlet element in a web.xml deployment descriptor is used to describe both types of web components. JSP page components are defined implicitly in the deployment descriptor through the use of an implicit .jsp extension mapping, or explicitly through the use of a jsp-group element.

[...] JSP 页面转换为实现类和部署信息.部署信息指示所需的支持类以及JSP 页面的原始 URL 路径与该页面的 JSP 页面实现的 URL 的 URL 之间的映射.

[...] JSP page translated into an implementation class plus deployment information. The deployment information indicates support classes needed and the mapping between the original URL path to the JSP page and the URL for the JSP page implementation class for that page.

因此,基本上,您的 JSP 被转换为 servlet,并创建了从原始 JSP 页面位置路径到由此生成的 servlet 的映射.

So basically, your JSP is translated into a servlet, and a mapping is created from your original JSP page location path to the servlet thus generated.

实际上并未执行 JSP.执行的是从 JSP 生成的 servlet.您必须意识到提供 JSP 是为了方便.如果您想从 servlet 生成 HTML,您必须执行一大堆 out.write("<html>>>>>>>>>>>>>>");out.write("\r\n"); 等等,用于整个 HTML 页面.这不仅非常容易出错,而且你会发疯.因此,提供 JSP 的选项与幕后完成的工作相结合,使其全部工作.

The JSP is not actually executed. What's executed is the servlet generated from the JSP. You have to realize that JSPs are provided for convenience. If you want to generate HTML from a servlet you have to do a whole bunch of out.write("<html>"); out.write("\r\n"); and so on, for your entire HTML page. It's not only very error prone, but you will go insane doing so. Thus, the option of providing an JSP combined with the things done behind the scene to make it all work.