A very basic difference:
- Servlet is
html in java
- JSP is
java in html
Other diff are:
- JSP is a webpage scripting language that can generate dynamic content while Servlets are Java programs that are already compiled which also creates dynamic web content
- Servlets run faster compared to JSP
- JSP can be compiled into Java Servlets
- It’s easier to code in JSP than in Java Servlets
- In MVC, jsp act as a view and servlet act as a controller.
- JSP are generally preferred when there is not much processing of data required. But servlets are best for use when there is more processing and manipulation involved.
- The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans. There is no such facility in servlets.
When a JSP is requested for the first time or when the webapp starts up, the servlet container will compile it into a class extending
HttpServlet and use it during the webapp's lifetime. You can find the generated source code in the server's work directory. In for example Tomcat, it's the
/work directory. On a JSP request, the servletcontainer will execute the compiled JSP class and send the generated output (usually just HTML/CSS/JS) through the webserver over network to the client side which in turn displays it in the webbrowser.
Servlet is an Java application programming interface (API) running on the server machine which can intercept on the requests made by the client and can generate/send a response accordingly. A well known example is the
HttpServlet which provides methods to hook on HTTP requests using the popular HTTP methods such as
POST. You can configure
HttpServlets to listen on a certain HTTP URL pattern, which is configureable in
web.xml, or more recently with Java EE 6, with
When a Servlet is requested for the first time or when the webapp starts up, the servlet container will create an instance of it and keep it in memory during webapp's lifetime. The same instance will be reused for every incoming request whose URL matches the servlet's URL pattern. You can access the request data by
HttpServletRequest and handle the response by
HttpServletResponse. Both objects are available as method arguments inside any of the overridden methods of
HttpServlet, such as