You are on page 1of 8

What is a Servlet?

• HTML code in a Java class


• Servlets handle controller part in
MVC (Model-View-Controller) pattern
• A servlet is a Java-based web application server
extension program that implements a standard API.
• Servlets are used in conjunction with JSPs in MVC
• Servlets can maintain state across many server
transactions by using HTTP Cookies, session variables
or URL Rewriting by Servlet Sessions.
A simple Servlet class
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" + "<html>\n" + "<head><title>Hello World
</title></head>\n" + "<body>\n" + "<h1>Hello World </h1> \n“
+"</body></html>“ ) ;
}
}
What is JSP?
• Java code in HTML & XML
• JSP handles view part in MVC
• A text-based document capable of returning
both static and dynamic content to a client browser
• Static content
– HTML, XML, Text
• Dynamic content
– Java code
– Displaying properties of JavaBeans
– Invoking business logic defined in Custom tags
What do you mean by Static & Dynamic
Contents?
● Static contents
– Typically static HTML page
– Same display for everyone
● Dynamic contents
– Contents is dynamically generated based on conditions
– Conditions could be
• User identity
• Time of the day
• User entered values through forms and selections
A Simple JSP Page
• (Blue: static, Red: Dynamic contents)
<html>
<body>
Hello World!
<br>
Current time is <%= new java.util.Date() %>
</body>
</html>
Output
Difference
Do I have to Use JSP over Servlet
or vice-versa?
• No, you want to use both leveraging the strengths of
each technology
– Servlet's strength is “controlling and dispatching”
– JSP's strength is “displaying”
• In a typically production environment, both servlet
and JSP are used in MVC pattern
– Servlet handles controller part
– JSP handles view part

You might also like