Sobes.tech
Middle

What are servlets? How do they work?

sobes.tech AI

Answer from AI

Servlets are Java components that run on a server and handle HTTP requests from clients (such as browsers). They are part of Java EE (now Jakarta EE) and are used to create web applications.

How servlets work:

  1. The client sends an HTTP request to the server.
  2. The web server (e.g., Apache Tomcat) receives the request and forwards it to the appropriate servlet.
  3. The servlet processes the request in the doGet or doPost method, performing necessary logic (such as database access, HTML generation).
  4. The servlet forms an HTTP response and sends it back to the client.

Example of a simple servlet:

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("<h1>Hello, world!</h1>");
    }
}

Thus, servlets enable the creation of dynamic web pages and handle user requests on the server.