Question

(Rewritten for reopening:)

What are relative advantages of Servlets over JSP, or vice versa?

Might JSP be preferred because it is easy to put code inside JSP, or Servlets because with them code can be separated from view? Are there other considerations?

Any information regarding this will be immensely helpful.

Was it helpful?

Solution

The main advantage of JSP is that it's are easier to code and to read when you are creating a dynamic HTML front-end.

That's because you write mainly HTML and in some places embed Java code.

In a servlet you would have to invert the logic, ie, write java code and print HTML.

That's because in the presentation layer most code is HTML/JS.

On the other hand, business logic is in most part Java code, so in that case it's better to use Servlets or POJOs (plain, old Java objects).

EDIT: there's no performance difference since JSP code, as such, is never run, it's converted to a servlet. Only the first time you run the JSP after it has been changed, it takes a little longer to run because it has to be converted to servlet.

Compare a simple "Hello World" program in JSP vs servlet:

JSP:

<html>
        <head><title>Hello World JSP Page.</title></head>
        <body>
                <font size="10"><%="Hello World!" %></font>
        </body>
</html>

Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

    public class HelloWorld extends HttpServlet{ 
      public void doGet(HttpServletRequest request, 
      HttpServletResponse response)
      throws ServletException,IOException{
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.println("<html>");
      pw.println("<head><title>Hello World</title></title>");
      pw.println("<body>");
      pw.println("<h1>Hello World</h1>");
      pw.println("</body></html>");
      }
    }
Licensed under: CC-BY-SA with attribution
scroll top