Servlet and JSP

// Import required java libraries
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {
// Do required initialization
message = "Hello World";

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set response content type

// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");

public void destroy() {
// do nothing.
<%-- JSP comment --%>
<%out.print("Hello, Sample JSP code");%>
<% Java code here %>
Java code here
<% if (doodad) {%>
<% } else { %>
<% } %>

To choose between servlet and JSP I use a simple rule: if the page contains more HTML code than java code, go for JSP, otherwise, just write a servlet. In general, that translates roughly to: use JSPs for content presentation and servlets for control, validation, etc. It's easier to organize and structure your code inside a servlet since it uses the plain java class syntax. JSPs tend to be more monolithic, although it's possible to create methods inside them.

Difference Between JSP and Servlet

Servlet Life Cycle



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store