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:
- The client sends an HTTP request to the server.
- The web server (e.g., Apache Tomcat) receives the request and forwards it to the appropriate servlet.
- The servlet processes the request in the
doGetordoPostmethod, performing necessary logic (such as database access, HTML generation). - 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.