Creating a Servlet

Learn how to create a servlet to map requests coming to localhost.

A servlet is a Java class that can take in a request and return a response. The input to the servlet is a request, and the output is a response. In a web application, we are talking about HTTP requests and HTTP responses. When something is typed in the address bar of a browser, it sends a request to the web server. The web server returns a response based on the request, and the browser displays the page.

So far, we have created a web.xml file that defines a welcome file, player.do, for our web application. When http://localhost:8080 is typed in the browser, the browser creates a GET request and sends it to http://localhost:8080/player.do. We want this request to be mapped to a servlet which sends some response back to the browser.

HttpServlet class

We will create a servlet class in src/main/java and call it PlayerServlet. A servlet class extends the HttpServlet class defined in javax.servlet.http.HttpServlet.

import javax.servlet.http.HttpServlet

public class PlayerServlet extends HttpServlet {

}

Mapping URL to servlet

The next step is to define a URL that will be used to access the servlet. We will assign /player.do to PlayerServlet. This can be done using the @WebServlet annotation. The urlPatterns property can be used to assign /player.do to our servlet as follows:

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.