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();
w.write(“<html>”);
w.write(“<body>”);
Date d = new Date();
w.write(d.toString());
w.write(“</body>”);
w.write(“</html>”);
}
}
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”%>
<html>
<body>
<%= new Date().toString() %>
</body>
</html>
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.