Servlet is a piece of code sitting at the server side and waiting for the information from the browsers. It then processes the information and possibly gives feedback to the browsers.

The servlet I’m talking about here is implemented using the Java langauge and runs in Tomcat web server. Long story short, a typical servlet example written in Java is as follows:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class One extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        java.util.Date today = new java.util.Date();
        out.println("<html>");
        out.println("<h1>Hello world</h1>");
        out.println("<h2>today is:" + today + "</h2>");
        out.println("</html>");
    }
}
#=> prints 'Hello world' and the current date.

Put the above code into your favorite text editor and save as a .java file, e.g. One.java. Take the servlet-api.jar file from the lib directory of the installed tomcat home directory and put it in the same directory as One.java, then run the following command in the command line:

javac -cp servlet-api.jar One.java

After that, you should get a file called One.class in your working directory. Put the One.class in the following created directory in the tomcat home:

$tomcat_home/webapps/one/WEB-INF/classes/

Create and put a web.xml file in the $tomcat_home/webapps/one/WEB-INF/. The web.xml should look as follows:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
 <servlet>
 <servlet-name>MyServlet</servlet-name>
 <servlet-class>One</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>MyServlet</servlet-name>
 <url-pattern>/hello</url-pattern>
 </servlet-mapping>
</web-app>
#=> pay attention to the <servlet> part.

Now what you need to do is start tomcat and type the following address in the location area of the browser and enjoy your accomplishment :coffee:.

http://localhost:8080/hello

All the above is the short story behind the servlet and more infomation can be obtained from the book :book: Professional Java for Web Applications by Nicholas S. Williams.