Difference Between JSP and Servlets

JSP vs Servlets

A Servlet is a server side software component written in Java and runs in a compatible container environment known as a Servelt container (like Apache Tomcat). Servlets are predominantly used in implementing web applications that generate dynamic web pages. They can however generate any other content type like XML, text, images, sound clips, PDF, Excel files programmatically.

A Servlet written to generate some HTML may look like this:

public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter w = response.getWriter();

Date d = new Date();

The code above contains a mixture of HTML and Java source code. Such is not very readable and maintainable. JSP which stands for JavaServer Pages provides a better alternative. For example, the following is a fragment of JSP code that results in identical output:

<%@page import=”java.util.Date”%>
<%= new Date().toString() %>

Web page authors find JSP easier to write and maintain. JSP files are however translated into Servlets by a Servlet container at the time JSP files are first accessed. However, business logic writers find Servlets to be easier to work with.

A request received by a web application should trigger the execution of some business logic and then generate a resultant web page as the response. In modern day web applications, controlling the overall request processing cycle is mostly handed by Servlets. As the last stage in processing a request, such a Servlet generally hands over the responsibility of generating the dynamic HTML to a JSP.