Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Java Server Pages (JSP)
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Session Tracking Honjo-Waseda Lets try this servlet (Get) public class Compute extends HttpServlet { int op1, op2; protected void doGet(request,
Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
CS320 Web and Internet Programming Generating HTTP Responses
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
CSC 2720 Building Web Applications
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets & Java Server Pages Lecture July 2013.
Chapter 6 Server-side Programming: Java Servlets
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
L.MARIA MICHAEL VISUWASAM UNIT-4
Operating Systems Lesson 12. HTTP vs HTML HTML: hypertext markup language ◦ Definitions of tags that are added to Web documents to control their appearance.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Servlets.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Servlets 4 Lec 30 Web Design and Development. Looking Back… Response Redirection  Sending a standard redirect  Sending a redirect to an error page Request.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Chapter 4 Request and Response. Servlets are controlled by the container.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
1 Lecture 8 George Koutsogiannakis/Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
Java Servlets By: Tejashri Udavant..
Java Servlets.
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
Session Tracking Honjo-Waseda 2008.
Servlet.
Chapter 26 Servlets.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
COP 4610L: Applications in the Enterprise Spring 2005
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Presentation transcript:

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

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 \webapps\examples\WEB-INF\classes can be contacted by the url Sometimes there is also necessary to have a manifest file (in XML) for defining aliases and parameters

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

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 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 HttpServletRequest is 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 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

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.

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

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

Parameters passed by client The client can pass parameters with the request according to the following format – 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 –

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 :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

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

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