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>