What is a servlet?

A servlet is a Java class used to extend the capabilities of servers that host server-side web applications. Servlets can respond to requests and generate responses. The base class for all servlets is javax.servlet.GenericServlet, defines a generic, protocol-independent servlet.

By far the most common type of servlet is an HTTP servlet. This type of servlet is used for handling HTTP requests and generating HTTP responses. An HTTP servlet is a class that extends the javax.servlet.http.HttpServlet class, which is a subclass of javax.servlet.GenericServlet.

A servlet must implement one or more methods to respond to specific HTTP requests. These methods are overridden from the parent HttpServlet class. As can be seen in the following table, these methods are named in such a way that knowing which one to use is intuitive:

HTTP request

HttpServlet method

GET

doGet(HttpServletRequest request, HttpServletResponse response)

POST

doPost(HttpServletRequest request, HttpServletResponse response)

PUT

doPut(HttpServletRequest request, HttpServletResponse response)

DELETE

doDelete(HttpServletRequest request, HttpServletResponse response)

 

Each of these methods takes the same two parameters, namely an instance of a class implementing the javax.servlet.http.HttpServletRequest interface and an instance of a class implementing javax.servlet.http.HttpServletResponse. These interfaces will be covered in detail later in this chapter.

Application developers never call the preceding methods directly, they are called automatically by the application server whenever it receives the corresponding HTTP request.

Of the four methods listed previously, doGet() and doPost() are, by far, the most commonly used.

An HTTP GET request is generated whenever a user types the servlet's URL in the browser, when a user clicks on a link pointing to the servlet's URL, or when a user submits an HTML form using the GET method where the form's action points to the servlet's URL. In any of these cases, the code inside the servlet's doGet() method gets executed.

An HTTP POST request is typically generated when a user submits an HTML form using the POST method and an action pointing to the servlet's URL. In this case, the servlet's code inside the doPost() method gets executed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.201.217