Your SlideShare is downloading. ×
Explicación del código del Servlet HolaMundo
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Explicación del código del Servlet HolaMundo

1,191
views

Published on

Explicación del código del Servlet Hola_Mundo

Explicación del código del Servlet Hola_Mundo


0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,191
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
16
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. En esta práctica vamos a explicar el código de un Servlet que escribe unapágina web con el mensaje “Hola Mundo”.package pkgServletHM;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class HolaMundo */@WebServlet("/HolaMundo")public class HolaMundo extends HttpServlet { private static final long serialVersionUID = 1L; /** * @throws IOException * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException,IOException { // TODO Auto-generated method stub PrintWriter out; out = response.getWriter(); response.setContentType("text/html"); out.println("<html>"); out.println("<head><title>Ejemplo de Servlet</title></head>"); out.println("<body>"); out.println("<h1>Hola Mundo</h1>"); out.println("</body></html>"); }}
  • 2. public class HolaMundo extends HttpServlet {Para escribir un servlet específicamente para el protocolo http, servlet detipo HTTP, se usa la clase HttpServlet que extiende a la clase GenericServletla cual proporciona una implementación básica del interfaz Servlet Interface(todo servlet debe directa o indirectamente implementar este interfaz).Los métodos para la clase HttpServlet son:Method Summaryprotected doDelete(HttpServletRequest req, HttpServletResponse resp) void Called by the server (via the service method) to allow a servlet to handle a DELETE request.protected doGet(HttpServletRequest req, HttpServletResponse resp) void Called by the server (via the service method) to allow a servlet to handle a GET request.protected doHead(HttpServletRequest req, HttpServletResponse resp) void Receives an HTTP HEAD request from the protected service method and handles the request.protected doOptions(HttpServletRequest req, HttpServletResponse resp) void Called by the server (via the service method) to allow a servlet to handle a OPTIONS request.protected doPost(HttpServletRequest req, HttpServletResponse resp) void Called by the server (via the service method) to allow a servlet to handle a POST request.protected doPut(HttpServletRequest req, HttpServletResponse resp) void Called by the server (via the service method) to allow a servlet to handle a PUT request.protected doTrace(HttpServletRequest req, HttpServletResponse resp) void Called by the server (via the service method) to allow a servlet to handle a TRACE request.protected getLastModified(HttpServletRequest req) long Returns the time the HttpServletRequest object was last modified, in milliseconds since midnight January 1, 1970 GMT.protected service(HttpServletRequest req, HttpServletResponse resp) void Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. void service(ServletRequest req, ServletResponse res) Dispatches client requests to the protected service method.
  • 3. protected void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException,IOException {Dependiendo del protocolo utilizado para las peticiones (mediante POST oGET), el servlet ejecutará el método doPost() o el método doGet(), que secorresponden con el método service() del Servlet.En nuestro caso el método doGet() es llamado por el servidor (a través delmédotod service()) para permitir al servlet manejar peticiones de tipo GET.Los servlets están diseñados para un tipo de interacción petición-respuesta.Cuando el servidor web recibe una petición para un servlet llama al métodopublic void service(HttpServletRequest req, HttpServletResponse res) con dosparámetros: el primero, de la clase HttpServletRequest, representa lapetición del cliente y el segundo, de la clase HttpServletResponse,representa la respuesta del servlet. PrintWriter out; out = response.getWriter(); response.setContentType("text/html"); out.println("<html>"); out.println("<head><title>Ejemplo de Servlet</title></head>"); out.println("<body>"); out.println("<h1>Hola Mundo</h1>"); out.println("</body></html>");Como en el ejemplo no utilizamos ninguna información del cliente, no usamosel parámetro HttpServletRequest. De la clase HttpServletResponse usamos dosmétodos: • PrinterWriter getWriter(void) con el que obtendremos un PrinterWriter en donde iremos escribiendo los datos que queremos que el cliente reciba. PrintWriter out; out = response.getWriter(); • setContextType(String str) para establecer el tipo de respuesta que vamos a dar. Para indicar que se trata de una página web usamos el tipo "text/html". response.setContentType("text/html");