TL;DR
- Servlet - html in java
- JSP - java in html
Details:
JSP (Java Server Pages) are pages that contain Java code that is put between HTML content in order to produce specific output. JSP page is compiled into Servlet at runtime, cached and presented for the end-user.
Servlet - is a Java class that produces specific output for the user. By using Java Servlet API, as a part of JEE, it responds to the requests in a specific way.
Why do people use both solutions instead of just one?
JSP can be considered more as a scripting language, hence it's easier/ faster to write and created
dynamic content.
JSP is compiled into Java Servlet (and then cached, but renewed whenever contents change).
JSP is used more as a View component, whereas Servlet is considered as Controller in the MVC (model-view-controller architecture).
Servlets by definition are faster than JSP, and should be used more for processing the data than displaying content.
// from http://www.caucho.com/resin-3.0/servlet/tutorial/helloworld/index.xtp
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class HelloServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();
out.println("Hello, world!");
out.close();
}
}
An example of a JSP mixing HTML and Java code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!doctype html>
<html>
<body>
Hello, world! Your IP address is <%= request.getRemoteAddr(); %>!
<%
if (request.getParameter("test") != null) {
%>
<p><strong>Something happened!</strong></p>
<%
}
%>
</body>
</html>