As a newbie programmer with java web world you will be facing this dilemma identifying difference between JSP and Servlet that experience programmer talk about or you read it in books, so let’s get started I’m going briefly over what servlet and JSP gives you individually and their pros and cons.
Java Server Pages JSP “java in html”
JSP is nothing but a webpage scripting language that can generate content, if we program taking in consideration MVC we can say that JSP role in MVC world is View where you can write template text, HTML, CSS and many other client side scripting that you can imagine doing while writing code for webpages.
When you request a JSP page for the first time from the server or when a web page starts up, in the background servlet container will compile it into a class which will extend HttpServlet and then this will be used during the webpage lifetime, this code can be found in server working directory for example if you have Tomcat server this Servlet can be found in /Work directory.
To summarise this in couple of bullet points what it can do.
- It’s webpage Scripting language that can generate dynamic content
- JSP run slower than Servlet
- JSP can be compiled into Servlets
- Easy to code than Servlet
- In MVC world JSP acts as View
Servlet is html in java
Servlet is a Java Application Programming Interface run on server that can generate code according to client request, a clear example would be HttpServlet, which provides method to hook on HTTP request using HTTP GET and POST request, and this can be found in web.xml but in recent Java after EE 6 can be found in @WebServelet.
When a Servlet is requested for the first time from server, the Servlet container will create an instance of it and keep it in memory during the webpage lifetime. The same instance will be reused for incoming request, you will be able to access the data request by HttpServletREquest and handle the responses by HttpSerlvletResponse. Both object are available as method argument as overridden method of HttpServlet for example doGet() and doPost().
To summarise this in couple of bullet points what it can do.
- Servlet is a lot faster than JSP
- Servlets are java program that are already compiled
- It’s not easy to code in Servlet JSP is much easier to code than Servlet
- In MVC world Servlet act as Controller
- Since Servlet act as Controller it make more sense to use it when we have a lot of CRUD going on.
These were some of key points between JSP and Servlet, there is many other difference these are not the only one but with this article I tried to give you most important key points that set them apart from each other.
1 Comment to Difference between Servlet and JSP