Java Servlets allow a software developer to add dynamic content to a web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML.

The simple servlet below shows how a servlet looks like:

import javax.servlet.*;
public class SampleServlet implements Servlet {
  private ServletConfig config;

  public void init (ServletConfig configthrows ServletException {
    this.config = config;

  public void destroy() {} // do nothing
  public ServletConfig getServletConfig() {
    return config;
  public String getServletInfo() {
    return "A Simple Servlet";
  public void service (ServletRequest req, ServletResponse res
  throws ServletException, IOException  {
      res.setContentType"text/html" );
      // Always set the Content Type before data is printed
      PrintWriter out = res.getWriter();
      out.println"<html>" );
      out.println"<head>" );
      out.println"<title>A Sample Servlet</title>" );
      out.println"</head>" );
      out.println"<body>" );
      out.println"<h1>A Sample Servlet</h1>" );
      out.println"</body>" );
      out.println"</html>" );

Parent Category: Java EE Tips