servlets and JSP are functionally equivalent. In fact, a JSP is (eventually) compiled into a servlet.
Having said that, the two technologies do best for different things. JSP are mostly HTML, possibly with a bit of Java mixed in. Servlets are mostly Java; to mix in HTML, you need ugly-looking out.println() statements.
* JSP are good for operations that are HTML-intensive.
* Servlets are good for operations that are Java-intensive.
A common usage pattern for web development is Model-View-Controller (MVC), which separates application components into three groups:
Model: Components holding application data. These are typically JavaBeans.
Views: Components that display information to the user. On the web, this means dynamically-generated HTML, so JSP work well here.
Controllers: Components that mediate between the model and the view, by (a) putting information entered by the user in the view into the model and (b) forwarding to the next view. Servlets do well for this, since these updates involve no HTML.
A typical web-interaction following this pattern would be:
1. User enters information into an HTML form and the form is submitted to a servlet.
2. This servlet retrieves the form information, and stores the changes in model JavaBeans (which typically save the data someplace permanent like a database).
3. The controller servlet automatically redirects to a view JSP.
4. The view JSP retrieves data from the model JavaBean and creates and HTML page to display the results.
Of course, this is only a sketch, and things can get much, much more complicated than this. My point is that both servlets and JSP have a legitimate role to play in Java web applications.
emma smith wrote: i know when we use HTML in java code then it is called Servlet and when we use java code in HTML then it is called JSP
That's a very simplistic, and not particularly accurate, way of looking at these concepts.
Servlets, as pointed out, are the Java objects that receive a request from a browser, and control how the response is generated. They could interact with model classes to read and write data to database, for example. They should not be used to emit HTML. That's a practice from about 15 years ago!
JSP, on the other hand, is the technology for generating HTML. They should not contain Java code. They are templates that a servlet uses to generate the HTML response. Again, I urge you to read this article and ask questions about anything that you do not understand.
This article is more advanced, but shows how JSPs and servlets work together to respond to a request.
The correct term is Java scriptlets (not Java scripts) and they have been obsolete for over 10 years. Modern JSPs -- any written after 2002 -- should not contain Java scriptlets. The JSTL and EL are the modern means to add dynamic data to a JSP.