Web Programming: Announcements. Sara Sprenkle August 3, 2006. August 3, 2006. Assignment 6 due today Project 2 due next Wednesday Review XML



Similar documents
Usability. Usability

ACM Crossroads Student Magazine The ACM's First Electronic Publication

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Introduction to J2EE Web Technologies

Web Container Components Servlet JSP Tag Libraries

Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

11.1 Web Server Operation

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

2.8. Session management

INSIDE SERVLETS. Server-Side Programming for the Java Platform. An Imprint of Addison Wesley Longman, Inc.

2. Follow the installation directions and install the server on ccc

An introduction to web programming with Java

CSc31800: Internet Programming, CS-CCNY, Spring 2004 Jinzhong Niu May 9, Java Servlets

Outline. CS 112 Introduction to Programming. Recap: HTML/CSS/Javascript. Admin. Outline

Creating Java EE Applications and Servlets with IntelliJ IDEA

Agenda. Summary of Previous Session. Application Servers G Session 3 - Main Theme Page-Based Application Servers (Part II)

Development of Web Applications

Announcements. Comments on project proposals will go out by in next couple of days...

Ch-03 Web Applications

INTRODUCTION TO WEB TECHNOLOGY

Web Development in Java

Pure server-side Web Applications with Java, JSP. Application Servers: the Essential Tool of Server-Side Programming. Install and Check Tomcat

Principles and Techniques of DBMS 5 Servlet

Class Focus: Web Applications that provide Dynamic Content

Applets, RMI, JDBC Exam Review

CS506 Web Design and Development Solved Online Quiz No. 01

Outline. Lecture 9: Java Servlet and JSP. Servlet API. HTTP Servlet Basics

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

Java 2 Web Developer Certification Study Guide Natalie Levi

CIS 455/555: Internet and Web Systems

Supplement IV.E: Tutorial for Tomcat. For Introduction to Java Programming By Y. Daniel Liang

Web Applications. For live Java training, please see training courses at

Arjun V. Bala Page 20

DTS Web Developers Guide

Please send your comments to:

Complete Java Web Development

Glassfish, JAVA EE, Servlets, JSP, EJB

Course Name: Course in JSP Course Code: P5

Cours. Client/serveur avancé en Java (servlets, RMI, etc.) M.M.F.A.I. François Bourdoncle

Web Programming with Java Servlets

Controlling Web Application Behavior

Course Number: IAC-SOFT-WDAD Web Design and Application Development

If you wanted multiple screens, there was no way for data to be accumulated or stored

Core Java+ J2EE+Struts+Hibernate+Spring

Servlet 3.0. Alexis Moussine-Pouchkine. mercredi 13 avril 2011

Building Web Applications, Servlets, JSP and JDBC

PA165 - Lab session - Web Presentation Layer

Servlet and JSP Filters

In this chapter, we lay the foundation for all our further discussions. We start

Model-View-Controller. and. Struts 2

AN OVERVIEW OF SERVLET AND JSP TECHNOLOGY

Managing Data on the World Wide-Web

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Building a Multi-Threaded Web Server

In this chapter the concept of Servlets, not the entire Servlet specification, is

Web Application Programmer's Guide

CHAPTER 9: SERVLET AND JSP FILTERS

PowerTier Web Development Tools 4

CHAPTER 5. Java Servlets

Session Tracking Customized Java EE Training:

JSP Java Server Pages

Developing Web Applications using JavaServer Pages and Servlets

Introduction to Web Technologies

JBoss SOAP Web Services User Guide. Version: M5

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

SSC - Web development Model-View-Controller for Java web application development

CS108, Stanford Handout #33 Young. HW5 Web

Java Server Pages combined with servlets in action. Generals. Java Servlets

Server-Side Web Development JSP. Today. Web Servers. Static HTML Directives. Actions Comments Tag Libraries Implicit Objects. Apache.

Java Servlet 3.0. Rajiv Mordani Spec Lead

Java Servlet Tutorial. Java Servlet Tutorial

10. Java Servelet. Introduction

Mastering Tomcat Development

Liferay Enterprise ecommerce. Adding ecommerce functionality to Liferay Reading Time: 10 minutes

Web. Services. Web Technologies. Today. Web. Technologies. Internet WWW. Protocols TCP/IP HTTP. Apache. Next Time. Lecture # Apache.

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Outline Introduction

Clojure Web Development

Exam Prep. Sun Certified Web Component Developer (SCWCD) for J2EE Platform

Web Programming II JSP (Java Server Pages) ASP request processing. The Problem. The Problem. Enterprise Application Development using J2EE

Web Development on the SOEN 6011 Server

Drupal CMS for marketing sites

Tutorial: Building a Web Application with Struts

Web Pages. Static Web Pages SHTML

Web Frameworks and WebWork

Web Application Architecture (based J2EE 1.4 Tutorial)

Java Web Programming. Student Workbook

LabVIEW Internet Toolkit User Guide

Database System Concepts

An introduction to creating JSF applications in Rational Application Developer Version 8.0

COMP9321 Web Applications Engineering: Java Servlets

Oracle WebLogic Server

How to program Java Card3.0 platforms?

Web Application Developer s Guide

Web-JISIS Reference Manual

Getting Started with Web Applications

Java Servlet and JSP Programming. Structure and Deployment China Jiliang University

Penetration from application down to OS

Tomcat 5 New Features

Building Java Servlets with Oracle JDeveloper

Transcription:

Web Programming: Java Servlets and JSPs Sara Sprenkle Announcements Assignment 6 due today Project 2 due next Wednesday Review XML Sara Sprenkle - CISC370 2 1

Web Programming Client Network Server Web Browser Web Web Server Application Specialized network programming Web browser: makes requests, renders responses; executes JavaScript, client-side code Web Server: handles static requests Web Application: handles dynamic requests Sara Sprenkle - CISC370 3 Web Programming Client HTTP Request Server Web Browser Web Application Response: HTML Document - can contain JavaScript Web Server Web Application Parses request, including data Executes request Returns response (often an HTML document) May do other things, like send email, Sara Sprenkle - CISC370 4 2

Java Web Application Server Client HTTP Request Response: HTML Document Server Web Application Server Web Application Server Container to run the web applications Listens on another port besides 80, typically 8080 Sara Sprenkle - CISC370 5 Servlets A servlet is a Java program that extends the functionality of web servers Processing occurs at the server and then the results (typically as an HTML file) are sent back to the client In javax.servlet.* packages Part of J2EE or as a separate download Servlets are Java s s answer to CGI Servlets are supported by many major web servers including Netscape, iplanet,, and Apache (with Tomcat/Jakarta Jakarta) Specialized web servers: Resin Sara Sprenkle - CISC370 6 3

The Servlet Interface All servlets implement the Servlet interface Many key methods of Servlet interface are invoked automatically Web application server calls methods The program itself does not call Sara Sprenkle - CISC370 7 Servlet Interface: Key Methods init(serverconfig config) Called once by the web server to initialize the servlet ServletConfig getservletconfig() Returns a reference to a ServletConfig that provides access to the servlet s configuration information and the servlet s ServletContext,, which provides access to the server itself void service(servletrequest ServletRequest, ServletResponse) Called to respond to a client request String getservletinfo() Returns a String that describes the servlet (name, version, etc.) void destroy() Called by the server to terminate a servlet Should close open files, close database connections, etc. Sara Sprenkle - CISC370 8 4

The service() Method Called for every client request by application server Generally not overridden Method receives both a ServletRequest and a ServletResponse object ServletRequest gives the servlet access to input streams and methods to read data from the client ServletResponse gives the servlet access to output streams and methods to write data back to the client Sara Sprenkle - CISC370 9 The HttpServlet Class Web-based servlets (almost all of them) typically extend the HttpServlet class HttpServlet overrides the service() method to distinguish between the typical types of requests (HTTP commands/requests) Most common request types are GET and POST GET - data encoded in URL Request a resource (file) or retrieve data POST - data encoded in body of message Upload data; processing; hide data from URL Sara Sprenkle - CISC370 10 5

The doget() & dopost() Methods HttpServlet defines the doget() and dopost() methods service() calls the respective method in response to a HTTP GET or POST request doget() and dopost() receive HttpServletRequest From the client HttpServletResponse To the client Sara Sprenkle - CISC370 11 The HttpServletRequest Object String getparameter(string) Returns the value of a parameter sent to the servlet String[] getparametervalues (String) Returns an array of Strings containing the values for a specific servlet parameter Enumeration getparameternames() Returns the names of all of the parameters passed to the servlet Requests for a digital publication library: GET dspace/simple-search?search=xxx&sort=date&title=title GET dspace/simple-search?search=xxx&sort=name&header=head Sara Sprenkle - CISC370 12 6

The HttpServletRequest Object Cookie[] getcookies() Returns an array of Cookie class objects that have been stored on the client by the server Cookies can be used to uniquely identify clients to the server HttpSession getsession (boolean create) Returns an HttpSession associated with the client s current browser session Sessions can also be used to uniquely identify clients Sara Sprenkle - CISC370 13 The HttpServletResponse Object void addcookie(cookie) Add a Cookie to the header in the response to the client The cookie will be stored on the client, depending on the max- life and if the client allows cookies ServletOutputStream getoutputstream() obtains a byte output stream that enables the servlet to send binary data to the client PrintWriter getwriter() obtains a text writer that enables the servlet to send character data to the client void setcontenttype(string) Specifies the MIME type of the response to the client so that the browser will know what it received and how to format it text/html specifies an HTML document Sara Sprenkle - CISC370 14 7

A Simple Example Let s s create a very basic servlet Create a HTML page with a very basic form, one submit button When the button is pressed, browser passes the servlet a basic GET request Sara Sprenkle - CISC370 15 <HTML> <HEAD> <TITLE>Servlet HTTP GET Example (simple!)</title> </HEAD> <BODY> <FORM ACTION= http://localhost:8080/080306/simpleservlet METHOD= GET > <P>Click on the button to have the servlet send back an HTML document.</p> <INPUT TYPE= submit VALUE= Get HTML Document > </FORM> </BODY> </HTML> Creates a submit button When the submit button is pressed, the browser makes a GET request to the web application server on the local machine listening to port 8080. The application server then calls the doget() method on the servlet, which is named HTTPGetServlet and located in a webapp directory Sara Sprenkle - CISC370 16 8

The Actual Servlet We can design the server to only accept/handle GET requests Extend the HttpServlet class and override the doget() method Could return an error inside of dopost() doget() method needs to Obtain an output stream writer to write back to the client Generate an HTML page Write out the HTML page to the client using the writer Close the writer Sara Sprenkle - CISC370 17 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HTTPGetServlet extends HttpServlet { public void doget( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter output; response.setcontenttype( text/html ); output = response.getwriter(); StringBuffer buffer = new StringBuffer(); buffer.append( <HTML><HEAD><TITLE>\n ); buffer.append( A Simple Servlet Example\n ); buffer.append( </TITLE></HEAD><BODY>\n ); buffer.append( <H1>Welcome to Servlets!</H1>\n ); buffer.append( </BODY></HTML>\n ); output.println( buffer.tostring()); output.close(); } } Sara Sprenkle - CISC370 18 9

The Example Servlet Flow HTML Form submit Client Web Browser HTTP Request Response doget() Server Web Application Server HTML Document Sara Sprenkle - CISC370 19 A More Complex Example This example was the most basic type of servlet it always did the same thing The power of servlets is that the web server can receive data from the client,, perform substantial processing, and then generate results to send back to the client As a more complex example, let s s create a survey system An HTML document that asks the user for their favorite type of pet After they submit the form, the server sends back the current results of the survey. Sara Sprenkle - CISC370 20 10

<HTML> <HEAD> <TITLE>Pet Survey</TITLE> </HEAD> <BODY> <FORM METHOD= POST ACTION= SurveyServlet > What is your favorite pet?<br><br> <INPUT TYPE=radio NAME=animal VALUE=dog>Dog<BR> <INPUT TYPE=radio NAME=animal VALUE=cat>Cat<BR> <INPUT TYPE=radio NAME=animal VALUE=bird>Bird<BR> <INPUT TYPE=radio NAME=animal VALUE=snake>Snake<BR> <INPUT TYPE=radio NAME=animal VALUE=fish>Fish<BR> <INPUT TYPE=radio NAME=animal VALUE=none CHECKED>Other<BR> <INPUT TYPE=submit VALUE= Submit > <INPUT TYPE=reset> </FORM> </BODY> </HTML> Assumes on same server, Same path Create a radio button for each type of animal in the survey. Sara Sprenkle - CISC370 21 public class SurveyServlet extends HttpServlet { private String animalnames[] = { dog, cat, bird, snake, fish, none }; public void dopost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int animals[] = null, total = 0; File f = new File( survey.results ); if (f.exists()) { try { ObjectInputStream in = new ObjectInputStream( new FileInputStream( f )); animals = (int []) in.readobject(); in.close(); for (int x = 0; x < animals.length; x++) total += animals[x]; } catch (ClassNotFoundException exp) { }; } else animals = new int[6]; Sara Sprenkle - CISC370 22 11

// read current response (that caused this to run) String value = request.getparameter( animal ); total++; // determine which was selected and update the total for (int x = 0; x < animalnames.length; x++) if(value.equals(animalnames[x])) animals[x]++; // write updated total to the disk ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( f )); out.writeobject(animals); out.flush(); out.close(); // determine precentages double percentages[] = new double[animals.length]; for (int x = 0; x < percentages.length; x++) percentages[x] = 100.0 * animals[x] / total; Sara Sprenkle - CISC370 23 } } // now sent a thanks to the client and the results response.setcontenttype( text/html ); PrintWriter clientoutput = response.getwriter(); StringBuffer buffer = new StringBuffer(); buffer.append( <HTML><TITLE>Thanks!</TITLE>\n ); buffer.append( Thanks for your input.<br>results:\n<pre> ); DecimalFormat twodigits = new DecimalFormat( #0.00 ); for (int x = 0; x < percentages.length; x++) { buffer.append( <BR> + animalnames[x] + : ); buffer.append(twodigits.format(percentages[x])); buffer.append( % Responses: + animals[x] + \n ); } buffer.append( \n<br><br>total Responses: ); buffer.append(total + </PRE>\n</HTML> ); clientoutput.println(buffer.tostring()); clientoutput.close(); Sara Sprenkle - CISC370 24 12

Multiple Clients The survey servlet stores the results of the survey in a static file on the web server What happens if more than one client connects to the server at one time? The server handles both of the clients concurrently More than one thread can open/close/modify that file at one time Can lead to inconsistent data! Need to use Java s synchronization mechanisms How would you synchronize SurveyServlet? Sara Sprenkle - CISC370 25 Cookies A popular way to customize web pages is to use cookies Cookies are sent from the server (servlet) to the client Small files, part of a header in the response to a client Every HTTP transaction includes HTTP headers Store information on the client s s computer that can be retrieved later in the same browser session or in a future browsing session Sara Sprenkle - CISC370 26 13

Cookies When a servlet receives a request from the client, the header contains the cookies stored on the client by the server When the servlet sends back a response, the headers can include any cookies that the server wants to store on the client For example, the server could store a person s book preferences in a cookie When that person returns to the online store later, the server can examine the cookies and read back the preferences Sara Sprenkle - CISC370 27 Cookie Structure Cookies have the name/value structure (similar to a hashtable) Creating a Cookie object is very easy pass the constructor a name and a value For example, to store a user s s preferred language on the client (so the servlet only has to ask for this information once) String cookie_name = new String( Pref_language ); String cookie_value = new String( English ); Cookie new_cookie = new Cookie(cookie_name, cookie_value); Sara Sprenkle - CISC370 28 14

Sending the Cookie to the Client Construct the Cookie object Call addcookie() on the HttpServletResponse object before you call the getwriter() method HTTP header is always sent first, so the cookie(s) must be added to the response object before you start writing to the client public void dopost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {... Cookie c = new Cookie( Pref_language, English ); c.setmaxage(120); // max age of cookie response.addcookie(c);... output = response.getwriter(); } Sara Sprenkle - CISC370 29 Cookies: Maximum Ages The maximum age of the cookie is how long the cookie can live on the client (in seconds) When a cookie reaches it maximum age, the client automatically deletes it Sara Sprenkle - CISC370 30 15

Retrieving Cookies Call getcookies() on the HttpServletRequest object returns an array of Cookie objects, representing the cookies that the server previously sent to the client For example public void dopost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {... Cookie[] cookies = request.getcookies();... } Sara Sprenkle - CISC370 31 Retrieving Cookies The client will send all cookies that the server previously sent to it in the HTTP headers of its requests Client s s cookies are available immediately upon entry into the dopost() and doget() methods Sara Sprenkle - CISC370 32 16

Session variables A session is one user s s visit to an application Can be made up of lots of accesses Associate data with a session rather than a request Example: User gives application data Application stores data in session variable value/ name variable session.setattribute setattribute("username", username); Application can use later, without user having to give information every time String username = session.getattribute getattribute( username ); Sara Sprenkle - CISC370 33 JavaServer Pages (JSPs( JSPs) Simplify web application development Separate UI from backend code Difficult to write HTML in print statements Merge HTML and Java Separate static HTML from dynamic Make HTML templates, fill in dynamic content Web application server compiles JSPs into Servlet code Sara Sprenkle - CISC370 34 17

JSP Syntax Enclose code in <% %> <html> <body> Hello! The time is now <%= new java.util.date() %> </body> </html> Expression Aside: new convention is all lowercase HTML tags Sara Sprenkle - CISC370 35 JSP Syntax <html> <body> <% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. java.util.date date = new java.util.date(); %> Hello! The time is now <%= date %> </body> </html> Sara Sprenkle - CISC370 36 18

JSP Directives Page Directive Java files to import (like import statement in Java) <%@ page import="java. "java.util.*,java.text.*" %> <%@ page import="servlets servlets.surveyservlet2".surveyservlet2"%> Include Directive Include contents of another file: JSP or HTML or text Could include common headers or footers for a site <%@ include file="hello. "hello.jsp" %> Sara Sprenkle - CISC370 37 JSP Variables By default, JSPs have some variables not explicitly declared in the file HttpServletRequest request HttpServletResponse response HttpSession session From JSPs,, can get access to request parameters, session data Sara Sprenkle - CISC370 38 19

Web Application Architecture Java Classes (Model) JSP Server-side Client DataStore Java Servlets Using traditional Java classes, JSPs and Servlets together Sara Sprenkle - CISC370 39 Communicating Between JSPs and Servlets Attributes Name/Value pairs Values are Objects Can get/set attributes on the request object Rather than Parameters All Strings From forms or in URLs SurveyServlet2 pet.jsp Sara Sprenkle - CISC370 40 20

A Real Example: CPM The Course Project Manager that we use Technologies JSPs, Servlets Filestore backend Sara Sprenkle - CISC370 41 Deployment: WAR files Web Archives Copy into webapp directory of web application server Server will automatically extract files and run Procedure for Apache/Tomcat and Resin Can create WAR files from Eclipse, with Web Tools Plugin Sara Sprenkle - CISC370 42 21

Configuration: web.xml Contains configuration parameters For security Map URLs to Servlet names Map Servlet classes to Servlet names Sara Sprenkle - CISC370 43 Web Programming Tools Eclipse plugin Web Tools Platform http://www.eclipse.org/webtools/ Firefox plugins Firebug Web developer plug-in: http://chrispederick chrispederick.com/work/.com/work/webdeveloper/ Sara Sprenkle - CISC370 44 22

Newer Web Technologies Struts Controller component of MVC Model and Viewer are from other standard technologies JSPs,, JDBC JavaServer Faces (JSF) Framework to make creating UIs easier Custom JSP tag libraries Sara Sprenkle - CISC370 45 Exam Preparation Similar format to quizzes Variety of questions May have some find the bug and coding questions Covers all topics this semester What we did, how/when to apply/use Bring your questions next Tuesday Also have quiz Brief overview of other packages Sara Sprenkle - CISC370 46 23

Project2 Replay tool to help automate testing Generate different test cases Makes requests, saves responses Sara Sprenkle - CISC370 47 24