I'm new to this and I do not quite understand the structure of a Servlet, it just seems to consist of 3 methods doGet, doPost and processRequest, no? But at what moment does each one run?
I'm new to this and I do not quite understand the structure of a Servlet, it just seems to consist of 3 methods doGet, doPost and processRequest, no? But at what moment does each one run?
A servlet is an object running on a server that is responsible for intercepting requests sent by a client and generating a response. The most popular type of servlet is HttpServlet
that handles HTTP methods such as GET and POST, among others.
In Java EE these servlets are set to listen to a certain URL or specifically to a URL pattern, either from the web.xml
configuration file or the @WebServlet
annotation.
A servlet is created by a servlet container, the first time it is required or during initialization and will be kept in memory throughout the execution of the application. That same instance will be reused for each request with a URL that matches the URL pattern of the servlet.
For example the pattern /sitio/*
, matches the following URLs:
http://server.com/server/sitio/entrada
http://server.com/server/sitio/orden?id=2
http://server.com/server/sitio
How are the methods executed?
Depending on the type of request sent by the client, the servlet can execute the doGet()
method (click on a link, access a URL from the address bar) or doPost()
(login, form submission). To access the data of the request the object HttpServletRequest
is used and to send the response the object HttpSevletResponse
.
Only one of these methods is necessary for a servlet to complete its task, but several can be written in case they are required.
In Java EE, there is the interface Servlet
that defines how A servlet must be defined. Any class that implements this interface and is configured as @WebServlet
in the code or via XML:
<servlet-config>
<servlet-name>MiServlet</servlet-name>
<servlet-class>paquete.donde.esta.la.ClaseServlet</servlet-class>
</servlet-config>
<servlet-mapping>
<servlet-name>MiServlet</servlet-name>
<servlet-url>/una/url</servlet-url>
</servlet-mapping>
The interface has several methods, of which the following are the main ones, ordered according to the life cycle of the Servlet (the other methods are not as relevant but they should be implemented anyway):
init(ServletConfig config)
: Method invoked after creating the Servlet. It allows to provide configuration parameters after starting the Servlet. These parameters can be used to start resources, such as opening a database connection or indicating a folder where files will be found that need to be processed. service(ServletRequest req, ServletResponse res)
: Method that allows to fulfill a request made to the server. It requires as parameters information about the request, which is in ServletRequest
, and the elements that will be written as part of the response, which is in ServletResponse
. destroy()
: Method that is executed prior to the elimination of the Servlet. This method must contain code to release any resource used by the servlet instance. By saying that the servlet is "removed" it is actually used to meet requests, and then the memory it occupies can be claimed by the Garbage Collector. To facilitate the development of servlets, two classes are provided that already implement this interface and allow developers to focus on more timely work.
The first class is GenericServlet
. This abstract class implements the Servlet
interface and provides basic functionality for almost all methods, with the exception of the service
method.
The second class is HttpServlet
. This abstract class extends from GenericServlet
and implements the service
method. In addition, it provides a service(HttpServletRequest req, HttpServletResponse res)
method that facilitates the execution of methods associated with HTTP verbs. This class also provides the methods doGet
, doPost
and others also important: doPut
, doDelete
, doHead
, doOptions
, doTrace
, to support other HTTP verbs. In the implementation of this method service
there is the following fragment of code that explains when each method doXxx
is executed (obtained from the code of javax.servlet.http.HttpServlet
in its version 3.1.0):
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
//si el método es GET
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
if (ifModifiedSince < lastModified) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
//si el método es HEAD
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
//si el método es POST
} else if (method.equals(METHOD_POST)) {
doPost(req, resp);
//si el método es PUT
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
//si el método es DELETE
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
//si el método es OPTIONS
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
//si el método es TRACE
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
//si el método es desconocido, no lo soporta
} else {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
The reason that HttpServlet
is an abstract class is so you can not configure a servlet directly as HttpServlet
and require the developer to extend that class.
apparently only consists of 3 methods doGet, doPost and processRequest
As you can see, none of those methods is part of Servlet
. The methods doGet
and doPost
are the methods provided to meet the requests type GET and POST. The IDEs generate the relevant code for these methods because when the Web applications arose, the browsers could only send requests of type GET and POST, therefore the support to the other methods was not necessary. The processRequest
method is a method that provides the IDE assuming that you will process the GET and POST requests in the same way, which is INCORRECT . The GET method must be used to pre-process the view and / or obtain information. The POST method must be used to process information and generate a view or redirect to a new view.