Junior — Middle
Could you explain what a Servlet is in the context of Java web development?
sobes.tech AI
Answer from AI
A Servlet is a Java class that runs on a server and handles HTTP requests from clients (such as browsers). It is part of Java EE (Jakarta EE) and is used to create dynamic web applications.
When a browser sends a request, the server forwards it to the Servlet, which performs the logic (for example, accessing a database, forming a response) and returns the result to the client.
Example of a simple Servlet in Java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
resp.getWriter().write("Hello from Servlet!");
}
}
This code responds to a GET request with plain text. The Servlet runs inside a servlet container (such as Tomcat), which manages its lifecycle.