1 / 24

Servlets

Learn about Servlets, modules that extend the functionality of a Java-enabled web server to dynamically generate HTML code and web content. Explore the anatomy of a servlet, how to write and deploy servlets, and how to work with parameters and initialization parameters.

underwoodc
Download Presentation

Servlets

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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

  3. Anatomy of a Servlet • A new servlet can be written by extending the class HttpServlet 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

  4. 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

  5. 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.

  6. 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.

  7. A first Example • Writing a servlet with Netbeans is very easy • Also the deplyment 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

  8. SimpleServlet • SimpleServlet extends HttpServlet which implements the interface Servlet. • 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.

  9. 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 • See Count.java

  10. 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 this file some parameters for the servlet can be defined • Allows servlet to change functionality of servlet without compiling them again • In netbeans the parameters are defined while creation and may be modified afterwards browsing the file projectName/build/web/WEB-INF/web.xml • See ShowParameters.java

  11. Parameters passed by client • The client can pass parameters with the request according to the following format • http://host:port/servlet?param1=value1&param2=value2 • The servlet can ask for those values in the following way: • String value = req.getParameter(param1); • String[] value = req.getParameterValues(param1) • Parameter names and values are strings • see ShowParameters1.java and call with • http://host:port/ServletParameter1?name=nelson

  12. 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

  13. 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

  14. 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

  15. 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.

  16. 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

  17. 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

  18. ¿ 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

  19. 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

  20. 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

  21. 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)

  22. 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)

  23. 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

  24. 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

More Related