You are on page 1of 8

¿Qué son los Servlets?

 
Java Servlets son programas que corren en una web o un servidor de
aplicaciones y actúan como capa media entre una petición que viene de un explorador Web u otro
cliente del HTTP y bases de datos o usos en el servidor de HTTP. 
Usando Servlets, usted puede recoger la entrada de usuarios a través de formas de una página
web, los registros actuales  de una base de datos u otra fuente, y crea las páginas web dinámicamente.
Definición
Un ciclo de vida del servlet se puede definir como  todo el
proceso de su creación hasta la destrucción. Los
siguientes pasos son la trayectoria seguida por un servlet
El servlet es inicializado llamando el método init ().
El servlet llama método del service () para
procesar la petición de un cliente.
El servlet es terminado llamando el método destroy ().
Finalmente, el servlet es basura recogida por el
recolector del JVM.
Ahora déjenos discuten los métodos de ciclo de
vida en detalles.
Pasos tipico
The following is a typical user scenario of these methods.
1.Assume that a user requests to visit a URL.
•The browser then generates an HTTP request for this URL.
•This request is then sent to the appropriate server.
2.The HTTP request is received by the web server and forwarded to the servlet container.
•The container maps this request to a particular servlet.
•The servlet is dynamically retrieved and loaded into the address space of the container.
3.The container invokes the init() method of the servlet.
•This method is invoked only when the servlet is first loaded into memory.
•It is possible to pass initialization parameters to the servlet so that it may configure itself.
4.The container invokes the service() method of the servlet.
•This method is called to process the HTTP request.
•The servlet may read data that has been provided in the HTTP request.
•The servlet may also formulate an HTTP response for the client.
5.The servlet remains in the container's address space and is available to process any other HTTP
requests received from clients.
•The service() method is called for each HTTP request.
6.The container may, at some point, decide to unload the servlet from its memory.
•The algorithms by which this decision is made are specific to each container.
7.The container calls the servlet's destroy() method to relinquish any resources such as file handles
that are allocated for the servlet; important data may be saved to a persistent store.
8.The memory allocated for the servlet and its objects can then be garbage collected.
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletLifeCycleExample extends HttpServlet {
private int count;
public void init(ServletConfig config) throws ServletException {
super.init(config);
getServletContext().log("init() called");
count = 0; }

protected void service(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

getServletContext().log("service() called");
count++;
response.getWriter().write("Incrementing the count: count = " + count);
}
public void destroy() {
getServletContext().log("destroy() called");
GET y POST

Usted debe haber pasado  muchas situaciones


cuando usted necesita pasar una cierta
información de su navegador al web server y en última
instancia a su programa backend. El navegador utiliza dos métodos para
pasar esta información al web server. Estos métodos  GET y POST 
GET()
GET():
El método del GET() envía la información del usuario codificada añadida a la solicitud de
página. ¿La página y la información codificada son separadas por ? carácter como
sigue:http://www.test.com/hello?key1=value1&key2=value2
El método del GET() es el método default para pasar la información del navegador al web
server y produce una secuencia larga aparece en la ubicación de su navegador: Nunca utilice el 
método del GET() si usted tiene la contraseña u otra información delicada a
pasar al servidor. El método del GET()tiene limtacion del tamaño: solamente 1024caracteres pue
den estar en una secuencia de petición.
Esta información se pasa usando QUERY_STRING y será accesible con variable de
entorno de QUERY_STRING y Servlet maneja este tipo de peticiones usando método  doGet().

You might also like