Junior
What steps are needed to create servlets?
sobes.tech AI
Answer from AI
- Create a class that implements the
javax.servlet.Servletinterface or extends one of its subclasses, such asjavax.servlet.http.HttpServlet. - Override necessary methods like
init(),service(),destroy(), and forHttpServlet—doGet(),doPost(), and otherdo*methods. - Compile the servlet class.
- Register the servlet in the deployment descriptor
web.xmlor use@WebServletannotations for configuration. - Package the servlet and other web resources (HTML, JSP, etc.) into a standard web archive (
.war). - Deploy the
.warfile on an application server or web container (e.g., Apache Tomcat, Jetty).
When using @WebServlet:
// Example of a simple servlet
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("/hello") // Annotation for registering the servlet at URL "/hello"
public class HelloServlet 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 object for response
out.println("<html><body>"); // Write HTML response
out.println("<h1>Hello from servlet!</h1>");
out.println("</body></html>");
}
}
When using web.xml:
<!-- Example of servlet registration in 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>HelloServlet</servlet-name> <!-- Unique servlet name -->
<servlet-class>com.example.HelloServlet</servlet-class> <!-- Full class name of the servlet -->
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name> <!-- Registered servlet name -->
<url-pattern>/hello_from_xml</url-pattern> <!-- URL pattern for accessing the servlet -->
</servlet-mapping>
</web-app>