A Servlet is an java object that receives a HTTP request and generates a HTTP response based on that request.
A Java servlet is:
Servlets are the Java counterpart to non-Java dynamic Web content technologies such as:
They are not tied to a specific client-server protocol, but are most often used with the HTTP protocol. Therefore, the word “Servlet” is often used in the meaning of “HTTP Servlet”.
Servlets are best suited for:
Servlets can maintain state in session variables across many server transactions by using HTTP cookies, or URL rewriting.
Servlets are most often used to
Note that HttpServlet is a subclass of GenericServlet, an implementation of the Servlet interface. The service() method dispatches requests to methods doGet(), doPost(), doPut(), doDelete(), etc., according to the HTTP request.
Here is a simple servlet that just generates HTML.
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;
//or use
//import java.io.*;
//import javax.servlet.*;
//import javax.servlet.http.*;
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>");
}
}
With a enterprise bean:
The myServlet class uses dependency injection to obtain a reference to the Bean MyBean. The javax.ejb.EJB (@EJB) annotation is added to the declaration of the private member variable myBean, which is of type MyBean.
In this case, MyBean exposes a local, no-interface view, so the enterprise bean implementation class is the variable type.
@WebServlet
public class myServlet extends HttpServlet {
@EJB
MyBean myBean;
...
}
Note the annotation @webservlet (javax.servlet.annotation.WebServlet)