Sobes.tech
Junior

What actions need to be performed to create servlets?

sobes.tech AI

Answer from AI

  1. Create a class that implements the javax.servlet.Servlet interface or extends one of its subclasses (for example, javax.servlet.GenericServlet or javax.servlet.http.HttpServlet).
  2. Override the servlet lifecycle methods (such as init(), service(), destroy()). For HTTP servlets, it is common to override methods like doGet(), doPost(), etc., to handle the corresponding HTTP methods.
  3. Register the servlet in the web application. This can be done in one of the following ways:
    • Use the @WebServlet annotation in the servlet class, specifying the servlet name and URL patterns it will be accessible through.
    • Configure the servlet in the deployment descriptor web.xml using <servlet> and <servlet-mapping> elements.
  4. Package the servlet and other web application resources (HTML, JSP, static files) into a WAR file.
  5. Deploy the WAR file on an application server (such as Tomcat, WildFly, Jetty).

Example of an HTTP servlet class:

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

@WebServlet(name = "HelloWorldServlet", urlPatterns = {"/hello"})
public class HelloWorldServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html"); // Set content type
        PrintWriter out = response.getWriter(); // Get writer for response

        out.println("<html>");
        out.println("<head><title>Hello World</title></head>");
        out.println("<body>");
        out.println("<h1>Hello World!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

Example configuration in web.xml:

<!-- web.xml -->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>HelloWorldServletXml</servlet-name>
        <servlet-class>com.example.HelloWorldServlet</servlet-class> <!-- Full class name -->
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWorldServletXml</servlet-name>
        <url-pattern>/hello-xml</url-pattern> <!-- URL pattern -->
    </servlet-mapping>

</web-app>