360 likes | 373 Views
Servlets. Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically. This is sent to the browser which displays it.
E N D
Servlets • Servlets are modules that extend the functionality of a “java-enabled” web-server • They normally generate HTML code and web content dynamically. This is sent to the browser which displays it. • For example, they send a query to a database based on parameters sent by the browser and send the results to the browser in html format
Interaccion browser-servidor web • Durante la comunicación entre el cliente y el servidor HTTP en el que el cliente solicita el documento doc1.html al servidor se intercambian la siguiente transacción HTTP: GET /doc1.html HTTP/1.0 Accept: www/source Accept: text/html Accept: image/gif User-Agent: Lynx/2.2 libwww/2.14 From: jvegas@infor.uva.es <- linea en blanco • El método GET indica el archivo que el cliente solicita y la versión de HTTP. El cliente también muestra una lista de los tipos MIME que puede aceptar como retorno, además de identificar el browser que utiliza y su dirección de correo electrónico (opcional). Al final se manda una línea en blanco que determina el final de la cabecera HTTP.
Respuesta del servidor El servidor responde mandando la siguiente transacción HTTP: HTTP/1.0 200 OK Date: Friday, 23-Feb-01 16:30:00 GMT Server: Apache/1.1.1 Content-type: text/html Content-length: 230 <- linea en blanco <HTML><HEAD><TITLE> ........ </HTML> En este mensaje el servidor utiliza la versión 1.0 de HTTP, y manda el código de estado 200 para indicar que la petición del cliente ha sido procesada satisfactoriamente. También se identifica como un servidor Apache. Indica al cliente que el contenido del documento es texto en formato HTML y que tiene una longitud de 230 bytes.
GET, HEAD y POST • La primera línea de una petición contiene los comandos HTTP, conocidos como métodos. Existen varios, pero los más conocidos y utilizados son tres: GET, HEAD y POST
GET • El método GET se utiliza para recuperar información identificada por un URI por parte de los navegadores. Si el URI se refiere a un proceso generador de datos como un programa CGI, en lugar de él, se devuelven los datos generados por el programa. El método GET también se puede utilizar para pasar una pequeña cantidad de información al servidor en forma de pares atributo-valor añadidos al final del URI detrás de un símbolo de interrogación, ?.
Ejemplo GET con parámetros GET /servlet/saludar?nombre=pepe&email=pepe@dss.cl HTTP/1.0 • La longitud de la petición GET está limitada por el espacio libre en los buffers de entrada. Por lo que para mandar una gran cantidad de información al servidor ha de utilizarse el método POST. • Buffer: porcion de memoria en el computador usado para traspasar datos entre dos medios distintos (memoria principal-memoria secundaria, memoria principal – internet)
HEAD • El método HEAD es idéntico al GET excepto que el servidor no devolverá el cuerpo del mensaje en la respuesta a un método HEAD. Esto es útil para obtener información sobre las entidades implicadas en la petición sin que tengan que transferirse. Sirve para comprobar si los enlaces son válidos o para saber cuando fue la última modificación de la entidad solicitada.
POST • El método POST se refiere normalmente a la invocación de procesos que generan datos que serán devueltos como respuesta a la petición. Además se utiliza para aportar datos de entrada a esos programas. En este caso los pares atributo-valor son incluidos en el cuerpo de la petición separados por &.
Ejemplo POST POST /servlet/saludar HTTP/1.0 Accept: */* <- linea en blanco nombre=pepe&email=pepe@dsstgo.cl • Primero el browser manda las líneas de arriba y el servidor queda esperando información adicional hasta que el browser corta la comunicación (notar la diferencia con el get que solo manda una línea y corta la comunicación) • De este modo el método POST no sufre de las limitaciones de espacio y puede enviar mucha más información al servidor. En particular se usa cuando se quieren mandar archivos completos (tareas!!!!) • Más aún, es muy conveneinte cuando se quiere mandar información confidencial (passwords) ya que esta no queda en el historial del browser (solo queda la primera linea)
Preliminary work • The package javax.servlet provides the interfaces and classes which allows the compilation and execution of servlets • It does not come with the standard distribution of j2sdk, it is necessary to download the jar file containing it and make it „visible“ when compiling the programs • for executing servlets normally the java-enabled server will provide the necessary classes • Every server follows different rules for the way servlets should be deployed (make them available for clients) • Normally, they should be copied in a certain directory For example, in tomcat servlets under <tomcatroot>\webapps\examples\WEB-INF\classes can be contacted by the url http://host:port/servlet/examples/servletname • Sometimes there is also necessary to have a manifest file (in XML) for defining aliases and parameters
Development Environments • There are many good development environments which help to write and test the servlets • They include an editor and a java-enabled sever • They also include all the necessary jar files an import statements • Some of them are Eclipse (need to download plugins) and Netbeans (which also has full j2ee support
Anatomy of a Servlet • A new servlet can be written by extending the HttpServlet class which has the following pre-defined methods • init() is called when the servlet is “uploaded” the first time (this can vary depending on the server) • doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException is called every time the servlet is contacted by a GET request (which is the default way) • doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException is called when the client contacted the servlet with a POST request
Anatomy of a Servlet (2) • A web browser generates a GET request when it sends an http request from the user • For example, by entering http://www.yahoo.com in the browser it will send the string „GET index.html Httpx.x“ • When a servlet is contacted the first time it starts 4-6 threads are initialised to serve future clients (why ?) • It is very often to see servlets contacted by a POST request generated by an HTML „form“ which also passes a lot of parameters
The HttpServletRequest Parameter • HttpServletRequestis the class of one of the two parameters the server calls doGet and doPost and implements the interface ServletRequest which give access to: • Information about the client, for example, parameters passed, protocol used, client’s host, etc. • The input stream, ServletInputStream is used by the servlet to receive data from the client when the method POST or PUT has been used.
The HttpServletResponse parameter • HttpServletResponse is the class of the second argument. • Implements the interface ServletResponse which provides methods for : • Declaring the MIME type of the answer that will be sent to the client • The output stream ServletOutputStream and a Writer through which the servlet can send dinamically generated html code.
A first Example • Writing a servlet with Netbeans is very easy • Also the deployment is done automatically • Open netbeans • Create a web project (this will create a lot of directories for putting the different kind of files) • Create a servlet • Copy the code of SimpleServlet.java • Run the file
SimpleServlet • SimpleServlet extends HttpServlet • Overwrites the method doGet from the HttpServlet class. doGet is called by the service method • Inside the method doGet, • The client´s request is represented by the object of the class HttpServletRequest. • The answer by an object of the class HttpServletResponse • Because the answer to the client is text, the servlet creates an object from the class Writer from the parameter HttpServletResponse.
A second example • Implementing a web counter • It will count • how many times it has been created (init) • how many times all instances has been called • Haw many times the instance that has been contacted has been already called • The Address of the last computer that contacted the servlet • See Count.java
Proposed 1 • Modify the count servlet in order to generate an answer showing every time ALL computer that have accessed it • Use a vector or an array to store the Addresses of the computers • The Address of the client computer can be retrieved with • String s = request.getRemoteHost(); • String s = request.getRemoteAddress();
Proposed 2 • Modify the count servlet in order to generate an answer showing the IP or hostname of the client which most contacted the servlet • Use a hashtable with the client addresses as index and the times they visited the servlet as the information associated
Using initialization parameters(also called context parameters) • In all servers there is the possibility to use a configuration file for servlets called web.xml • It can be edited “by hand” with a text editor • In netbeans they can be defined while creation and may be modified afterwards browsing the file projectName/web/WEB-INF/web.xml • In this file some parameters for the servlet can be defined • Allows servlet to change functionality of servlet without compiling them again • See ShowParameters.java
Parameters passed by client • The client can pass parameters with the request according to the following format • http://host:port/servlet?param1=value1¶m2=value2 • The servlet can ask for those values in the following way: • String value = request.getParameter(param1); • String[] value = request.getParameterValues(param1) • Parameter names and values are strings • see ShowParameters1.java and call it with • http://host:port/ServletParameter1?name=nelson
The normal way is to gather parameters with forms • A Form is an HTML page which may contain graphical objects to gather information which ist sent to the server in an URL • We can use the same servlet but call it whith !!!! - ShowParameters1.html (add to project an html file) • Example 1: • ShowParametersRequest.java called by ShowParametersPostForm.html • Example 2: • SurveyServlet.java called by JdcSurvey.html
Session Tracking • Session tracking is a mechanism that servlets may use to maintain a state for a client during a session • A session is a dialogue between an instance of a browser and the server for a certain period of time (default is 30 minutes). • It is possible to associate information to the session objects, which is kept on the server during the session • The session is not managed by the programmer but by the server. • See SessionServlet
Some methods • HttpSession sesion = request.getSession(true) cretes a session object if it did not existed already • sesion.isNew()returns true if the above methods created a new object • sesion.putAttribute/Value(String nombre, Object valor) associates to the parameter nombre the value valor (value se usa hasta v2.2) • Object o = sesion.getAttribute/Value(“nombre”)returns the object associated to that prameter for that session • sesion.removeAttribute/Value(“nombre”)deletes the object associated to the parameter named “nombre” for that session • Enumeration[]valores = sesion.getAttributeNames() • String[]valores = sesion.ValueNames() returns an array/ennumeration of names for attributes/values the session has stored • long l = sesion.getCreationTime()returns the time (in milliseconds starting from 1.1.70 0:0:0 ) the session object was created • Long l = sesion.lastAccessedTime() returns the time of the las access • sesion.setMaxInactiveInterval(int seconds)sets the timeout of the session
Examples • Session Servlet: muestra todas las sesiones que se han creado en el servlet • OrderPage: muestra una página que implementa un “carro de compras” para un sitio que vende libros • Propuesto: hacer la página que saca la cuenta de cuanto tiene que pagar el cliente
Using Cookies • Cookies are another way to keep track of what the client has been doing • Trough a cookie the servlet can send information to the client so it can store it and send it every time it contacts the server again. • The Servlets send cookies to the clients adding information to the header of the Http response it send to the client. • The clients automatically return these cookies when thy contact the server again for a further request as additional information on the HTTP request. • Cookies have a name and a value (both strings) Additionally they can store a comment • A server can pass more than a cookie to the client.
Using Cookies • To send a cookie 1. Instantiate a Cookie object 2. Set attributes (pair name-value) 3. Send cookie • To retrieve the information of a cookie, 1. Retrieve all cookies from the client 2. Find the cookie you need by its name 3. Retrieve the associated value
Examples of Cookies • The first example (Cookies.java) shows the times when the client contacted the servlet for the first time (via doGet method) and the time when it contacted the server by pressing the button • The second example (CookieExample) shows how to retrieve all the cookies • The third example (SetCookie and ShowCookies) shows how to put time-out values for a cookie
¿ Cookies or Sessions ? • With sessions the information is stored on the server, this means, there is a state which has to be administrated carefully • With cookies it is the client which has the information, this means the information travels back and forth every time the client contacts the server • The client can prohibit the use of cookies • Sessions can store much more (and better) information • Sessions are implemented with cookies !!!!!!!!
The headers of request and response • Provide high level information from the client and to the client • The request allows the servlet to obtain interesting characteristics of the client • The response allows the servlet to define how the information will be delivered to the browser • In general, they help make the dialog with the client more effective • For the request, there are methods called getXXX or getHeader(xxx) to obtain information • For the response, there are methods called setHeader(xxx) or setXXX for defining the form of the response data. • Often both are required to be used in combination to generate an adequate response
Some get for the request • getCookies(): received the cookies which the client browser may have sent • getAuthType(): is used for clients trying to access a page for which a password is required • getRemoteHost(): to obtain the hostname of the client • getMethod(): to get the name of the method with which the browser contacted the servlet (GET, POST, etc..) • getProtocol(): version of the HTTP protocol the client is using • getHeaderNames(): the name of all the headers the client has sent (is variable depending on the HTTP and browser version
Some xxx for the getHeader(xxx) • Accept: which MIME types the client “understands” • Accept-Charset: which character set the client is using • Accept-Encoding: encoding algorithms the client accepts • Accept-Language: language (en-us, sp, ge, ..) • Authorization: to identify clients with a protected page • Host: the client’s computer name • Referer: the URL of the page that generated the contact • Cookie: to obtain the cookies • Connection: if the client can manage persistent connections (for example, in order to send files)
Some set for the response • setContentType(xxx): for informing the MIME type of the response • setContentLength(xxx): for informing the length of the response (used when transmitting bytes) • addCookie(): to add cookies with information to the client • sendRedirect(): to redirect the request to another URL • setHeader(xxx,xxx) a general form • setIntHeader(xxx,xxx) when the second argument is an integer (no need to convert to string)
Some xxx for the setHeader(xxx,xxx) • Content-Type: some MIME type like “image/gif” • Content-Length: length (para bytes) • Content-Encoding: codification • Content-Language: language • Cache: como se debe manejar el cache en el cliente (ej, no-cache, no-store, must-revalidate, max-age=xxxx, • Refresh: informs the browser how often the page should be refreshed • www-Authenticate: for managing pages protected with passwords
Some more elaborated exemples showing the use of these methods • ShowRequestHeaders: just shows the headers of the request • ProtectedPage: shows how to ask for a password (run PasswordBuilder first) • Ping & Pong: shows redirection