Understanding Servlet

Servlet is JAVA class that extend the capabilities of servers to enhance the functionality of web applications.

It provides a server-side component model that is both platform-independent and scalable.

It operates on the server side, responding to client requests and generating dynamic content.


Example of Servlet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().println("Hello, Servlets!");
    }
}
cs

In this example, we create a class HelloServlet that extends HttpServlet.

The doGet method handels HTTP GET requests and it is simply writes "Hello Servlets!" to the response.


-Mapping Servlets in the Deplyment Descriptor(web.xml)

1
2
3
4
5
6
7
8
<servlet>
    <servlet-name>HelloServlet</servlet-name>
    <servlet-class>com.example.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloServlet</servlet-name>
    <url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
cs

This XML configuration informs the servlet container about the servlet's name, class, and URL pattern.


-Servlet Lifecycle

Servlets undergo a lifecycle that includes initialization, service, and destruction phases.

The init method is called during initialization, service method handles requests, and destroy method is called before the servlet is taken out of service.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
public void init() throws ServletException {
    // Initialization logic
}
 
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Request handling logic
}
 
@Override
public void destroy() {
    // Cleanup logic
}
cs


-Servlet and Form Handling

Servlet plays a pivotal role in processing HTML forms.

Let's take a example.

1
2
3
4
5
6
7
<!-- index.html -->
<form action="/FormServlet" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>
    <br>
    <input type="submit" value="Submit">
</form>
cs

1
2
3
4
5
6
7
8
@WebServlet("/FormServlet")
public class FormServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        response.getWriter().printf("Hello, %s!", name);
    }
}
cs