Serving HTTP NetworkServer.java EchoServer.java PostForm.html PostForm.html Browser EchoServer Response Using POST GetForm.html GetForm.html Browser EchoServer.

Slides:



Advertisements
Similar presentations
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Advertisements

Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
Servlets. A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password: In Netbeans you can graphically create.
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.
10-Jun-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
CSE 190: Internet E-Commerce Lecture 7. HTML Templates Designed to separate server side logic from HTML presentation Key features –Escapes from HTML into.
Core Servlets chapter 5: HTTP request headers. Requesting header information It is possible that information the servlet needs is not in the form data.
OCT 1 Master of Information System Management Organizational Communications and Distributed Object Technologies Week 2: Sockets and Servlets.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 10 Object Oriented Programming in Java Advanced Topics Servlets.
Web Technologies1 Java Servlets Part I Server and Servlet Basics Part II Session Tracking and Servlet Collaboration.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Servlets. A form The HTML source Chapter 1 Please enter your name and password then press start Name: Password: In Netbeans you can graphically create.
Core Servlets Chapter 3 Link for Core Servlets code: om/archive/ om/archive/
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
13-Jul-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
JDBC 1 Some introductory database terminology 2 Basic JDBC 3 Servlets 4 JDBC and servlets Gary Alperson helped developed these slides.
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.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
CSCI 6962: Server-side Design and Programming History and Background.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Web technologies and programming cse hypermedia and multimedia technology Fanis Tsandilas April 3, 2007.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
S ERVLETS Cookies Handling 5-Dec-15. S ERVLETS - C OOKIES H ANDLING Cookies are text files stored on the client computer and they are kept for various.
Java Servlets and Java Server Pages Norman White Stern School of Business.
Hints for Assignment #8. Initial Screen Hints for the initial page You need a DOCTYPE with the proper namespaces defined You need to import the facebook.
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.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
Configuration Web Server Tomcat - Install JDK Install Tom cat Configure Tom cat for running Servlet C:\Program Files\Apache Software Foundation\Tomcat.
Java Servlets and Java Server Pages
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Introduction To HTML Dr. Magdi AMER. HTML elements.
ClaRA web services V. Gyurjyan Clas12 Software Meeting
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Introduction to Servlets
Building Web Apps with Servlets
Servlets Hits Counter 20-Jul-18.
Session Tracking in Servlets
HTTP Servlet Overview Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might.
Lecture 2: Server-Side Programming: An Introduction to Servlets
HTTP request message two types of HTTP messages: request, response
Generating the Server Response: HTTP Status Codes
Servlets and Java Server Pages
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
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.
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Presentation transcript:

Serving HTTP NetworkServer.java EchoServer.java PostForm.html PostForm.html Browser EchoServer Response Using POST GetForm.html GetForm.html Browser EchoServer Response Using GET More HTML form examples Reading Form Data With Servlets

NetworkServer.java // NetworkServer.java Adapted from "Core Servlets // and Java Server Pages" // by Marty Hall import java.net.*; import java.io.*; public class NetworkServer { private int port; private int maxConnections;

protected void setPort(int port) { this.port = port; } public int getPort() { return port; } protected void setMaxConnections(int max) { maxConnections = max; } public int getMaxConnections() { return maxConnections; } public NetworkServer(int port, int maxConnections) { setPort(port); setMaxConnections(maxConnections); }

// Wait for a connections until maxConnections. // On each connection call handleConnection() passing // the socket. If maxConnections == 0 loop forever public void listen() { int i = 0; try { ServerSocket listener = new ServerSocket(port); Socket server ; while((i++ < maxConnections) || (maxConnections == 0)) { server = listener.accept(); // wait for connection handleConnection(server); } } catch (IOException ioe) { System.out.println("IOException : " + ioe); ioe.printStackTrace(); }

// Open readers and writers to socket. // Display client's host name to console. // Read a line from the client and display it on the console. // Send "Generic network server" to the client. // Override this method. protected void handleConnection(Socket server) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( server.getInputStream() )); PrintWriter out = new PrintWriter( server.getOutputStream(),true);

System.out.println("Generic network server: got connection from "+ server.getInetAddress().getHostName() + "\n" + "with first line '" + in.readLine() + "'"); out.println("Generic network server"); server.close(); } public static void main(String args[]) { NetworkServer test = new NetworkServer(6502, 5); test.listen(); }

EchoServer.java /* An HTTP Request example Notes GET /path/file.html HTTP/1.0 whitespace required Accept: text/html request header fields Accept: audio/x tell the client which data types User-agent: MacWeb can be handled by the browser

HTTP General form [ : ] : : : [ : ] a blank line [entity body] The resource identifier field specifies the name of the target resource; it's the URL stripped of the protocol and the server domain name. When using the GET method, this field will also contain a series of name=value pairs separated by &. When using a POST method, the entity body contains these pairs. The HTTP version identifies the protocol used by the client. */

// Adapted from Core Servlets and JavaServerPages // by Marty Hall, chapter 16 import java.net.*; import java.io.*; import java.util.StringTokenizer; public class EchoServer extends NetworkServer { protected int maxRequestLines = 50; // Post data is brought in // as a single string. protected String serverName = "EchoServer"; public static void main(String a[]) { int port = 6502; new EchoServer(port,0); // loop forever }

public EchoServer(int port, int maxConnections) { super(port,maxConnections); // call base class constructor listen(); // call base class listen() } // listen calls handleConnection() // Overrides base class handleConection and is called by listen() public void handleConnection(Socket server) throws IOException { // Assign readers and writers to the socket BufferedReader in = new BufferedReader( new InputStreamReader( server.getInputStream() )); PrintWriter out = new PrintWriter(server.getOutputStream(),true); // Announce connection to console System.out.println(serverName + " got connection from "+ server.getInetAddress().getHostName() + "\n");

String inputLines[] = new String[maxRequestLines]; int i; for(i = 0; i < maxRequestLines; i++) { inputLines[i] = in.readLine(); if(inputLines[i] == null) break; // client closed connection if(inputLines[i].length() == 0) { // blank line // maybe done or maybe post if(usingPost(inputLines)) { // readPostData reads into a single string // at location i+1 readPostData(inputLines,i,in); // i was not changed in the procedure so // bump it one past the post data string i = i + 2; } break; }

printHeader(out); for(int j = 0; j < i; j++) { out.println(inputLines[j]); } printTrailer(out); server.close(); }

private void printHeader(PrintWriter out) { out.println( "HTTP/ OK\r\n" + "Server: " + serverName + "\r\n" + "Content-Type: text/html\r\n" + “\r\n” + "<!DOCTYPE HTML PUBLIC " + "\"-//W3C//DTD HTML 4.0 Transitional//EN\">\n" + " \n" + " " + serverName + " Results \n" + " \n" + "\n" + " \n" + " " + serverName + " Results \n" + "Here is your request line and request headers\n" + "sent by your browser:\n" + " “ ); // honors whitespace }

private void printTrailer(PrintWriter out) { out.println(" \n" + " \n" + " \n"); } private boolean usingPost(String[] inputs) { return (inputs[0].toUpperCase().startsWith("POST")); }

// Read the post data as a single array of char and place it all // in one string. private void readPostData (String inputs[], int i, BufferedReader in) throws IOException { int contentLength = contentLength(inputs); char postData[] = new char[contentLength]; in.read(postData, 0, contentLength); // All of the post data is converted to a single string inputs[++i] = new String(postData,0,contentLength); }

// The header fields may arrive in any order. // Search for and return the CONTENT-LENGTH. private int contentLength(String inputs[]) { String input; for(int i = 0; i < inputs.length; i++) { if(inputs[i].length() == 0) break; input = inputs[i].toUpperCase(); if(input.startsWith("CONTENT-LENGTH")) return (getLength(input)); } return (0); } // Return the integer associated with the second token. private int getLength(String length) { StringTokenizer tok = new StringTokenizer(length); tok.nextToken(); return (Integer.parseInt(tok.nextToken())); }

PostForm.html Post Form Hi, what is your name? What is your age?

PostForm.html Browser

EchoServer Response Using POST POST data Size of Name value pairs with spaces as ‘+’ etc.

GetForm.html Get Form Hi, what is your name? What is your age?

GetForm.html Browser

EchoServer Response Using GET GET data

A Form With Checkboxes CheckBoxes Select Pizza Toppings Pepperoni Sausage Extra Cheese Mushrooms

CheckBoxes Browser

CheckBox Response Data from client

RadioBoxes HTML Radio Buttons Please Vote George W. Bush Al Gore Pat Buchanan Ralph Nader

RadioBoxes Browser

EchoServer Response

Reading Form Data With Servlets Under Jisaw // QueryData.java -- Handle the voting form in radio.html import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class QueryData extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { doGet(req, response); }

public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { String newPresident = req.getParameter("president"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"//W3C//DTD” + “HTML 4.0 "; docType += "Transitional//EN\">\n";

out.println(docType + " \n" + " Presidential Servlet" + " ” + “ \n" + " \n" + " The new president is "+ newPresident + " \n" + " "); }

Radio Buttons Please Vote George W. Bush Al Gore Pat Buchanan Ralph Nader servlet

Radio HTML in the browser

The Servlet’s Response

Handling CheckBoxes CheckBoxes Select Pizza Toppings Pepperoni Sausage Extra Cheese Mushrooms servlet

Pizza Toppings

Servlet Response

PizzaData Servlet // PizzaData.java -- Handle the toppings selection from pizza.html import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PizzaData extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { doGet(req, response); }

public void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String finalString = ""; Enumeration paramNames = req.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); finalString += paramName + ":" ; finalString += req.getParameter(paramName) + " "; }

String docType = "<!DOCTYPE HTML PUBLIC \"//W3C//DTD” + “ HTML 4.0 "; docType += "Transitional//EN\">\n"; out.println(docType + " \n" + " Pizza Selections" + " ” + “ \n" + " \n" + " " + finalString + " \n" + " "); }