Category: React • Beginner
Published on 17 Mar 2026
Explanation
A Java Servlet is a server-side Java class that handles HTTP requests and responses. It runs inside a servlet container such as Apache Tomcat.
Code Example
public class HelloServlet extends
HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello from Servlet");
}
}
Explanation
Servlets can process form data sent from a client. In this example, the servlet reads username and password from the HTTP request.
Code Example
protected void doPost(
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String pass = request.getParameter("pass");
response.getWriter().println("
Login successful for " + username);
}
Explanation
Servlets can redirect users to another URL using the sendRedirect() method of HttpServletResponse.
Code Example
protected void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
response.sendRedirect("https://example.com");
}
}
Explanation
Servlets can read HTTP headers from the request object. This is useful for identifying browsers or client information.
Code Example
public class HeaderServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String agent = request.getHeader("User-Agent");
response.getWriter().println(agent);
}
}
Explanation
Servlets can manage cookies using the Cookie class. Cookies are often used to store session or user information.
Code Example
protected void doGet(HttpServletRequest
request, HttpServletResponse response)
throws IOException {
Cookie cookie = new Cookie("user", "hackforge");
response.addCookie(cookie);
response.getWriter().println("Cookie added");
}
}