Engineering Full Stack Apps with Java and JavaScript
While servlets can be considered Java classes that contain some html code, JSPs can be considered as html pages (except for the .jsp extension and some extra lines) with some java inside.
If we use servlets, we should use a print statement for sending every line of the html code to the client.
JSP File
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Simple JSP</title>
</head>
<body>
<h1>This is a simple JSP file</h1>
<p>
This is a simple JSP File.
<br> This JSP file does not contain any java code.
</p>
</body>
</html>
Servlet File
The above example JSP contents may be written using servlets as:
out.write("\r\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
out.write("<html>\r\n");
out.write("<head>\r\n");
out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\r\n");
out.write("<title>Simple JSP</title>\r\n");
out.write("</head>\r\n");
out.write("<body>\r\n");
out.write("Simple JSP\r\n");
out.write("</body>\r\n");
out.write("</html>");
If you had a lot of html code, as in the case of most complex projects, you would have to write a lot of print statements with servlets. If you see the source of any complex web page using the view source feature of your browser, you will see lot of lines of html, javascript, css etc. If we use servlets to create such a page, it would take a lot of time as we need to write a print statement for those every line. I just right clicked the javajee.com home page and checked the number of lines to find around 1000 lines.
Using JSPs will help us use standard web design tools for HTML, Javascript and CSS. We will not be able to use the help of any web design tools easily if we use servlets.
Usually web design tasks using html, javascript, css etc. are done by designers whereas writing java logic is done by developers. Web designers can design using JSP pages and Java developers can develop servlets and/or tags and can be reused. However with the use of only servlets, we will need even designers to know java programming language.
As a simple practice, if you have lot of html code than java then use JSPs and if you have more java logic, then use servlets.