Java 什么时候使用 JSP,什么时候使用 Servlet?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/101579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:18:29  来源:igfitidea点击:

When do you use a JSP and when a Servlet?

javajspservlets

提问by Antony

I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transaction is known to us. It then updates the database to reflect the status. This is all done without any interaction with the customer.

我有一个应用程序将客户发送到另一个站点来处理付款。客户之外的另一个站点调用我们服务器上的一个页面,让我们知道付款的状态。被调用的页面检查支付应用程序提供的参数,并检查我们是否知道交易。然后更新数据库以反映状态。这一切都是在与客户没有任何互动的情况下完成的。

I have personally chosen to implement this functionality as a JSP since it is easier to just drop a file in the file system than to compile and package the file and then to add an entry into a configuration file.

我个人选择将这个功能作为 JSP 来实现,因为在文件系统中放置一个文件比编译和打包文件然后在配置文件中添加一个条目更容易。

Considering the functionality of the page I would presume that a servlet would be the preferred option. The question(s) are:

考虑到页面的功能,我认为 servlet 将是首选选项。问题是:

  • Is my presumption correct?
  • 我的推测正确吗?
  • Is there a real reason to use a servlet over a JSP?
  • 是否有真正的理由在 JSP 上使用 servlet?
  • What are those reasons?
  • 这些原因是什么?
  • 采纳答案by s3v1

    A JSP is compiled to a servlet the first time it is run. That means that there's no real runtime difference between them.

    JSP 在第一次运行时被编译成一个 servlet。这意味着它们之间没有真正的运行时差异。

    However, most have a tradition to use servlets for controllers and JSPs for views. Since controllers are just java classes you can get full tool support (code completion etc.) from all IDEs. That gives better quality and faster development times compared to JSPs. Some more advanced IDE's (IntelliJ IDEA springs to mind) have great JSP support, rendering that argument obsolete.

    然而,大多数人都有将 servlet 用于控制器和 JSP 用于视图的传统。由于控制器只是 Java 类,因此您可以从所有 IDE 获得完整的工具支持(代码完成等)。与 JSP 相比,这提供了更好的质量和更快的开发时间。一些更高级的 IDE(想到 IntelliJ IDEA)有很好的 JSP 支持,从而使该论点过时了。

    If you're making your own framework or just making it with simple JSPs, then you should feel free to continue to use JSPs. There's no performance difference and if you feel JSPs are easier to write, then by all means continue.

    如果您正在制作自己的框架或只是使用简单的 JSP 制作它,那么您应该可以继续使用 JSP。没有性能差异,如果您觉得 JSP 更容易编写,那么一定要继续。

    回答by Bill the Lizard

    JSPs should be used in the presentation layer, servlets for business logic and back-end (usually database layer) code.

    JSP 应该用于表示层,servlet 用于业务逻辑和后端(通常是数据库层)代码。

    I don't know any reason why you can't use a JSP as you describe (it gets compiled to a servlet by the containter anyway), but you're right, the preferred method is to make it a servlet in the first place.

    我不知道为什么您不能像您描述的那样使用 JSP(无论如何它都会被容器编译为 servlet),但是您是对的,首选方法是首先使其成为 servlet .

    回答by sblundy

    Yeah, this should be a servlet. A JSP may be easier to develop, but a servlet will be easier to maintain. Just imagine having to fix some random bug in 6 months and trying to remember how it worked.

    是的,这应该是一个servlet。JSP 可能更容易开发,但 servlet 将更容易维护。试想一下,必须在 6 个月内修复一些随机错误并尝试记住它是如何工作的。

    回答by Steve Moyer

    JSP's are essentially markup that automatically gets compiled to a servlet by the servlet container, so the compile step will happen in both instances. This is why a servlet container that supports JSP must have the full JDK available as opposed to only needing the JRE.

    JSP 本质上是由 servlet 容器自动编译为 servlet 的标记,因此编译步骤将在这两种情况下发生。这就是为什么支持 JSP 的 servlet 容器必须有完整的 JDK,而不是只需要 JRE。

    So the primary reason for JSP is to reduce the amount of code required to render a page. If you don't have to render a page, a servlet is better.

    因此,JSP 的主要原因是减少呈现页面所需的代码量。如果您不必呈现页面,那么 servlet 会更好。

    回答by Alexandre Victoor

    Most java applications nowadays are build on the MVC pattern... In the controller side (servlet) you implement business logic. The servlet controller usually forward the request to a jsp that will generate the actual html response (the View in MVC). The goal is to separate concerns... Thousands of books have been written on that subject.

    现在大多数 Java 应用程序都是建立在 MVC 模式上的……在控制器端(servlet)你实现业务逻辑。servlet 控制器通常将请求转发到将生成实际 html 响应(MVC 中的视图)的 jsp。目标是分离关注点……关于这个主题已经写了数千本书。

    回答by JeeBee

    JSPs: To present data to the user. No business logic should be here, and certainly no database access.

    JSP:向用户呈现数据。这里不应该有业务逻辑,当然也没有数据库访问。

    Servlets: To handle input from a form or specific URL. Usually people will use a library like Struts/Spring on top of Servlets to clear up the programming. Regardless the servlet should just validate the data that has come in, and then pass it onto a backend business layer implementation (which you can code test cases against). It should then put the resulting values on the request or session, and call a JSP to display them.

    Servlets:处理来自表单或特定 URL 的输入。通常人们会在 Servlet 之上使用像 Struts/Spring 这样的库来清理编程。无论如何,servlet 应该只验证传入的数据,然后将其传递到后端业务层实现(您可以针对它编写测试用例)。然后它应该将结果值放在请求或会话上,并调用 JSP 来显示它们。

    Model: A data model that holds your structured data that the website handles. The servlet may take the arguments, put them into the model and then call the business layer. The model can then interface with back-end DAOs (or Hibernate) to access the database.

    模型:保存网站处理的结构化数据的数据模型。servlet 可以接受参数,将它们放入模型中,然后调用业务层。然后该模型可以与后端 DAO(或 Hibernate)交互以访问数据库。

    Any non-trivial project should implement a MVC structure. It is, of course, overkill for trivial functionality. In your case I would implement a servlet that called a DAO to update the status, etc, or whatever is required.

    任何重要的项目都应该实现 MVC 结构。当然,对于微不足道的功能来说,这太过分了。在您的情况下,我将实现一个调用 DAO 的 servlet 来更新状态等,或任何需要的东西。

    回答by user16120

    JSPs are a shortcut to write a servlet. In fact they are translated to servlet java code before compilation. (You can check it under some tomcat subdir wich I don't remember the name).

    JSP 是编写 servlet 的捷径。事实上,它们在编译之前被翻译成 servlet java 代码。(你可以在一些我不记得名字的 tomcat 子目录下检查它)。

    To choose between servlet an JSP I use a simple rule: if the page contains more html code than java code, go for JSP, otherwise just write a servlet. In general that translates roughly to: use JSPs for content presentation and servlets for control, validation, etc.

    要在 servlet 和 JSP 之间进行选择,我使用一个简单的规则:如果页面包含的 html 代码多于 java 代码,则选择 JSP,否则只需编写一个 servlet。一般而言,大致翻译为:使用 JSP 进行内容呈现,使用 servlet 进行控制、验证等。

    Also, Its easier to organize and structure your code inside a servlet, since it uses the plain java class syntax. JSPs tend to be more monolithic, although its possible to create methods inside then.

    此外,在 servlet 内组织和构建代码更容易,因为它使用纯 java 类语法。JSP 往往更加单一,尽管它可以在内部创建方法。

    回答by Rudi Adianto

    In an MVC architecture, servlets are used as controller and JSPs as view. But both are technically the same. JSP will be translated into servlet, either in compile time (like in JDeveloper) or when accessed for the first time (like in Tomcat). So the real difference is in the ease of use. I'm pretty sure that you'll have a hard time rendering HTML page using servlet; but opposite to common sense, you'll actually find it pretty easy to code even a fairly complex logic all inside JSP (with the help of some prepared helper class maybe). PHP guys do this all the time. And so they fall into the pitfall of creating spaghetti codes. So my solution to your problem: if you found it easier to code in JSP and it wouldn't involve too many code, feel free to code in JSP. Otherwise, use servlet.

    在 MVC 架构中,servlet 用作控制器,而 JSP 用作视图。但两者在技术上是相同的。JSP 将在编译时(如在 JDeveloper 中)或在第一次访问时(如在 Tomcat 中)转换为 servlet。所以真正的区别在于易用性。我很确定您将很难使用 servlet 呈现 HTML 页面;但与常识相反,您实际上会发现在 JSP 中编写甚至相当复杂的逻辑都非常容易(可能借助一些准备好的帮助程序类)。PHP 家伙一直这样做。因此,他们陷入了创建意大利面条式代码的陷阱。所以我对您的问题的解决方案是:如果您发现在 JSP 中编码更容易并且不会涉及太多代码,请随意在 JSP 中编码。否则,使用 servlet。

    回答by Alan

    Agreed with all the points above about the differences between JSPs and Servlets, but here are a couple additional considerations. You write:

    同意以上关于 JSP 和 Servlet 之间差异的所有观点,但这里有一些额外的考虑因素。你写:

    I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transaction is known to us. It then updates the database to reflect the status. This is all done without any interaction with the customer.

    我有一个应用程序将客户发送到另一个站点来处理付款。客户之外的另一个站点调用我们服务器上的一个页面,让我们知道付款的状态。被调用的页面检查支付应用程序提供的参数,并检查我们是否知道交易。然后更新数据库以反映状态。这一切都是在与客户没有任何互动的情况下完成的。

    Your application is consuming the payment service of another application. Your solution is fragile because if the payment service in the other application changes, that breaks your JSP page. Or if you want to change your application's payment policies, then your page will have to change. The short answer is that your application should be consuming the application's payment service via a web service. Neither a servlet nor a JSP page is appropriate place to put your consumption logic.

    您的应用程序正在使用另一个应用程序的支付服务。您的解决方案很脆弱,因为如果其他应用程序中的支付服务发生变化,就会破坏您的 JSP 页面。或者,如果您想更改应用程序的付款政策,则必须更改您的页面。简短的回答是您的应用程序应该通过 Web 服务使用应用程序的支付服务。servlet 和 JSP 页面都不是放置消费逻辑的合适位置。

    Second, along those lines, most usages of servlets/JSP pages in the last few years have been put inside the context of a framework like Spring or Struts. I would recommend Spring, as it offers you the full stack of what you need from the server pages to web service gateway logic to DAOs. If you want to understand the nuts and bolts of Spring, I would recommend Spring in Action. If you need to understand better how to tier an enterprise architecture written in a language like Java (or C#), I would recommend Fowler's Patterns of Enterprise Application Architecture.

    其次,沿着这些路线,过去几年 servlets/JSP 页面的大多数用法都放在 Spring 或 Struts 等框架的上下文中。我会推荐 Spring,因为它为您提供了从服务器页面到 Web 服务网关逻辑再到 DAO 所需的完整堆栈。如果您想了解 Spring 的具体细节,我会推荐Spring in Action。如果您需要更好地了解如何对用 Java(或 C#)等语言编写的企业架构进行分层,我会推荐 Fowler 的企业应用程序架构模式

    回答by Jay

    I know this isn't the popular answer today, but: When I'm designing an app from scratch, I always use JSPs. When the logic is non-trivial, I create ordinary Java classes to do the grunt work that I call from the JSP. I've never understood the argument that you should use servlets because, as pure Java classes, they are more maintainable. A JSP can easily call a pure Java class, and of course an ordinary Java class is just as maintainable as any servlet. It's easier to format a page in a JSP because you can put all the markup in-line instead of having to write a bunch of println's. But the biggest advantage of JSPs is that you can just drop them in a directory and they are directly accessible: you don't need to mess with setting up relationships between the URL and the class file. Security is easily handled by having every JSP begin with a security check, which can be a single call statement, so there's no need to put security into a dispatch layer.

    我知道这不是今天流行的答案,但是:当我从头开始设计应用程序时,我总是使用 JSP。当逻辑不重要时,我会创建普通的 Java 类来完成从 JSP 调用的繁重工作。我一直不明白您应该使用 servlet 的论点,因为作为纯 Java 类,它们更易于维护。JSP 可以轻松调用纯 Java 类,当然普通 Java 类与任何 servlet 一样可维护。在 JSP 中格式化页面更容易,因为您可以将所有标记放在内联,而不必编写一堆 println 。但是 JSP 的最大优点是您可以将它们放在一个目录中并且可以直接访问它们:您不需要在 URL 和类文件之间设置关系。

    The only reason I can see to use a servlet is if you need a complex mapping between URLs and the resulting execution class. Like, if you want to examine the URL and then call one of many classes depending on session state or some such. Personally I've never wanted to do this, and apps I've seen that do do it tend to be hard to maintain because before you can even begin to make a change you have to figure out what code is really being executed.

    我认为使用 servlet 的唯一原因是您是否需要 URL 和结果执行类之间的复杂映射。就像,如果您想检查 URL,然后根据会话状态或类似状态调用许多类之一。就我个人而言,我从来不想这样做,而且我见过的应用程序这样做往往很难维护,因为在你甚至可以开始进行更改之前,你必须弄清楚真正执行的是什么代码。