1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 8 Servlets (Based on Møller and Schwartzbach,

Slides:



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

Servlets & JSPs - Sharad Ballepu.
Internet i jego zastosowania 1 J2EE Servlets. Internet i jego zastosowania 2 Agenda Overview Servlet Interface Servlet Context Request Response Sample.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
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)
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
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.
MC365 Application Servers: Servlets. Today We Will Cover: What a servlet is The HTTPServlet and some of its more important methods How to configure the.
Servlets and a little bit of Web Services Russell Beale.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
An introduction to Java Servlet Programming
CS320 Web and Internet Programming Generating HTTP Responses
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Web Applications Basics. Introduction to Web Web features Clent/Server HTTP HyperText Markup Language URL addresses Web server - a computer program that.
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.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
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 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
 2005 Pearson Education, Inc. All rights reserved Servlets.
AN OVERVIEW OF SERVLET TECHNOLOGY SERVER SETUP AND CONFIGURATION WEB APPLICATION STRUCTURE BASIC SERVLET EXAMPLE Java Servlets - Compiled By Nitin Pai.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
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
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.
2007cs Servers on the Web. The World-Wide Web 2007 cs CSS JS HTML Server Browser JS CSS HTML Transfer of resources using HTTP.
Copyright © 2002 ProsoftTraining. All rights reserved. Java Servlets.
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.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
Java Enterprise Edition Programming Page 1 of 9Configuring Servlets Web Application Context Name  In multiple web applications, a “context name” is used.
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.
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.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
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,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
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.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
Servlets.
Java Servlets By: Tejashri Udavant..
Java Servlets.
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
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
Presentation transcript:

1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 8 Servlets (Based on Møller and Schwartzbach, 2006, Chapter 9) David Meredith

2 Web applications and servlets Last week we saw how to build a simple Web server – Could only generate static pages This week we look at how to generate responses dynamically using servlets that have been plugged into the server Servlet framework is a Java-based API for programming Web applications A servlet is a program written for this API

3 Web applications: Basic concepts Web server responds to http requests Responses can be generated by Web applications – contain programs that are plugged into the Web server One server typically runs many concurrent threads of each Web application – Each thread handles one HTTP request or one client A series of response-request interactions between a server and a client is called a session

4 Sessions Session is a sequence of related interactions between a client and a server It is a thread of execution managed by a server Session thread stops when client logs out or times out after client has stopped issuing requests HTTP is stateless, so session states have to be managed at a higher level Three categories of state: 1.Shared state (global data) – shared between all sessions and stored in a database on the server 2.Session state (local data) – private to a particular session thread – e.g., – contents of a shopping cart – whether client has logged in – "program pointer" of thread 3.Transient state – data that is only used in a single interaction

5 A "Hello World!" Servlet Servlet can be run with the Apache Tomcat server Servlet API consists of two packages – javax.servlet – javax.servlet.http contains functionality specific to HTTP Servlet is usually a subclass of HttpServlet doGet method is invoked in response to a GET method – takes two arguments: HttpServletRequest object holds information about the request HttpServletResponse object used to generate response

6 Servlet life cycle init method used to initialize servlet when it is constructed – e.g., connecting to a database GET request causes doGet method to be invoked POST request causes doPost method to be invoked Variables in doGet and doPost correspond to transient state – i.e., private to session When server shut down, destroy method invoked on each servlet getServletInfo method should be implemented to return a short descriptive string log method writes messages to the log

7 Requests HttpServletRequest parameter of doGet and doPost contains information about incoming request Most important methods of HttpServletRequest are – getHeader returns the value of the specified header name as a string – e.g., request.getHeader("User-Agent") – getParameter returns decoded value of a form field as a string – e.g., request.getParameter("name") » returns the value provided by the user to a GUI form element whose name attribute has the value "name" works for GET and POST requests works for different encodings in POST requests provides useful level of abstraction – getInputStream returns an input stream for accessing HTTP request body – getRemoteHost, getRemoteAddr, getRemotePort return information about the client end of the TCP connection

8 Requests Note use of – getRemoteHost (l.13) – getHeader (l.14) – getParameter (l.17) POST requests are redirected to doGet htmlEscape escapes special characters in the value entered in the "name" control Never assume that values from expected form fields or request header lines are present (see lines 15, 18)

9 Responses HttpServletResponse parameter of doGet and doPost used to construct outgoing response Main methods in HttpServletResponse are – setStatus sets response status code (default is 200) – addHeader and setHeader adds or overwrites header fields – getOutputStream returns output stream for writing response body – getWriter returns a PrintWriter which wraps the output stream and sends characters rather than bytes – setContentType sets the Content-Type response header field sets character encoding for PrintWriter – e.g., response.setContentType("text/xml;charset=UTF-8") – sendError and sendRedirect simplify construction of error responses and temporary redirects

10 Servlet contexts and Shared State Each Web application has a ServletContext object that holds information about the context of a servlet – accessible via Servlet class getServletContext method ServletContext has getServerInfo method that returns information about the server – e.g., Apache Tomcat/ Each Web application may contain many servlets and other resources (e.g., CSS, GIFs, etc. ) Each Web application is associated with a context path – Context path is base of URIs for resources in application – Determined by deployment configuration (see later) ServletContext getRealPath method computes absolute path of resource from context path and relative path of resource ServletContext can be used to store shared state – setAttribute method binds an object to an attribute name – getAttribute returns object bound to an attribute name Data can be communicated between different Web applications running on the same server by using the getContext method which returns the ServletContext of a servlet

11 A Polling Service This Web application consists of – an HTML file called QuickPollQuestion.html which contains a form for entering the poll question – a servlet called QuickPollSetup for receiving data from the form in QuickPollQuestion.html – a servlet called QuickPollAsk for making an HTML page containing the question and a form which allows the user to vote 'Yes' or 'No' – a servlet called QuickPollVote for receiving a vote – a servlet called QuickPollResults for showing the results

12 QuickPollQuestion.html Deploy Deployment configuration (see later) defines mapping from URI setup in action attribute of form element to the QuickPollSetup servlet

13 QuickPollSetup Servlet String q set to equal value entered by user into GUI element named "question" in QuickPollQuestion.html Attributes question, yes and no set in servlet context, c Message sent back to user to indicate that question has been registered

14 QuickPollAsk Servlet Uses question stored in servlet context to make a new HTML form with two radio buttons that allow the user to vote on the question getAttribute returns an Object which has to be cast to a String

15 QuickPollVote Servlet Receives form data from voting form Increments either yes or no servlet context attributes accordingly Sends an acknowledgement to the user

16 QuickPollResults Servlet Uses tables within tables to draw a barchart that represents the responses to the poll Set Cache-Control so as to disable caching to ensure that new, up-to- date form is loaded, not cached version Use POST in cases where servlet has side-effects, GET when it doesn't

17 HttpSession objects HttpSession object is an abstraction of a session that hides implementational details of session management HttpServletRequest has a getSession method which returns the current HttpSession object Session terminated by – an invocation of the invalidate method – inactivity for a certain time interval, determined by setMaxInactiveInterval method HttpSession object can be used to store session state using setAttribute and getAttribute methods

18 cart is stored in a TreeMap that maps items to amounts cart is stored as an attribute of the session If the request method is POST, then an item is added to the cart (causes side-effect on server) Returns 400 Bad Request if cannot parse amount A Shopping Cart Servlet (1/2)

19 A Shopping Cart Servlet (2/2) Prints out form for adding new item Prints out table listing contents of cart URLs passed through the encodeURL method to ensure special characters are escaped

20 Web applications and deployment In servlets, files always organised in a common directory structure as follows Assuming context path is myapp, – myapp/ and all subdirectories except WEB-INF contain static resources e.g., HTML, images, stylesheets, JSP files – myapp/WEB-INF/ contains the deployment descriptor (see later) – myapp/WEB-INF/classes contains all servlet classes and auxiliary classes used by servlets – myapp/WEB-INF/lib contains additional jar files Class files must be placed in subdirectories that match their package names – e.g., if MyServlet.class belongs to inc.widget package, then it is placed in myapp/WEB-INF/classes/inc/widget/ An whole Web application can be bundled in a single Web Archive file (.WAR) using the jar tool

21 Deployment descriptors Every Web application contains a deployment descriptor – An XML file called web.xml stored in myapp/WEB-INF/ – Configures application by providing mapping from URI paths to application resources initialization parameters error-handling configuration...

22 Example Deployment Descriptor display-name element provides name for the application web-app element can contain more than one servlet and servlet- mapping elements servlet element (servlet declaration) – associates a name with a servlet class can be many servlet declarations for a given servlet class – each declaration results in an instance of the servlet being constructed servlet-mapping element associates servlet name with a URI pattern – pattern is relative to context path e.g., if context path is myapp, then complete path here would be myapp/hello/ and this would cause the HelloWorld servlet to be executed namespace declaration identifies deployment descriptor language which is defined by an XML Schema definition

23 Initialization parameters Context initialization parameters apply to whole application – accessed using getInitParameter method of ServletContext object – in deployment descriptor above, context initialization parameter, admin, is added with the value Servlet initialization parameters apply to individual servlet instances – accessed using getInitParameter method of HttpServlet object – in deployment descriptor above, servlet initialization parameter, verbose, added with value true