SemperAmbroscus
SemperAmbroscus

Reputation: 1388

JSP or Servlet PrintWriter

I recently began implementing java into my website but I've been reading that the method:

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. What are the benefits of doing one versus the other?

Upvotes: 0

Views: 2533

Answers (3)

Gundamaiah
Gundamaiah

Reputation: 786

Servlet intended for Control and Business Logic. JSP intended for Presentation Logic.

Upvotes: 0

Tot&#242;
Tot&#242;

Reputation: 1854

Technically you can write presentation and business logic in both jsp and servlets. 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. Generating the html with your servlet break this separation, that's why it's generally to avoid.

I'm not aware of any benefit from generating the html in a servlet.

Upvotes: 0

Akinkunle Allen
Akinkunle Allen

Reputation: 1309

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. With JSP, you can mix Java code freely with your HTML code (using tags JSP provides like <%= %>). Your JSP page ultimately compiles to a servlet, the servlet runs, and the response is sent back to the browser.

Pure 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:

<%@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>

Upvotes: 2

Related Questions