简体   繁体   English

JSP或Servlet PrintWriter

[英]JSP or Servlet PrintWriter

I recently began implementing java into my website but I've been reading that the method: 我最近开始在自己的网站中实现Java,但我一直在阅读该方法:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();

        out.println("<html>");
        //code
        out.println("</html>");
        out.close();
    }

Is outdated and rarely used due to jsp. 已过时,由于jsp很少使用。 What are the benefits of doing one versus the other? 与另一人相比,这样做有什么好处?

The advantage of using JSP over pure servlets is that it is more convenient to write (and to modify) regular HTML than to have plenty of out.println statements that generate the HTML. 与纯servlet相比,使用JSP的优势在于,与具有大量生成HTML的out.println语句相比,编写(和修改)常规HTML更为方便。 With JSP, you can mix Java code freely with your HTML code (using tags JSP provides like <%= %> ). 使用JSP,您可以将Java代码与HTML代码自由混合(使用JSP提供的标记,例如<%= %> )。 Your JSP page ultimately compiles to a servlet, the servlet runs, and the response is sent back to the browser. 您的JSP页面最终将编译为一个servlet,该servlet运行,并将响应发送回浏览器。

Pure Servlet: 纯Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<body>")
    out.println("<p>The date is: " + (new Java.util.date()).toLocaleString() +"</p>");
    out.println("</body>")
    out.println("</html>");
    out.close();
}

JSP: JSP:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  ....
  <body>
      <p>The date is: <%= (new Java.util.date()).toLocaleString() %></p> //mixing HTML and Java
  </body>
</html>

Technically you can write presentation and business logic in both jsp and servlets. 从技术上讲,您可以在jsp和servlet中编写表示和业务逻辑。 It's widely considered a good practice to to implement the MVC pattern in your webapp, so you want to implement the view in the JSP, use the servlets as the controller and EJBs for the model. 在Web应用程序中实现MVC模式被广泛认为是一种好习惯,因此您想在JSP中实现视图,使用servlet作为模型的控制器和EJB。 Generating the html with your servlet break this separation, that's why it's generally to avoid. 用servlet生成html打破了这种分离,这就是为什么通常要避免的原因。

I'm not aware of any benefit from generating the html in a servlet. 我不知道在servlet中生成html有什么好处。

Servlet intended for Control and Business Logic. 用于控制和业务逻辑的Servlet。 JSP intended for Presentation Logic. JSP用于表示逻辑。

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

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